1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2007 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
19 This must come before <config.h> because <config.h> may include
20 <features.h>, and once <features.h> has been included, it's too late. */
22 # define _GNU_SOURCE 1
32 # include "vasnwprintf.h"
34 # include "vasnprintf.h"
37 #include <locale.h> /* localeconv() */
38 #include <stdio.h> /* snprintf(), sprintf() */
39 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
40 #include <string.h> /* memcpy(), strlen() */
41 #include <errno.h> /* errno */
42 #include <limits.h> /* CHAR_BIT */
43 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
45 # include <langinfo.h>
48 # include "wprintf-parse.h"
50 # include "printf-parse.h"
53 /* Checked size_t computations. */
56 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
62 #if NEED_PRINTF_INFINITE_DOUBLE && !defined IN_LIBINTL
67 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !defined IN_LIBINTL
69 # include "isnanl-nolibm.h"
73 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
76 # include "printf-frexp.h"
77 # include "isnanl-nolibm.h"
78 # include "printf-frexpl.h"
82 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
84 # define EOVERFLOW E2BIG
89 # define local_wcslen wcslen
91 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
92 a dependency towards this library, here is a local substitute.
93 Define this substitute only once, even if this file is included
94 twice in the same compilation unit. */
95 # ifndef local_wcslen_defined
96 # define local_wcslen_defined 1
98 local_wcslen (const wchar_t *s)
102 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
110 #if WIDE_CHAR_VERSION
111 # define VASNPRINTF vasnwprintf
112 # define CHAR_T wchar_t
113 # define DIRECTIVE wchar_t_directive
114 # define DIRECTIVES wchar_t_directives
115 # define PRINTF_PARSE wprintf_parse
116 # define USE_SNPRINTF 1
117 # if HAVE_DECL__SNWPRINTF
118 /* On Windows, the function swprintf() has a different signature than
119 on Unix; we use the _snwprintf() function instead. */
120 # define SNPRINTF _snwprintf
123 # define SNPRINTF swprintf
126 # define VASNPRINTF vasnprintf
128 # define DIRECTIVE char_directive
129 # define DIRECTIVES char_directives
130 # define PRINTF_PARSE printf_parse
131 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
132 But don't use it on BeOS, since BeOS snprintf produces no output if the
133 size argument is >= 0x3000000. */
134 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
135 # define USE_SNPRINTF 1
137 # define USE_SNPRINTF 0
139 # if HAVE_DECL__SNPRINTF
141 # define SNPRINTF _snprintf
144 # define SNPRINTF snprintf
145 /* Here we need to call the native snprintf, not rpl_snprintf. */
149 /* Here we need to call the native sprintf, not rpl_sprintf. */
152 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
153 /* Determine the decimal-point character according to the current locale. */
154 # ifndef decimal_point_char_defined
155 # define decimal_point_char_defined 1
157 decimal_point_char ()
160 /* Determine it in a multithread-safe way. We know nl_langinfo is
161 multithread-safe on glibc systems, but is not required to be multithread-
162 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
163 is rarely multithread-safe. */
164 # if HAVE_NL_LANGINFO && __GLIBC__
165 point = nl_langinfo (RADIXCHAR);
168 sprintf (pointbuf, "%#.0f", 1.0);
169 point = &pointbuf[1];
171 point = localeconv () -> decimal_point;
173 /* The decimal point is always a single byte: either '.' or ','. */
174 return (point[0] != '\0' ? point[0] : '.');
179 #if NEED_PRINTF_INFINITE_DOUBLE && !defined IN_LIBINTL
181 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
183 is_infinite_or_zero (double x)
185 return isnan (x) || x + x == x;
190 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !defined IN_LIBINTL
192 /* Equivalent to !isfinite(x), but does not require libm. */
194 is_infinitel (long double x)
196 return isnanl (x) || (x + x == x && x != 0.0L);
201 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
203 /* Converting 'long double' to decimal without rare rounding bugs requires
204 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
205 (and slower) algorithms. */
207 typedef unsigned int mp_limb_t;
208 # define GMP_LIMB_BITS 32
209 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
211 typedef unsigned long long mp_twolimb_t;
212 # define GMP_TWOLIMB_BITS 64
213 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
215 /* Representation of a bignum >= 0. */
219 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
222 /* Compute the product of two bignums >= 0.
223 Return the allocated memory in case of success, NULL in case of memory
224 allocation failure. */
226 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
233 if (src1.nlimbs <= src2.nlimbs)
247 /* Now 0 <= len1 <= len2. */
250 /* src1 or src2 is zero. */
252 dest->limbs = (mp_limb_t *) malloc (1);
256 /* Here 1 <= len1 <= len2. */
262 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
265 for (k = len2; k > 0; )
267 for (i = 0; i < len1; i++)
269 mp_limb_t digit1 = p1[i];
270 mp_twolimb_t carry = 0;
271 for (j = 0; j < len2; j++)
273 mp_limb_t digit2 = p2[j];
274 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
276 dp[i + j] = (mp_limb_t) carry;
277 carry = carry >> GMP_LIMB_BITS;
279 dp[i + len2] = (mp_limb_t) carry;
282 while (dlen > 0 && dp[dlen - 1] == 0)
290 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
291 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
293 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
295 Return the allocated memory in case of success, NULL in case of memory
296 allocation failure. */
298 divide (mpn_t a, mpn_t b, mpn_t *q)
301 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
302 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
303 If m<n, then q:=0 and r:=a.
304 If m>=n=1, perform a single-precision division:
307 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
308 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
309 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
310 Normalise [q[m-1],...,q[0]], yields q.
311 If m>=n>1, perform a multiple-precision division:
312 We have a/b < beta^(m-n+1).
313 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
314 Shift a and b left by s bits, copying them. r:=a.
315 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
316 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
318 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
319 In case of overflow (q* >= beta) set q* := beta-1.
320 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
321 and c3 := b[n-2] * q*.
322 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
323 occurred. Furthermore 0 <= c3 < beta^2.
324 If there was overflow and
325 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
326 the next test can be skipped.}
327 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
328 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
330 Put r := r - b * q* * beta^j. In detail:
331 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
332 hence: u:=0, for i:=0 to n-1 do
334 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
335 u:=u div beta (+ 1, if carry in subtraction)
337 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
339 the carry u does not overflow.}
340 If a negative carry occurs, put q* := q* - 1
341 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
343 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
344 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
346 The room for q[j] can be allocated at the memory location of r[n+j].
347 Finally, round-to-even:
348 Shift r left by 1 bit.
349 If r > b or if r = b and q[0] is odd, q := q+1.
351 const mp_limb_t *a_ptr = a.limbs;
352 size_t a_len = a.nlimbs;
353 const mp_limb_t *b_ptr = b.limbs;
354 size_t b_len = b.nlimbs;
356 mp_limb_t *tmp_roomptr = NULL;
362 /* Allocate room for a_len+2 digits.
363 (Need a_len+1 digits for the real division and 1 more digit for the
364 final rounding of q.) */
365 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
370 while (a_len > 0 && a_ptr[a_len - 1] == 0)
377 /* Division by zero. */
379 if (b_ptr[b_len - 1] == 0)
385 /* Here m = a_len >= 0 and n = b_len > 0. */
389 /* m<n: trivial case. q=0, r := copy of a. */
392 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
393 q_ptr = roomptr + a_len;
398 /* n=1: single precision division.
399 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
403 mp_limb_t den = b_ptr[0];
404 mp_limb_t remainder = 0;
405 const mp_limb_t *sourceptr = a_ptr + a_len;
406 mp_limb_t *destptr = q_ptr + a_len;
408 for (count = a_len; count > 0; count--)
411 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
412 *--destptr = num / den;
413 remainder = num % den;
415 /* Normalise and store r. */
418 r_ptr[0] = remainder;
425 if (q_ptr[q_len - 1] == 0)
431 /* n>1: multiple precision division.
432 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
433 beta^(m-n-1) <= a/b < beta^(m-n+1). */
437 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
465 /* 0 <= s < GMP_LIMB_BITS.
466 Copy b, shifting it left by s bits. */
469 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
470 if (tmp_roomptr == NULL)
476 const mp_limb_t *sourceptr = b_ptr;
477 mp_limb_t *destptr = tmp_roomptr;
478 mp_twolimb_t accu = 0;
480 for (count = b_len; count > 0; count--)
482 accu += (mp_twolimb_t) *sourceptr++ << s;
483 *destptr++ = (mp_limb_t) accu;
484 accu = accu >> GMP_LIMB_BITS;
486 /* accu must be zero, since that was how s was determined. */
492 /* Copy a, shifting it left by s bits, yields r.
494 At the beginning: r = roomptr[0..a_len],
495 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
499 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
504 const mp_limb_t *sourceptr = a_ptr;
505 mp_limb_t *destptr = r_ptr;
506 mp_twolimb_t accu = 0;
508 for (count = a_len; count > 0; count--)
510 accu += (mp_twolimb_t) *sourceptr++ << s;
511 *destptr++ = (mp_limb_t) accu;
512 accu = accu >> GMP_LIMB_BITS;
514 *destptr++ = (mp_limb_t) accu;
516 q_ptr = roomptr + b_len;
517 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
519 size_t j = a_len - b_len; /* m-n */
520 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
521 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
522 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
523 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
524 /* Division loop, traversed m-n+1 times.
525 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
530 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
532 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
534 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
535 | r_ptr[j + b_len - 1];
536 q_star = num / b_msd;
541 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
542 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
543 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
544 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
545 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
547 If yes, jump directly to the subtraction loop.
548 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
549 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
550 if (r_ptr[j + b_len] > b_msd
551 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
552 /* r[j+n] >= b[n-1]+1 or
553 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
558 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
560 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
561 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
562 mp_twolimb_t c3 = /* b[n-2] * q* */
563 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
564 /* While c2 < c3, increase c2 and decrease c3.
565 Consider c3-c2. While it is > 0, decrease it by
566 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
567 this can happen only twice. */
570 q_star = q_star - 1; /* q* := q* - 1 */
571 if (c3 - c2 > b_msdd)
572 q_star = q_star - 1; /* q* := q* - 1 */
578 /* Subtract r := r - b * q* * beta^j. */
581 const mp_limb_t *sourceptr = b_ptr;
582 mp_limb_t *destptr = r_ptr + j;
583 mp_twolimb_t carry = 0;
585 for (count = b_len; count > 0; count--)
587 /* Here 0 <= carry <= q*. */
590 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
591 + (mp_limb_t) ~(*destptr);
592 /* Here 0 <= carry <= beta*q* + beta-1. */
593 *destptr++ = ~(mp_limb_t) carry;
594 carry = carry >> GMP_LIMB_BITS; /* <= q* */
596 cr = (mp_limb_t) carry;
598 /* Subtract cr from r_ptr[j + b_len], then forget about
600 if (cr > r_ptr[j + b_len])
602 /* Subtraction gave a carry. */
603 q_star = q_star - 1; /* q* := q* - 1 */
606 const mp_limb_t *sourceptr = b_ptr;
607 mp_limb_t *destptr = r_ptr + j;
610 for (count = b_len; count > 0; count--)
612 mp_limb_t source1 = *sourceptr++;
613 mp_limb_t source2 = *destptr;
614 *destptr++ = source1 + source2 + carry;
617 ? source1 >= (mp_limb_t) ~source2
618 : source1 > (mp_limb_t) ~source2);
621 /* Forget about the carry and about r[j+n]. */
624 /* q* is determined. Store it as q[j]. */
633 if (q_ptr[q_len - 1] == 0)
635 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
636 b is shifted left by s bits. */
637 /* Shift r right by s bits. */
640 mp_limb_t ptr = r_ptr + r_len;
641 mp_twolimb_t accu = 0;
643 for (count = r_len; count > 0; count--)
645 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
646 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
647 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
652 while (r_len > 0 && r_ptr[r_len - 1] == 0)
655 /* Compare r << 1 with b. */
663 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
664 | (i < r_len ? r_ptr[i] << 1 : 0);
665 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
675 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
680 for (i = 0; i < q_len; i++)
681 if (++(q_ptr[i]) != 0)
686 if (tmp_roomptr != NULL)
693 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
695 Destroys the contents of a.
696 Return the allocated memory - containing the decimal digits in low-to-high
697 order, terminated with a NUL character - in case of success, NULL in case
698 of memory allocation failure. */
700 convert_to_decimal (mpn_t a, size_t extra_zeroes)
702 mp_limb_t *a_ptr = a.limbs;
703 size_t a_len = a.nlimbs;
704 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
705 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
706 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
710 for (; extra_zeroes > 0; extra_zeroes--)
714 /* Divide a by 10^9, in-place. */
715 mp_limb_t remainder = 0;
716 mp_limb_t *ptr = a_ptr + a_len;
718 for (count = a_len; count > 0; count--)
721 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
722 *ptr = num / 1000000000;
723 remainder = num % 1000000000;
725 /* Store the remainder as 9 decimal digits. */
726 for (count = 9; count > 0; count--)
728 *d_ptr++ = '0' + (remainder % 10);
729 remainder = remainder / 10;
732 if (a_ptr[a_len - 1] == 0)
735 /* Remove leading zeroes. */
736 while (d_ptr > c_ptr && d_ptr[-1] == '0')
738 /* But keep at least one zero. */
741 /* Terminate the string. */
747 /* Assuming x is finite and >= 0:
748 write x as x = 2^e * m, where m is a bignum.
749 Return the allocated memory in case of success, NULL in case of memory
750 allocation failure. */
752 decode_long_double (long double x, int *ep, mpn_t *mp)
759 /* Allocate memory for result. */
760 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
761 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
764 /* Split into exponential part and mantissa. */
765 y = frexpl (x, &exp);
766 if (!(y >= 0.0L && y < 1.0L))
768 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
769 latter is an integer. */
770 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
771 I'm not sure whether it's safe to cast a 'long double' value between
772 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
773 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
775 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
776 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
779 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
782 if (!(y >= 0.0L && y < 1.0L))
784 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
787 if (!(y >= 0.0L && y < 1.0L))
789 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
794 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
797 if (!(y >= 0.0L && y < 1.0L))
799 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
803 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
806 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
809 if (!(y >= 0.0L && y < 1.0L))
811 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
814 if (!(y >= 0.0L && y < 1.0L))
816 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
821 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
824 *ep = exp - LDBL_MANT_BIT;
828 /* Assuming x is finite and >= 0, and n is an integer:
829 Returns the decimal representation of round (x * 10^n).
830 Return the allocated memory - containing the decimal digits in low-to-high
831 order, terminated with a NUL character - in case of success, NULL in case
832 of memory allocation failure. */
834 scale10_round_decimal_long_double (long double x, int n)
838 void *memory = decode_long_double (x, &e, &m);
845 unsigned int s_limbs;
854 /* x = 2^e * m, hence
855 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
856 = round (2^s * 5^n * m). */
859 /* Factor out a common power of 10 if possible. */
862 extra_zeroes = (s < n ? s : n);
866 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
867 Before converting to decimal, we need to compute
868 z = round (2^s * 5^n * m). */
869 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
870 sign. 2.322 is slightly larger than log(5)/log(2). */
871 abs_n = (n >= 0 ? n : -n);
872 abs_s = (s >= 0 ? s : -s);
873 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
874 + abs_s / GMP_LIMB_BITS + 1)
875 * sizeof (mp_limb_t));
876 if (pow5_ptr == NULL)
881 /* Initialize with 1. */
884 /* Multiply with 5^|n|. */
887 static mp_limb_t const small_pow5[13 + 1] =
889 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
890 48828125, 244140625, 1220703125
893 for (n13 = 0; n13 <= abs_n; n13 += 13)
895 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
897 mp_twolimb_t carry = 0;
898 for (j = 0; j < pow5_len; j++)
900 mp_limb_t digit2 = pow5_ptr[j];
901 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
902 pow5_ptr[j] = (mp_limb_t) carry;
903 carry = carry >> GMP_LIMB_BITS;
906 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
909 s_limbs = abs_s / GMP_LIMB_BITS;
910 s_bits = abs_s % GMP_LIMB_BITS;
911 if (n >= 0 ? s >= 0 : s <= 0)
913 /* Multiply with 2^|s|. */
916 mp_limb_t *ptr = pow5_ptr;
917 mp_twolimb_t accu = 0;
919 for (count = pow5_len; count > 0; count--)
921 accu += (mp_twolimb_t) *ptr << s_bits;
922 *ptr++ = (mp_limb_t) accu;
923 accu = accu >> GMP_LIMB_BITS;
927 *ptr = (mp_limb_t) accu;
934 for (count = pow5_len; count > 0;)
937 pow5_ptr[s_limbs + count] = pow5_ptr[count];
939 for (count = s_limbs; count > 0;)
946 pow5.limbs = pow5_ptr;
947 pow5.nlimbs = pow5_len;
950 /* Multiply m with pow5. No division needed. */
951 z_memory = multiply (m, pow5, &z);
955 /* Divide m by pow5 and round. */
956 z_memory = divide (m, pow5, &z);
961 pow5.limbs = pow5_ptr;
962 pow5.nlimbs = pow5_len;
966 Multiply m with pow5, then divide by 2^|s|. */
970 tmp_memory = multiply (m, pow5, &numerator);
971 if (tmp_memory == NULL)
977 /* Construct 2^|s|. */
979 mp_limb_t *ptr = pow5_ptr + pow5_len;
981 for (i = 0; i < s_limbs; i++)
983 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
984 denominator.limbs = ptr;
985 denominator.nlimbs = s_limbs + 1;
987 z_memory = divide (numerator, denominator, &z);
993 Multiply m with 2^s, then divide by pow5. */
996 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
997 * sizeof (mp_limb_t));
1005 mp_limb_t *destptr = num_ptr;
1008 for (i = 0; i < s_limbs; i++)
1013 const mp_limb_t *sourceptr = m.limbs;
1014 mp_twolimb_t accu = 0;
1016 for (count = m.nlimbs; count > 0; count--)
1018 accu += (mp_twolimb_t) *sourceptr++ << s;
1019 *destptr++ = (mp_limb_t) accu;
1020 accu = accu >> GMP_LIMB_BITS;
1023 *destptr++ = (mp_limb_t) accu;
1027 const mp_limb_t *sourceptr = m.limbs;
1029 for (count = m.nlimbs; count > 0; count--)
1030 *destptr++ = *sourceptr++;
1032 numerator.limbs = num_ptr;
1033 numerator.nlimbs = destptr - num_ptr;
1035 z_memory = divide (numerator, pow5, &z);
1042 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1044 if (z_memory == NULL)
1046 digits = convert_to_decimal (z, extra_zeroes);
1051 /* Assuming x is finite and > 0:
1052 Return an approximation for n with 10^n <= x < 10^(n+1).
1053 The approximation is usually the right n, but may be off by 1 sometimes. */
1055 floorlog10l (long double x)
1062 /* Split into exponential part and mantissa. */
1063 y = frexpl (x, &exp);
1064 if (!(y >= 0.0L && y < 1.0L))
1070 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1072 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1073 exp -= GMP_LIMB_BITS;
1075 if (y < (1.0L / (1 << 16)))
1077 y *= 1.0L * (1 << 16);
1080 if (y < (1.0L / (1 << 8)))
1082 y *= 1.0L * (1 << 8);
1085 if (y < (1.0L / (1 << 4)))
1087 y *= 1.0L * (1 << 4);
1090 if (y < (1.0L / (1 << 2)))
1092 y *= 1.0L * (1 << 2);
1095 if (y < (1.0L / (1 << 1)))
1097 y *= 1.0L * (1 << 1);
1101 if (!(y >= 0.5L && y < 1.0L))
1103 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1106 if (z < 0.70710678118654752444)
1108 z *= 1.4142135623730950488;
1111 if (z < 0.8408964152537145431)
1113 z *= 1.1892071150027210667;
1116 if (z < 0.91700404320467123175)
1118 z *= 1.0905077326652576592;
1121 if (z < 0.9576032806985736469)
1123 z *= 1.0442737824274138403;
1126 /* Now 0.95 <= z <= 1.01. */
1128 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1129 Four terms are enough to get an approximation with error < 10^-7. */
1130 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1131 /* Finally multiply with log(2)/log(10), yields an approximation for
1133 l *= 0.30102999566398119523;
1134 /* Round down to the next integer. */
1135 return (int) l + (l < 0 ? -1 : 0);
1141 VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list args)
1146 if (PRINTF_PARSE (format, &d, &a) < 0)
1157 if (printf_fetchargs (args, &a) < 0)
1165 size_t buf_neededlength;
1167 CHAR_T *buf_malloced;
1171 /* Output string accumulator. */
1176 /* Allocate a small buffer that will hold a directive passed to
1177 sprintf or snprintf. */
1179 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1181 if (buf_neededlength < 4000 / sizeof (CHAR_T))
1183 buf = (CHAR_T *) alloca (buf_neededlength * sizeof (CHAR_T));
1184 buf_malloced = NULL;
1189 size_t buf_memsize = xtimes (buf_neededlength, sizeof (CHAR_T));
1190 if (size_overflow_p (buf_memsize))
1191 goto out_of_memory_1;
1192 buf = (CHAR_T *) malloc (buf_memsize);
1194 goto out_of_memory_1;
1198 if (resultbuf != NULL)
1201 allocated = *lengthp;
1210 result is either == resultbuf or == NULL or malloc-allocated.
1211 If length > 0, then result != NULL. */
1213 /* Ensures that allocated >= needed. Aborts through a jump to
1214 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1215 #define ENSURE_ALLOCATION(needed) \
1216 if ((needed) > allocated) \
1218 size_t memory_size; \
1221 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1222 if ((needed) > allocated) \
1223 allocated = (needed); \
1224 memory_size = xtimes (allocated, sizeof (CHAR_T)); \
1225 if (size_overflow_p (memory_size)) \
1226 goto out_of_memory; \
1227 if (result == resultbuf || result == NULL) \
1228 memory = (CHAR_T *) malloc (memory_size); \
1230 memory = (CHAR_T *) realloc (result, memory_size); \
1231 if (memory == NULL) \
1232 goto out_of_memory; \
1233 if (result == resultbuf && length > 0) \
1234 memcpy (memory, result, length * sizeof (CHAR_T)); \
1238 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1240 if (cp != dp->dir_start)
1242 size_t n = dp->dir_start - cp;
1243 size_t augmented_length = xsum (length, n);
1245 ENSURE_ALLOCATION (augmented_length);
1246 memcpy (result + length, cp, n * sizeof (CHAR_T));
1247 length = augmented_length;
1252 /* Execute a single directive. */
1253 if (dp->conversion == '%')
1255 size_t augmented_length;
1257 if (!(dp->arg_index == ARG_NONE))
1259 augmented_length = xsum (length, 1);
1260 ENSURE_ALLOCATION (augmented_length);
1261 result[length] = '%';
1262 length = augmented_length;
1266 if (!(dp->arg_index != ARG_NONE))
1269 if (dp->conversion == 'n')
1271 switch (a.arg[dp->arg_index].type)
1273 case TYPE_COUNT_SCHAR_POINTER:
1274 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1276 case TYPE_COUNT_SHORT_POINTER:
1277 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1279 case TYPE_COUNT_INT_POINTER:
1280 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1282 case TYPE_COUNT_LONGINT_POINTER:
1283 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1285 #if HAVE_LONG_LONG_INT
1286 case TYPE_COUNT_LONGLONGINT_POINTER:
1287 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1294 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
1295 else if (dp->conversion == 'a' || dp->conversion == 'A')
1297 arg_type type = a.arg[dp->arg_index].type;
1298 int flags = dp->flags;
1311 if (dp->width_start != dp->width_end)
1313 if (dp->width_arg_index != ARG_NONE)
1317 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1319 arg = a.arg[dp->width_arg_index].a.a_int;
1322 /* "A negative field width is taken as a '-' flag
1323 followed by a positive field width." */
1325 width = (unsigned int) (-arg);
1332 const CHAR_T *digitp = dp->width_start;
1335 width = xsum (xtimes (width, 10), *digitp++ - '0');
1336 while (digitp != dp->width_end);
1343 if (dp->precision_start != dp->precision_end)
1345 if (dp->precision_arg_index != ARG_NONE)
1349 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1351 arg = a.arg[dp->precision_arg_index].a.a_int;
1352 /* "A negative precision is taken as if the precision
1362 const CHAR_T *digitp = dp->precision_start + 1;
1365 while (digitp != dp->precision_end)
1366 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1371 /* Allocate a temporary buffer of sufficient size. */
1372 if (type == TYPE_LONGDOUBLE)
1374 (unsigned int) ((LDBL_DIG + 1)
1375 * 0.831 /* decimal -> hexadecimal */
1377 + 1; /* turn floor into ceil */
1380 (unsigned int) ((DBL_DIG + 1)
1381 * 0.831 /* decimal -> hexadecimal */
1383 + 1; /* turn floor into ceil */
1384 if (tmp_length < precision)
1385 tmp_length = precision;
1386 /* Account for sign, decimal point etc. */
1387 tmp_length = xsum (tmp_length, 12);
1389 if (tmp_length < width)
1392 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1394 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1398 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1400 if (size_overflow_p (tmp_memsize))
1401 /* Overflow, would lead to out of memory. */
1403 tmp = (CHAR_T *) malloc (tmp_memsize);
1405 /* Out of memory. */
1411 if (type == TYPE_LONGDOUBLE)
1413 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1417 if (dp->conversion == 'A')
1419 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1423 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1429 DECL_LONG_DOUBLE_ROUNDING
1431 BEGIN_LONG_DOUBLE_ROUNDING ();
1433 if (signbit (arg)) /* arg < 0.0L or negative zero */
1441 else if (flags & FLAG_SHOWSIGN)
1443 else if (flags & FLAG_SPACE)
1446 if (arg > 0.0L && arg + arg == arg)
1448 if (dp->conversion == 'A')
1450 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1454 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1460 long double mantissa;
1463 mantissa = printf_frexpl (arg, &exponent);
1471 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
1473 /* Round the mantissa. */
1474 long double tail = mantissa;
1477 for (q = precision; ; q--)
1479 int digit = (int) tail;
1483 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
1492 for (q = precision; q > 0; q--)
1498 *p++ = dp->conversion - 'A' + 'X';
1503 digit = (int) mantissa;
1506 if ((flags & FLAG_ALT)
1507 || mantissa > 0.0L || precision > 0)
1509 *p++ = decimal_point_char ();
1510 /* This loop terminates because we assume
1511 that FLT_RADIX is a power of 2. */
1512 while (mantissa > 0.0L)
1515 digit = (int) mantissa;
1520 : dp->conversion - 10);
1524 while (precision > 0)
1531 *p++ = dp->conversion - 'A' + 'P';
1532 # if WIDE_CHAR_VERSION
1534 static const wchar_t decimal_format[] =
1535 { '%', '+', 'd', '\0' };
1536 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1539 sprintf (p, "%+d", exponent);
1545 END_LONG_DOUBLE_ROUNDING ();
1550 double arg = a.arg[dp->arg_index].a.a_double;
1554 if (dp->conversion == 'A')
1556 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1560 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1567 if (signbit (arg)) /* arg < 0.0 or negative zero */
1575 else if (flags & FLAG_SHOWSIGN)
1577 else if (flags & FLAG_SPACE)
1580 if (arg > 0.0 && arg + arg == arg)
1582 if (dp->conversion == 'A')
1584 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1588 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1597 mantissa = printf_frexp (arg, &exponent);
1605 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
1607 /* Round the mantissa. */
1608 double tail = mantissa;
1611 for (q = precision; ; q--)
1613 int digit = (int) tail;
1617 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
1626 for (q = precision; q > 0; q--)
1632 *p++ = dp->conversion - 'A' + 'X';
1637 digit = (int) mantissa;
1640 if ((flags & FLAG_ALT)
1641 || mantissa > 0.0 || precision > 0)
1643 *p++ = decimal_point_char ();
1644 /* This loop terminates because we assume
1645 that FLT_RADIX is a power of 2. */
1646 while (mantissa > 0.0)
1649 digit = (int) mantissa;
1654 : dp->conversion - 10);
1658 while (precision > 0)
1665 *p++ = dp->conversion - 'A' + 'P';
1666 # if WIDE_CHAR_VERSION
1668 static const wchar_t decimal_format[] =
1669 { '%', '+', 'd', '\0' };
1670 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1673 sprintf (p, "%+d", exponent);
1680 /* The generated string now extends from tmp to p, with the
1681 zero padding insertion point being at pad_ptr. */
1682 if (has_width && p - tmp < width)
1684 size_t pad = width - (p - tmp);
1685 CHAR_T *end = p + pad;
1687 if (flags & FLAG_LEFT)
1689 /* Pad with spaces on the right. */
1690 for (; pad > 0; pad--)
1693 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
1695 /* Pad with zeroes. */
1700 for (; pad > 0; pad--)
1705 /* Pad with spaces on the left. */
1710 for (; pad > 0; pad--)
1718 size_t count = p - tmp;
1720 if (count >= tmp_length)
1721 /* tmp_length was incorrectly calculated - fix the
1725 /* Make room for the result. */
1726 if (count >= allocated - length)
1728 size_t n = xsum (length, count);
1730 ENSURE_ALLOCATION (n);
1733 /* Append the result. */
1734 memcpy (result + length, tmp, count * sizeof (CHAR_T));
1741 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
1742 else if ((dp->conversion == 'f' || dp->conversion == 'F'
1743 || dp->conversion == 'e' || dp->conversion == 'E'
1744 || dp->conversion == 'g' || dp->conversion == 'G'
1745 || dp->conversion == 'a' || dp->conversion == 'A')
1747 # if NEED_PRINTF_INFINITE_DOUBLE
1748 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
1749 /* The systems (mingw) which produce wrong output
1750 for Inf, -Inf, and NaN also do so for -0.0.
1751 Therefore we treat this case here as well. */
1752 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
1754 # if NEED_PRINTF_LONG_DOUBLE
1755 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
1756 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
1757 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
1758 /* Some systems produce wrong output for Inf,
1760 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
1764 # if NEED_PRINTF_INFINITE_DOUBLE && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
1765 arg_type type = a.arg[dp->arg_index].type;
1767 int flags = dp->flags;
1780 if (dp->width_start != dp->width_end)
1782 if (dp->width_arg_index != ARG_NONE)
1786 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1788 arg = a.arg[dp->width_arg_index].a.a_int;
1791 /* "A negative field width is taken as a '-' flag
1792 followed by a positive field width." */
1794 width = (unsigned int) (-arg);
1801 const CHAR_T *digitp = dp->width_start;
1804 width = xsum (xtimes (width, 10), *digitp++ - '0');
1805 while (digitp != dp->width_end);
1812 if (dp->precision_start != dp->precision_end)
1814 if (dp->precision_arg_index != ARG_NONE)
1818 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1820 arg = a.arg[dp->precision_arg_index].a.a_int;
1821 /* "A negative precision is taken as if the precision
1831 const CHAR_T *digitp = dp->precision_start + 1;
1834 while (digitp != dp->precision_end)
1835 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1840 /* POSIX specifies the default precision to be 6 for %f, %F,
1841 %e, %E, but not for %g, %G. Implementations appear to use
1842 the same default precision also for %g, %G. */
1846 /* Allocate a temporary buffer of sufficient size. */
1847 # if NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
1848 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
1849 # elif NEED_PRINTF_LONG_DOUBLE
1850 tmp_length = LDBL_DIG + 1;
1854 if (tmp_length < precision)
1855 tmp_length = precision;
1856 # if NEED_PRINTF_LONG_DOUBLE
1857 # if NEED_PRINTF_INFINITE_DOUBLE
1858 if (type == TYPE_LONGDOUBLE)
1860 if (dp->conversion == 'f' || dp->conversion == 'F')
1862 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1863 if (!(isnanl (arg) || arg + arg == arg))
1865 /* arg is finite and nonzero. */
1866 int exponent = floorlog10l (arg < 0 ? -arg : arg);
1867 if (exponent >= 0 && tmp_length < exponent + precision)
1868 tmp_length = exponent + precision;
1872 /* Account for sign, decimal point etc. */
1873 tmp_length = xsum (tmp_length, 12);
1875 if (tmp_length < width)
1878 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1880 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1884 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1886 if (size_overflow_p (tmp_memsize))
1887 /* Overflow, would lead to out of memory. */
1889 tmp = (CHAR_T *) malloc (tmp_memsize);
1891 /* Out of memory. */
1898 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
1899 # if NEED_PRINTF_INFINITE_DOUBLE
1900 if (type == TYPE_LONGDOUBLE)
1903 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1907 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1909 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1913 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1919 DECL_LONG_DOUBLE_ROUNDING
1921 BEGIN_LONG_DOUBLE_ROUNDING ();
1923 if (signbit (arg)) /* arg < 0.0L or negative zero */
1931 else if (flags & FLAG_SHOWSIGN)
1933 else if (flags & FLAG_SPACE)
1936 if (arg > 0.0L && arg + arg == arg)
1938 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1940 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1944 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1949 # if NEED_PRINTF_LONG_DOUBLE
1952 if (dp->conversion == 'f' || dp->conversion == 'F')
1958 scale10_round_decimal_long_double (arg, precision);
1961 END_LONG_DOUBLE_ROUNDING ();
1964 ndigits = strlen (digits);
1966 if (ndigits > precision)
1970 *p++ = digits[ndigits];
1972 while (ndigits > precision);
1975 /* Here ndigits <= precision. */
1976 if ((flags & FLAG_ALT) || precision > 0)
1978 *p++ = decimal_point_char ();
1979 for (; precision > ndigits; precision--)
1984 *p++ = digits[ndigits];
1990 else if (dp->conversion == 'e' || dp->conversion == 'E')
1998 if ((flags & FLAG_ALT) || precision > 0)
2000 *p++ = decimal_point_char ();
2001 for (; precision > 0; precision--)
2012 exponent = floorlog10l (arg);
2017 scale10_round_decimal_long_double (arg,
2018 (int)precision - exponent);
2021 END_LONG_DOUBLE_ROUNDING ();
2024 ndigits = strlen (digits);
2026 if (ndigits == precision + 1)
2028 if (ndigits < precision
2029 || ndigits > precision + 2)
2030 /* The exponent was not guessed
2031 precisely enough. */
2034 /* None of two values of exponent is
2035 the right one. Prevent an endless
2039 if (ndigits == precision)
2046 /* Here ndigits = precision+1. */
2047 *p++ = digits[--ndigits];
2048 if ((flags & FLAG_ALT) || precision > 0)
2050 *p++ = decimal_point_char ();
2054 *p++ = digits[ndigits];
2061 *p++ = dp->conversion; /* 'e' or 'E' */
2062 # if WIDE_CHAR_VERSION
2064 static const wchar_t decimal_format[] =
2065 { '%', '+', '.', '2', 'd', '\0' };
2066 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2069 sprintf (p, "%+.2d", exponent);
2074 else if (dp->conversion == 'g' || dp->conversion == 'G')
2078 /* precision >= 1. */
2081 /* The exponent is 0, >= -4, < precision.
2082 Use fixed-point notation. */
2084 size_t ndigits = precision;
2085 /* Number of trailing zeroes that have to be
2088 (flags & FLAG_ALT ? 0 : precision - 1);
2092 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2094 *p++ = decimal_point_char ();
2095 while (ndigits > nzeroes)
2111 exponent = floorlog10l (arg);
2116 scale10_round_decimal_long_double (arg,
2117 (int)(precision - 1) - exponent);
2120 END_LONG_DOUBLE_ROUNDING ();
2123 ndigits = strlen (digits);
2125 if (ndigits == precision)
2127 if (ndigits < precision - 1
2128 || ndigits > precision + 1)
2129 /* The exponent was not guessed
2130 precisely enough. */
2133 /* None of two values of exponent is
2134 the right one. Prevent an endless
2138 if (ndigits < precision)
2144 /* Here ndigits = precision. */
2146 /* Determine the number of trailing zeroes
2147 that have to be dropped. */
2149 if ((flags & FLAG_ALT) == 0)
2150 while (nzeroes < ndigits
2151 && digits[nzeroes] == '0')
2154 /* The exponent is now determined. */
2156 && exponent < (long)precision)
2158 /* Fixed-point notation:
2159 max(exponent,0)+1 digits, then the
2160 decimal point, then the remaining
2161 digits without trailing zeroes. */
2164 size_t count = exponent + 1;
2165 /* Note: count <= precision = ndigits. */
2166 for (; count > 0; count--)
2167 *p++ = digits[--ndigits];
2168 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2170 *p++ = decimal_point_char ();
2171 while (ndigits > nzeroes)
2174 *p++ = digits[ndigits];
2180 size_t count = -exponent - 1;
2182 *p++ = decimal_point_char ();
2183 for (; count > 0; count--)
2185 while (ndigits > nzeroes)
2188 *p++ = digits[ndigits];
2194 /* Exponential notation. */
2195 *p++ = digits[--ndigits];
2196 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2198 *p++ = decimal_point_char ();
2199 while (ndigits > nzeroes)
2202 *p++ = digits[ndigits];
2205 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
2206 # if WIDE_CHAR_VERSION
2208 static const wchar_t decimal_format[] =
2209 { '%', '+', '.', '2', 'd', '\0' };
2210 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2213 sprintf (p, "%+.2d", exponent);
2225 /* arg is finite. */
2230 END_LONG_DOUBLE_ROUNDING ();
2233 # if NEED_PRINTF_INFINITE_DOUBLE
2237 # if NEED_PRINTF_INFINITE_DOUBLE
2239 /* Simpler than above: handle only NaN, Infinity, zero. */
2240 double arg = a.arg[dp->arg_index].a.a_double;
2244 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2246 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2250 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2257 if (signbit (arg)) /* arg < 0.0L or negative zero */
2265 else if (flags & FLAG_SHOWSIGN)
2267 else if (flags & FLAG_SPACE)
2270 if (arg > 0.0 && arg + arg == arg)
2272 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2274 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2278 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2288 if (dp->conversion == 'f' || dp->conversion == 'F')
2291 if ((flags & FLAG_ALT) || precision > 0)
2293 *p++ = decimal_point_char ();
2294 for (; precision > 0; precision--)
2298 else if (dp->conversion == 'e' || dp->conversion == 'E')
2301 if ((flags & FLAG_ALT) || precision > 0)
2303 *p++ = decimal_point_char ();
2304 for (; precision > 0; precision--)
2307 *p++ = dp->conversion; /* 'e' or 'E' */
2309 /* Produce the same number of exponent digits as
2310 the native printf implementation. */
2311 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2317 else if (dp->conversion == 'g' || dp->conversion == 'G')
2320 if (flags & FLAG_ALT)
2323 (precision > 0 ? precision - 1 : 0);
2324 *p++ = decimal_point_char ();
2325 for (; ndigits > 0; --ndigits)
2336 /* The generated string now extends from tmp to p, with the
2337 zero padding insertion point being at pad_ptr. */
2338 if (has_width && p - tmp < width)
2340 size_t pad = width - (p - tmp);
2341 CHAR_T *end = p + pad;
2343 if (flags & FLAG_LEFT)
2345 /* Pad with spaces on the right. */
2346 for (; pad > 0; pad--)
2349 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2351 /* Pad with zeroes. */
2356 for (; pad > 0; pad--)
2361 /* Pad with spaces on the left. */
2366 for (; pad > 0; pad--)
2374 size_t count = p - tmp;
2376 if (count >= tmp_length)
2377 /* tmp_length was incorrectly calculated - fix the
2381 /* Make room for the result. */
2382 if (count >= allocated - length)
2384 size_t n = xsum (length, count);
2386 ENSURE_ALLOCATION (n);
2389 /* Append the result. */
2390 memcpy (result + length, tmp, count * sizeof (CHAR_T));
2399 arg_type type = a.arg[dp->arg_index].type;
2400 int flags = dp->flags;
2401 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2405 #if NEED_PRINTF_FLAG_ZERO
2408 # define pad_ourselves 0
2411 unsigned int prefix_count;
2419 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2422 if (dp->width_start != dp->width_end)
2424 if (dp->width_arg_index != ARG_NONE)
2428 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2430 arg = a.arg[dp->width_arg_index].a.a_int;
2433 /* "A negative field width is taken as a '-' flag
2434 followed by a positive field width." */
2436 width = (unsigned int) (-arg);
2443 const CHAR_T *digitp = dp->width_start;
2446 width = xsum (xtimes (width, 10), *digitp++ - '0');
2447 while (digitp != dp->width_end);
2454 /* Allocate a temporary buffer of sufficient size for calling
2460 if (dp->precision_start != dp->precision_end)
2462 if (dp->precision_arg_index != ARG_NONE)
2466 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2468 arg = a.arg[dp->precision_arg_index].a.a_int;
2469 precision = (arg < 0 ? 0 : arg);
2473 const CHAR_T *digitp = dp->precision_start + 1;
2476 while (digitp != dp->precision_end)
2477 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2481 switch (dp->conversion)
2484 case 'd': case 'i': case 'u':
2485 # if HAVE_LONG_LONG_INT
2486 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2488 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2489 * 0.30103 /* binary -> decimal */
2491 + 1; /* turn floor into ceil */
2494 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2496 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2497 * 0.30103 /* binary -> decimal */
2499 + 1; /* turn floor into ceil */
2502 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2503 * 0.30103 /* binary -> decimal */
2505 + 1; /* turn floor into ceil */
2506 if (tmp_length < precision)
2507 tmp_length = precision;
2508 /* Multiply by 2, as an estimate for FLAG_GROUP. */
2509 tmp_length = xsum (tmp_length, tmp_length);
2510 /* Add 1, to account for a leading sign. */
2511 tmp_length = xsum (tmp_length, 1);
2515 # if HAVE_LONG_LONG_INT
2516 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2518 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2519 * 0.333334 /* binary -> octal */
2521 + 1; /* turn floor into ceil */
2524 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2526 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2527 * 0.333334 /* binary -> octal */
2529 + 1; /* turn floor into ceil */
2532 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2533 * 0.333334 /* binary -> octal */
2535 + 1; /* turn floor into ceil */
2536 if (tmp_length < precision)
2537 tmp_length = precision;
2538 /* Add 1, to account for a leading sign. */
2539 tmp_length = xsum (tmp_length, 1);
2543 # if HAVE_LONG_LONG_INT
2544 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2546 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2547 * 0.25 /* binary -> hexadecimal */
2549 + 1; /* turn floor into ceil */
2552 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2554 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2555 * 0.25 /* binary -> hexadecimal */
2557 + 1; /* turn floor into ceil */
2560 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2561 * 0.25 /* binary -> hexadecimal */
2563 + 1; /* turn floor into ceil */
2564 if (tmp_length < precision)
2565 tmp_length = precision;
2566 /* Add 2, to account for a leading sign or alternate form. */
2567 tmp_length = xsum (tmp_length, 2);
2571 if (type == TYPE_LONGDOUBLE)
2573 (unsigned int) (LDBL_MAX_EXP
2574 * 0.30103 /* binary -> decimal */
2575 * 2 /* estimate for FLAG_GROUP */
2577 + 1 /* turn floor into ceil */
2578 + 10; /* sign, decimal point etc. */
2581 (unsigned int) (DBL_MAX_EXP
2582 * 0.30103 /* binary -> decimal */
2583 * 2 /* estimate for FLAG_GROUP */
2585 + 1 /* turn floor into ceil */
2586 + 10; /* sign, decimal point etc. */
2587 tmp_length = xsum (tmp_length, precision);
2590 case 'e': case 'E': case 'g': case 'G':
2592 12; /* sign, decimal point, exponent etc. */
2593 tmp_length = xsum (tmp_length, precision);
2597 if (type == TYPE_LONGDOUBLE)
2599 (unsigned int) (LDBL_DIG
2600 * 0.831 /* decimal -> hexadecimal */
2602 + 1; /* turn floor into ceil */
2605 (unsigned int) (DBL_DIG
2606 * 0.831 /* decimal -> hexadecimal */
2608 + 1; /* turn floor into ceil */
2609 if (tmp_length < precision)
2610 tmp_length = precision;
2611 /* Account for sign, decimal point etc. */
2612 tmp_length = xsum (tmp_length, 12);
2616 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
2617 if (type == TYPE_WIDE_CHAR)
2618 tmp_length = MB_CUR_MAX;
2626 if (type == TYPE_WIDE_STRING)
2629 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
2631 # if !WIDE_CHAR_VERSION
2632 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
2637 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
2642 (unsigned int) (sizeof (void *) * CHAR_BIT
2643 * 0.25 /* binary -> hexadecimal */
2645 + 1 /* turn floor into ceil */
2646 + 2; /* account for leading 0x */
2653 if (tmp_length < width)
2656 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2659 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2663 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2665 if (size_overflow_p (tmp_memsize))
2666 /* Overflow, would lead to out of memory. */
2668 tmp = (CHAR_T *) malloc (tmp_memsize);
2670 /* Out of memory. */
2675 /* Decide whether to perform the padding ourselves. */
2676 #if NEED_PRINTF_FLAG_ZERO
2677 switch (dp->conversion)
2679 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
2689 /* Construct the format string for calling snprintf or
2693 #if NEED_PRINTF_FLAG_GROUPING
2694 /* The underlying implementation doesn't support the ' flag.
2695 Produce no grouping characters in this case; this is
2696 acceptable because the grouping is locale dependent. */
2698 if (flags & FLAG_GROUP)
2701 if (flags & FLAG_LEFT)
2703 if (flags & FLAG_SHOWSIGN)
2705 if (flags & FLAG_SPACE)
2707 if (flags & FLAG_ALT)
2711 if (flags & FLAG_ZERO)
2713 if (dp->width_start != dp->width_end)
2715 size_t n = dp->width_end - dp->width_start;
2716 memcpy (fbp, dp->width_start, n * sizeof (CHAR_T));
2720 if (dp->precision_start != dp->precision_end)
2722 size_t n = dp->precision_end - dp->precision_start;
2723 memcpy (fbp, dp->precision_start, n * sizeof (CHAR_T));
2729 #if HAVE_LONG_LONG_INT
2730 case TYPE_LONGLONGINT:
2731 case TYPE_ULONGLONGINT:
2732 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2745 case TYPE_WIDE_CHAR:
2748 case TYPE_WIDE_STRING:
2752 case TYPE_LONGDOUBLE:
2758 #if NEED_PRINTF_DIRECTIVE_F
2759 if (dp->conversion == 'F')
2763 *fbp = dp->conversion;
2772 /* Construct the arguments for calling snprintf or sprintf. */
2774 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
2776 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2778 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
2780 if (dp->precision_arg_index != ARG_NONE)
2782 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2784 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
2788 /* Prepare checking whether snprintf returns the count
2790 ENSURE_ALLOCATION (xsum (length, 1));
2791 result[length] = '\0';
2800 maxlen = allocated - length;
2805 /* SNPRINTF can fail if maxlen > INT_MAX. */
2806 if (maxlen > INT_MAX)
2808 # define SNPRINTF_BUF(arg) \
2809 switch (prefix_count) \
2812 retcount = SNPRINTF (result + length, maxlen, buf, \
2816 retcount = SNPRINTF (result + length, maxlen, buf, \
2817 prefixes[0], arg, &count); \
2820 retcount = SNPRINTF (result + length, maxlen, buf, \
2821 prefixes[0], prefixes[1], arg, \
2828 # define SNPRINTF_BUF(arg) \
2829 switch (prefix_count) \
2832 count = sprintf (tmp, buf, arg); \
2835 count = sprintf (tmp, buf, prefixes[0], arg); \
2838 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
2850 int arg = a.arg[dp->arg_index].a.a_schar;
2856 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
2862 int arg = a.arg[dp->arg_index].a.a_short;
2868 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
2874 int arg = a.arg[dp->arg_index].a.a_int;
2880 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
2886 long int arg = a.arg[dp->arg_index].a.a_longint;
2892 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
2896 #if HAVE_LONG_LONG_INT
2897 case TYPE_LONGLONGINT:
2899 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
2903 case TYPE_ULONGLONGINT:
2905 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
2912 double arg = a.arg[dp->arg_index].a.a_double;
2916 case TYPE_LONGDOUBLE:
2918 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2924 int arg = a.arg[dp->arg_index].a.a_char;
2929 case TYPE_WIDE_CHAR:
2931 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
2938 const char *arg = a.arg[dp->arg_index].a.a_string;
2943 case TYPE_WIDE_STRING:
2945 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2952 void *arg = a.arg[dp->arg_index].a.a_pointer;
2961 /* Portability: Not all implementations of snprintf()
2962 are ISO C 99 compliant. Determine the number of
2963 bytes that snprintf() has produced or would have
2967 /* Verify that snprintf() has NUL-terminated its
2969 if (count < maxlen && result[length + count] != '\0')
2971 /* Portability hack. */
2972 if (retcount > count)
2977 /* snprintf() doesn't understand the '%n'
2981 /* Don't use the '%n' directive; instead, look
2982 at the snprintf() return value. */
2988 /* Look at the snprintf() return value. */
2991 /* HP-UX 10.20 snprintf() is doubly deficient:
2992 It doesn't understand the '%n' directive,
2993 *and* it returns -1 (rather than the length
2994 that would have been required) when the
2995 buffer is too small. */
2996 size_t bigger_need =
2997 xsum (xtimes (allocated, 2), 12);
2998 ENSURE_ALLOCATION (bigger_need);
3007 /* Attempt to handle failure. */
3010 if (!(result == resultbuf || result == NULL))
3012 if (buf_malloced != NULL)
3013 free (buf_malloced);
3019 /* Make room for the result. */
3020 if (count >= maxlen)
3022 /* Need at least count bytes. But allocate
3023 proportionally, to avoid looping eternally if
3024 snprintf() reports a too small count. */
3026 xmax (xsum (length, count), xtimes (allocated, 2));
3028 ENSURE_ALLOCATION (n);
3032 maxlen = allocated - length;
3036 /* Perform padding. */
3037 #if NEED_PRINTF_FLAG_ZERO
3038 if (pad_ourselves && has_width && count < width)
3041 /* Make room for the result. */
3042 if (width >= maxlen)
3044 /* Need at least width bytes. But allocate
3045 proportionally, to avoid looping eternally if
3046 snprintf() reports a too small count. */
3048 xmax (xsum (length + 1, width),
3049 xtimes (allocated, 2));
3052 ENSURE_ALLOCATION (n);
3054 maxlen = allocated - length; /* > width */
3056 /* Here width < maxlen. */
3060 CHAR_T * const rp = result + length;
3062 CHAR_T * const rp = tmp;
3064 CHAR_T *p = rp + count;
3065 size_t pad = width - count;
3066 CHAR_T *end = p + pad;
3067 CHAR_T *pad_ptr = (*rp == '-' ? rp + 1 : rp);
3068 /* No zero-padding of "inf" and "nan". */
3069 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
3070 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
3072 /* The generated string now extends from rp to p,
3073 with the zero padding insertion point being at
3076 if (flags & FLAG_LEFT)
3078 /* Pad with spaces on the right. */
3079 for (; pad > 0; pad--)
3082 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3084 /* Pad with zeroes. */
3089 for (; pad > 0; pad--)
3094 /* Pad with spaces on the left. */
3099 for (; pad > 0; pad--)
3103 count = width; /* = count + pad = end - rp */
3109 if (count >= tmp_length)
3110 /* tmp_length was incorrectly calculated - fix the
3115 /* Here still count < maxlen. */
3118 /* The snprintf() result did fit. */
3120 /* Append the sprintf() result. */
3121 memcpy (result + length, tmp, count * sizeof (CHAR_T));
3126 #if NEED_PRINTF_DIRECTIVE_F
3127 if (dp->conversion == 'F')
3129 /* Convert the %f result to upper case for %F. */
3130 CHAR_T *rp = result + length;
3132 for (rc = count; rc > 0; rc--, rp++)
3133 if (*rp >= 'a' && *rp <= 'z')
3134 *rp = *rp - 'a' + 'A';
3145 /* Add the final NUL. */
3146 ENSURE_ALLOCATION (xsum (length, 1));
3147 result[length] = '\0';
3149 if (result != resultbuf && length + 1 < allocated)
3151 /* Shrink the allocated memory if possible. */
3154 memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
3159 if (buf_malloced != NULL)
3160 free (buf_malloced);
3163 /* Note that we can produce a big string of a length > INT_MAX. POSIX
3164 says that snprintf() fails with errno = EOVERFLOW in this case, but
3165 that's only because snprintf() returns an 'int'. This function does
3166 not have this limitation. */
3170 if (!(result == resultbuf || result == NULL))
3172 if (buf_malloced != NULL)
3173 free (buf_malloced);
3179 if (!(result == resultbuf || result == NULL))
3181 if (buf_malloced != NULL)
3182 free (buf_malloced);