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
61 #if NEED_PRINTF_INFINITE_DOUBLE && !defined IN_LIBINTL
66 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !defined IN_LIBINTL
68 # include "isnanl-nolibm.h"
71 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
74 # include "printf-frexp.h"
75 # include "isnanl-nolibm.h"
76 # include "printf-frexpl.h"
80 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
82 # define EOVERFLOW E2BIG
87 # define local_wcslen wcslen
89 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
90 a dependency towards this library, here is a local substitute.
91 Define this substitute only once, even if this file is included
92 twice in the same compilation unit. */
93 # ifndef local_wcslen_defined
94 # define local_wcslen_defined 1
96 local_wcslen (const wchar_t *s)
100 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
108 #if WIDE_CHAR_VERSION
109 # define VASNPRINTF vasnwprintf
110 # define CHAR_T wchar_t
111 # define DIRECTIVE wchar_t_directive
112 # define DIRECTIVES wchar_t_directives
113 # define PRINTF_PARSE wprintf_parse
114 # define USE_SNPRINTF 1
115 # if HAVE_DECL__SNWPRINTF
116 /* On Windows, the function swprintf() has a different signature than
117 on Unix; we use the _snwprintf() function instead. */
118 # define SNPRINTF _snwprintf
121 # define SNPRINTF swprintf
124 # define VASNPRINTF vasnprintf
126 # define DIRECTIVE char_directive
127 # define DIRECTIVES char_directives
128 # define PRINTF_PARSE printf_parse
129 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
130 But don't use it on BeOS, since BeOS snprintf produces no output if the
131 size argument is >= 0x3000000. */
132 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
133 # define USE_SNPRINTF 1
135 # define USE_SNPRINTF 0
137 # if HAVE_DECL__SNPRINTF
139 # define SNPRINTF _snprintf
142 # define SNPRINTF snprintf
143 /* Here we need to call the native snprintf, not rpl_snprintf. */
147 /* Here we need to call the native sprintf, not rpl_sprintf. */
150 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
151 /* Determine the decimal-point character according to the current locale. */
152 # ifndef decimal_point_char_defined
153 # define decimal_point_char_defined 1
155 decimal_point_char ()
158 /* Determine it in a multithread-safe way. We know nl_langinfo is
159 multithread-safe on glibc systems, but is not required to be multithread-
160 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
161 is rarely multithread-safe. */
162 # if HAVE_NL_LANGINFO && __GLIBC__
163 point = nl_langinfo (RADIXCHAR);
166 sprintf (pointbuf, "%#.0f", 1.0);
167 point = &pointbuf[1];
169 point = localeconv () -> decimal_point;
171 /* The decimal point is always a single byte: either '.' or ','. */
172 return (point[0] != '\0' ? point[0] : '.');
177 #if NEED_PRINTF_INFINITE_DOUBLE && !defined IN_LIBINTL
179 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
181 is_infinite_or_zero (double x)
183 return isnan (x) || x + x == x;
188 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !defined IN_LIBINTL
190 /* Equivalent to !isfinite(x), but does not require libm. */
192 is_infinitel (long double x)
194 return isnanl (x) || (x + x == x && x != 0.0L);
199 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
201 /* Converting 'long double' to decimal without rare rounding bugs requires
202 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
203 (and slower) algorithms. */
205 typedef unsigned int mp_limb_t;
206 # define GMP_LIMB_BITS 32
207 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
209 typedef unsigned long long mp_twolimb_t;
210 # define GMP_TWOLIMB_BITS 64
211 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
213 /* Representation of a bignum >= 0. */
217 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
220 /* Compute the product of two bignums >= 0.
221 Return the allocated memory in case of success, NULL in case of memory
222 allocation failure. */
224 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
231 if (src1.nlimbs <= src2.nlimbs)
245 /* Now 0 <= len1 <= len2. */
248 /* src1 or src2 is zero. */
250 dest->limbs = (mp_limb_t *) malloc (1);
254 /* Here 1 <= len1 <= len2. */
260 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
263 for (k = len2; k > 0; )
265 for (i = 0; i < len1; i++)
267 mp_limb_t digit1 = p1[i];
268 mp_twolimb_t carry = 0;
269 for (j = 0; j < len2; j++)
271 mp_limb_t digit2 = p2[j];
272 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
274 dp[i + j] = (mp_limb_t) carry;
275 carry = carry >> GMP_LIMB_BITS;
277 dp[i + len2] = (mp_limb_t) carry;
280 while (dlen > 0 && dp[dlen - 1] == 0)
288 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
289 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
291 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
293 Return the allocated memory in case of success, NULL in case of memory
294 allocation failure. */
296 divide (mpn_t a, mpn_t b, mpn_t *q)
299 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
300 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
301 If m<n, then q:=0 and r:=a.
302 If m>=n=1, perform a single-precision division:
305 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
306 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
307 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
308 Normalise [q[m-1],...,q[0]], yields q.
309 If m>=n>1, perform a multiple-precision division:
310 We have a/b < beta^(m-n+1).
311 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
312 Shift a and b left by s bits, copying them. r:=a.
313 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
314 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
316 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
317 In case of overflow (q* >= beta) set q* := beta-1.
318 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
319 and c3 := b[n-2] * q*.
320 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
321 occurred. Furthermore 0 <= c3 < beta^2.
322 If there was overflow and
323 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
324 the next test can be skipped.}
325 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
326 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
328 Put r := r - b * q* * beta^j. In detail:
329 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
330 hence: u:=0, for i:=0 to n-1 do
332 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
333 u:=u div beta (+ 1, if carry in subtraction)
335 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
337 the carry u does not overflow.}
338 If a negative carry occurs, put q* := q* - 1
339 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
341 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
342 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
344 The room for q[j] can be allocated at the memory location of r[n+j].
345 Finally, round-to-even:
346 Shift r left by 1 bit.
347 If r > b or if r = b and q[0] is odd, q := q+1.
349 const mp_limb_t *a_ptr = a.limbs;
350 size_t a_len = a.nlimbs;
351 const mp_limb_t *b_ptr = b.limbs;
352 size_t b_len = b.nlimbs;
354 mp_limb_t *tmp_roomptr = NULL;
360 /* Allocate room for a_len+2 digits.
361 (Need a_len+1 digits for the real division and 1 more digit for the
362 final rounding of q.) */
363 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
368 while (a_len > 0 && a_ptr[a_len - 1] == 0)
375 /* Division by zero. */
377 if (b_ptr[b_len - 1] == 0)
383 /* Here m = a_len >= 0 and n = b_len > 0. */
387 /* m<n: trivial case. q=0, r := copy of a. */
390 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
391 q_ptr = roomptr + a_len;
396 /* n=1: single precision division.
397 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
401 mp_limb_t den = b_ptr[0];
402 mp_limb_t remainder = 0;
403 const mp_limb_t *sourceptr = a_ptr + a_len;
404 mp_limb_t *destptr = q_ptr + a_len;
406 for (count = a_len; count > 0; count--)
409 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
410 *--destptr = num / den;
411 remainder = num % den;
413 /* Normalise and store r. */
416 r_ptr[0] = remainder;
423 if (q_ptr[q_len - 1] == 0)
429 /* n>1: multiple precision division.
430 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
431 beta^(m-n-1) <= a/b < beta^(m-n+1). */
435 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
463 /* 0 <= s < GMP_LIMB_BITS.
464 Copy b, shifting it left by s bits. */
467 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
468 if (tmp_roomptr == NULL)
474 const mp_limb_t *sourceptr = b_ptr;
475 mp_limb_t *destptr = tmp_roomptr;
476 mp_twolimb_t accu = 0;
478 for (count = b_len; count > 0; count--)
480 accu += (mp_twolimb_t) *sourceptr++ << s;
481 *destptr++ = (mp_limb_t) accu;
482 accu = accu >> GMP_LIMB_BITS;
484 /* accu must be zero, since that was how s was determined. */
490 /* Copy a, shifting it left by s bits, yields r.
492 At the beginning: r = roomptr[0..a_len],
493 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
497 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
502 const mp_limb_t *sourceptr = a_ptr;
503 mp_limb_t *destptr = r_ptr;
504 mp_twolimb_t accu = 0;
506 for (count = a_len; count > 0; count--)
508 accu += (mp_twolimb_t) *sourceptr++ << s;
509 *destptr++ = (mp_limb_t) accu;
510 accu = accu >> GMP_LIMB_BITS;
512 *destptr++ = (mp_limb_t) accu;
514 q_ptr = roomptr + b_len;
515 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
517 size_t j = a_len - b_len; /* m-n */
518 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
519 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
520 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
521 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
522 /* Division loop, traversed m-n+1 times.
523 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
528 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
530 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
532 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
533 | r_ptr[j + b_len - 1];
534 q_star = num / b_msd;
539 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
540 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
541 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
542 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
543 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
545 If yes, jump directly to the subtraction loop.
546 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
547 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
548 if (r_ptr[j + b_len] > b_msd
549 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
550 /* r[j+n] >= b[n-1]+1 or
551 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
556 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
558 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
559 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
560 mp_twolimb_t c3 = /* b[n-2] * q* */
561 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
562 /* While c2 < c3, increase c2 and decrease c3.
563 Consider c3-c2. While it is > 0, decrease it by
564 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
565 this can happen only twice. */
568 q_star = q_star - 1; /* q* := q* - 1 */
569 if (c3 - c2 > b_msdd)
570 q_star = q_star - 1; /* q* := q* - 1 */
576 /* Subtract r := r - b * q* * beta^j. */
579 const mp_limb_t *sourceptr = b_ptr;
580 mp_limb_t *destptr = r_ptr + j;
581 mp_twolimb_t carry = 0;
583 for (count = b_len; count > 0; count--)
585 /* Here 0 <= carry <= q*. */
588 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
589 + (mp_limb_t) ~(*destptr);
590 /* Here 0 <= carry <= beta*q* + beta-1. */
591 *destptr++ = ~(mp_limb_t) carry;
592 carry = carry >> GMP_LIMB_BITS; /* <= q* */
594 cr = (mp_limb_t) carry;
596 /* Subtract cr from r_ptr[j + b_len], then forget about
598 if (cr > r_ptr[j + b_len])
600 /* Subtraction gave a carry. */
601 q_star = q_star - 1; /* q* := q* - 1 */
604 const mp_limb_t *sourceptr = b_ptr;
605 mp_limb_t *destptr = r_ptr + j;
608 for (count = b_len; count > 0; count--)
610 mp_limb_t source1 = *sourceptr++;
611 mp_limb_t source2 = *destptr;
612 *destptr++ = source1 + source2 + carry;
615 ? source1 >= (mp_limb_t) ~source2
616 : source1 > (mp_limb_t) ~source2);
619 /* Forget about the carry and about r[j+n]. */
622 /* q* is determined. Store it as q[j]. */
631 if (q_ptr[q_len - 1] == 0)
633 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
634 b is shifted left by s bits. */
635 /* Shift r right by s bits. */
638 mp_limb_t ptr = r_ptr + r_len;
639 mp_twolimb_t accu = 0;
641 for (count = r_len; count > 0; count--)
643 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
644 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
645 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
650 while (r_len > 0 && r_ptr[r_len - 1] == 0)
653 /* Compare r << 1 with b. */
661 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
662 | (i < r_len ? r_ptr[i] << 1 : 0);
663 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
673 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
678 for (i = 0; i < q_len; i++)
679 if (++(q_ptr[i]) != 0)
684 if (tmp_roomptr != NULL)
691 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
693 Destroys the contents of a.
694 Return the allocated memory - containing the decimal digits in low-to-high
695 order, terminated with a NUL character - in case of success, NULL in case
696 of memory allocation failure. */
698 convert_to_decimal (mpn_t a, size_t extra_zeroes)
700 mp_limb_t *a_ptr = a.limbs;
701 size_t a_len = a.nlimbs;
702 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
703 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
704 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
708 for (; extra_zeroes > 0; extra_zeroes--)
712 /* Divide a by 10^9, in-place. */
713 mp_limb_t remainder = 0;
714 mp_limb_t *ptr = a_ptr + a_len;
716 for (count = a_len; count > 0; count--)
719 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
720 *ptr = num / 1000000000;
721 remainder = num % 1000000000;
723 /* Store the remainder as 9 decimal digits. */
724 for (count = 9; count > 0; count--)
726 *d_ptr++ = '0' + (remainder % 10);
727 remainder = remainder / 10;
730 if (a_ptr[a_len - 1] == 0)
733 /* Remove leading zeroes. */
734 while (d_ptr > c_ptr && d_ptr[-1] == '0')
736 /* But keep at least one zero. */
739 /* Terminate the string. */
745 /* Assuming x is finite and >= 0:
746 write x as x = 2^e * m, where m is a bignum.
747 Return the allocated memory in case of success, NULL in case of memory
748 allocation failure. */
750 decode_long_double (long double x, int *ep, mpn_t *mp)
757 /* Allocate memory for result. */
758 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
759 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
762 /* Split into exponential part and mantissa. */
763 y = frexpl (x, &exp);
764 if (!(y >= 0.0L && y < 1.0L))
766 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
767 latter is an integer. */
768 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
769 I'm not sure whether it's safe to cast a 'long double' value between
770 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
771 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
773 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
774 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
777 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
780 if (!(y >= 0.0L && y < 1.0L))
782 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
785 if (!(y >= 0.0L && y < 1.0L))
787 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
792 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
795 if (!(y >= 0.0L && y < 1.0L))
797 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
801 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
804 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
807 if (!(y >= 0.0L && y < 1.0L))
809 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
812 if (!(y >= 0.0L && y < 1.0L))
814 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
819 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
822 *ep = exp - LDBL_MANT_BIT;
826 /* Assuming x is finite and >= 0, and n is an integer:
827 Returns the decimal representation of round (x * 10^n).
828 Return the allocated memory - containing the decimal digits in low-to-high
829 order, terminated with a NUL character - in case of success, NULL in case
830 of memory allocation failure. */
832 scale10_round_decimal_long_double (long double x, int n)
836 void *memory = decode_long_double (x, &e, &m);
843 unsigned int s_limbs;
852 /* x = 2^e * m, hence
853 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
854 = round (2^s * 5^n * m). */
857 /* Factor out a common power of 10 if possible. */
860 extra_zeroes = (s < n ? s : n);
864 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
865 Before converting to decimal, we need to compute
866 z = round (2^s * 5^n * m). */
867 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
868 sign. 2.322 is slightly larger than log(5)/log(2). */
869 abs_n = (n >= 0 ? n : -n);
870 abs_s = (s >= 0 ? s : -s);
871 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
872 + abs_s / GMP_LIMB_BITS + 1)
873 * sizeof (mp_limb_t));
874 if (pow5_ptr == NULL)
879 /* Initialize with 1. */
882 /* Multiply with 5^|n|. */
885 static mp_limb_t const small_pow5[13 + 1] =
887 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
888 48828125, 244140625, 1220703125
891 for (n13 = 0; n13 <= abs_n; n13 += 13)
893 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
895 mp_twolimb_t carry = 0;
896 for (j = 0; j < pow5_len; j++)
898 mp_limb_t digit2 = pow5_ptr[j];
899 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
900 pow5_ptr[j] = (mp_limb_t) carry;
901 carry = carry >> GMP_LIMB_BITS;
904 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
907 s_limbs = abs_s / GMP_LIMB_BITS;
908 s_bits = abs_s % GMP_LIMB_BITS;
909 if (n >= 0 ? s >= 0 : s <= 0)
911 /* Multiply with 2^|s|. */
914 mp_limb_t *ptr = pow5_ptr;
915 mp_twolimb_t accu = 0;
917 for (count = pow5_len; count > 0; count--)
919 accu += (mp_twolimb_t) *ptr << s_bits;
920 *ptr++ = (mp_limb_t) accu;
921 accu = accu >> GMP_LIMB_BITS;
925 *ptr = (mp_limb_t) accu;
932 for (count = pow5_len; count > 0;)
935 pow5_ptr[s_limbs + count] = pow5_ptr[count];
937 for (count = s_limbs; count > 0;)
944 pow5.limbs = pow5_ptr;
945 pow5.nlimbs = pow5_len;
948 /* Multiply m with pow5. No division needed. */
949 z_memory = multiply (m, pow5, &z);
953 /* Divide m by pow5 and round. */
954 z_memory = divide (m, pow5, &z);
959 pow5.limbs = pow5_ptr;
960 pow5.nlimbs = pow5_len;
964 Multiply m with pow5, then divide by 2^|s|. */
968 tmp_memory = multiply (m, pow5, &numerator);
969 if (tmp_memory == NULL)
975 /* Construct 2^|s|. */
977 mp_limb_t *ptr = pow5_ptr + pow5_len;
979 for (i = 0; i < s_limbs; i++)
981 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
982 denominator.limbs = ptr;
983 denominator.nlimbs = s_limbs + 1;
985 z_memory = divide (numerator, denominator, &z);
991 Multiply m with 2^s, then divide by pow5. */
994 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
995 * sizeof (mp_limb_t));
1003 mp_limb_t *destptr = num_ptr;
1006 for (i = 0; i < s_limbs; i++)
1011 const mp_limb_t *sourceptr = m.limbs;
1012 mp_twolimb_t accu = 0;
1014 for (count = m.nlimbs; count > 0; count--)
1016 accu += (mp_twolimb_t) *sourceptr++ << s;
1017 *destptr++ = (mp_limb_t) accu;
1018 accu = accu >> GMP_LIMB_BITS;
1021 *destptr++ = (mp_limb_t) accu;
1025 const mp_limb_t *sourceptr = m.limbs;
1027 for (count = m.nlimbs; count > 0; count--)
1028 *destptr++ = *sourceptr++;
1030 numerator.limbs = num_ptr;
1031 numerator.nlimbs = destptr - num_ptr;
1033 z_memory = divide (numerator, pow5, &z);
1040 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1042 if (z_memory == NULL)
1044 digits = convert_to_decimal (z, extra_zeroes);
1049 /* Assuming x is finite and > 0:
1050 Return an approximation for n with 10^n <= x < 10^(n+1).
1051 The approximation is usually the right n, but may be off by 1 sometimes. */
1053 floorlog10l (long double x)
1060 /* Split into exponential part and mantissa. */
1061 y = frexpl (x, &exp);
1062 if (!(y >= 0.0L && y < 1.0L))
1068 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1070 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1071 exp -= GMP_LIMB_BITS;
1073 if (y < (1.0L / (1 << 16)))
1075 y *= 1.0L * (1 << 16);
1078 if (y < (1.0L / (1 << 8)))
1080 y *= 1.0L * (1 << 8);
1083 if (y < (1.0L / (1 << 4)))
1085 y *= 1.0L * (1 << 4);
1088 if (y < (1.0L / (1 << 2)))
1090 y *= 1.0L * (1 << 2);
1093 if (y < (1.0L / (1 << 1)))
1095 y *= 1.0L * (1 << 1);
1099 if (!(y >= 0.5L && y < 1.0L))
1101 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1104 if (z < 0.70710678118654752444)
1106 z *= 1.4142135623730950488;
1109 if (z < 0.8408964152537145431)
1111 z *= 1.1892071150027210667;
1114 if (z < 0.91700404320467123175)
1116 z *= 1.0905077326652576592;
1119 if (z < 0.9576032806985736469)
1121 z *= 1.0442737824274138403;
1124 /* Now 0.95 <= z <= 1.01. */
1126 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1127 Four terms are enough to get an approximation with error < 10^-7. */
1128 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1129 /* Finally multiply with log(2)/log(10), yields an approximation for
1131 l *= 0.30102999566398119523;
1132 /* Round down to the next integer. */
1133 return (int) l + (l < 0 ? -1 : 0);
1139 VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list args)
1144 if (PRINTF_PARSE (format, &d, &a) < 0)
1155 if (printf_fetchargs (args, &a) < 0)
1163 size_t buf_neededlength;
1165 CHAR_T *buf_malloced;
1169 /* Output string accumulator. */
1174 /* Allocate a small buffer that will hold a directive passed to
1175 sprintf or snprintf. */
1177 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1179 if (buf_neededlength < 4000 / sizeof (CHAR_T))
1181 buf = (CHAR_T *) alloca (buf_neededlength * sizeof (CHAR_T));
1182 buf_malloced = NULL;
1187 size_t buf_memsize = xtimes (buf_neededlength, sizeof (CHAR_T));
1188 if (size_overflow_p (buf_memsize))
1189 goto out_of_memory_1;
1190 buf = (CHAR_T *) malloc (buf_memsize);
1192 goto out_of_memory_1;
1196 if (resultbuf != NULL)
1199 allocated = *lengthp;
1208 result is either == resultbuf or == NULL or malloc-allocated.
1209 If length > 0, then result != NULL. */
1211 /* Ensures that allocated >= needed. Aborts through a jump to
1212 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1213 #define ENSURE_ALLOCATION(needed) \
1214 if ((needed) > allocated) \
1216 size_t memory_size; \
1219 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1220 if ((needed) > allocated) \
1221 allocated = (needed); \
1222 memory_size = xtimes (allocated, sizeof (CHAR_T)); \
1223 if (size_overflow_p (memory_size)) \
1224 goto out_of_memory; \
1225 if (result == resultbuf || result == NULL) \
1226 memory = (CHAR_T *) malloc (memory_size); \
1228 memory = (CHAR_T *) realloc (result, memory_size); \
1229 if (memory == NULL) \
1230 goto out_of_memory; \
1231 if (result == resultbuf && length > 0) \
1232 memcpy (memory, result, length * sizeof (CHAR_T)); \
1236 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1238 if (cp != dp->dir_start)
1240 size_t n = dp->dir_start - cp;
1241 size_t augmented_length = xsum (length, n);
1243 ENSURE_ALLOCATION (augmented_length);
1244 memcpy (result + length, cp, n * sizeof (CHAR_T));
1245 length = augmented_length;
1250 /* Execute a single directive. */
1251 if (dp->conversion == '%')
1253 size_t augmented_length;
1255 if (!(dp->arg_index == ARG_NONE))
1257 augmented_length = xsum (length, 1);
1258 ENSURE_ALLOCATION (augmented_length);
1259 result[length] = '%';
1260 length = augmented_length;
1264 if (!(dp->arg_index != ARG_NONE))
1267 if (dp->conversion == 'n')
1269 switch (a.arg[dp->arg_index].type)
1271 case TYPE_COUNT_SCHAR_POINTER:
1272 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1274 case TYPE_COUNT_SHORT_POINTER:
1275 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1277 case TYPE_COUNT_INT_POINTER:
1278 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1280 case TYPE_COUNT_LONGINT_POINTER:
1281 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1283 #if HAVE_LONG_LONG_INT
1284 case TYPE_COUNT_LONGLONGINT_POINTER:
1285 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1292 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
1293 else if ((dp->conversion == 'f' || dp->conversion == 'F'
1294 || dp->conversion == 'e' || dp->conversion == 'E'
1295 || dp->conversion == 'g' || dp->conversion == 'G')
1297 # if NEED_PRINTF_INFINITE_DOUBLE
1298 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
1299 /* The systems (mingw) which produce wrong output
1300 for Inf and -Inf also do so for NaN and -0.0.
1301 Therefore we treat these cases here as well. */
1302 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
1304 # if NEED_PRINTF_LONG_DOUBLE
1305 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
1306 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
1307 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
1308 /* The systems which produce wrong output for Inf
1309 and -Inf also do so for NaN. Therefore treat
1310 this case here as well. */
1311 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
1315 # if NEED_PRINTF_INFINITE_DOUBLE && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
1316 arg_type type = a.arg[dp->arg_index].type;
1318 int flags = dp->flags;
1331 if (dp->width_start != dp->width_end)
1333 if (dp->width_arg_index != ARG_NONE)
1337 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1339 arg = a.arg[dp->width_arg_index].a.a_int;
1342 /* "A negative field width is taken as a '-' flag
1343 followed by a positive field width." */
1345 width = (unsigned int) (-arg);
1352 const CHAR_T *digitp = dp->width_start;
1355 width = xsum (xtimes (width, 10), *digitp++ - '0');
1356 while (digitp != dp->width_end);
1363 if (dp->precision_start != dp->precision_end)
1365 if (dp->precision_arg_index != ARG_NONE)
1369 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1371 arg = a.arg[dp->precision_arg_index].a.a_int;
1372 /* "A negative precision is taken as if the precision
1382 const CHAR_T *digitp = dp->precision_start + 1;
1385 while (digitp != dp->precision_end)
1386 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1391 /* POSIX specifies the default precision to be 6 for %f, %F,
1392 %e, %E, but not for %g, %G. Implementations appear to use
1393 the same default precision also for %g, %G. */
1397 /* Allocate a temporary buffer of sufficient size. */
1398 # if NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
1399 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
1400 # elif NEED_PRINTF_LONG_DOUBLE
1401 tmp_length = LDBL_DIG + 1;
1405 if (tmp_length < precision)
1406 tmp_length = precision;
1407 # if NEED_PRINTF_LONG_DOUBLE
1408 # if NEED_PRINTF_INFINITE_DOUBLE
1409 if (type == TYPE_LONGDOUBLE)
1411 if (dp->conversion == 'f' || dp->conversion == 'F')
1413 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1414 if (!(isnanl (arg) || arg + arg == arg))
1416 /* arg is finite and nonzero. */
1417 int exponent = floorlog10l (arg < 0 ? -arg : arg);
1418 if (exponent >= 0 && tmp_length < exponent + precision)
1419 tmp_length = exponent + precision;
1423 /* Account for sign, decimal point etc. */
1424 tmp_length = xsum (tmp_length, 12);
1426 if (tmp_length < width)
1429 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1431 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1435 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1437 if (size_overflow_p (tmp_memsize))
1438 /* Overflow, would lead to out of memory. */
1440 tmp = (CHAR_T *) malloc (tmp_memsize);
1442 /* Out of memory. */
1449 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
1450 # if NEED_PRINTF_INFINITE_DOUBLE
1451 if (type == TYPE_LONGDOUBLE)
1454 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1458 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1460 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1464 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1470 DECL_LONG_DOUBLE_ROUNDING
1472 BEGIN_LONG_DOUBLE_ROUNDING ();
1474 if (signbit (arg)) /* arg < 0.0L or negative zero */
1482 else if (flags & FLAG_SHOWSIGN)
1484 else if (flags & FLAG_SPACE)
1487 if (arg > 0.0L && arg + arg == arg)
1489 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1491 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1495 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1500 # if NEED_PRINTF_LONG_DOUBLE
1503 if (dp->conversion == 'f' || dp->conversion == 'F')
1509 scale10_round_decimal_long_double (arg, precision);
1512 END_LONG_DOUBLE_ROUNDING ();
1515 ndigits = strlen (digits);
1517 if (ndigits > precision)
1521 *p++ = digits[ndigits];
1523 while (ndigits > precision);
1526 /* Here ndigits <= precision. */
1527 if ((flags & FLAG_ALT) || precision > 0)
1529 *p++ = decimal_point_char ();
1530 for (; precision > ndigits; precision--)
1535 *p++ = digits[ndigits];
1541 else if (dp->conversion == 'e' || dp->conversion == 'E')
1549 if ((flags & FLAG_ALT) || precision > 0)
1551 *p++ = decimal_point_char ();
1552 for (; precision > 0; precision--)
1563 exponent = floorlog10l (arg);
1568 scale10_round_decimal_long_double (arg,
1569 (int)precision - exponent);
1572 END_LONG_DOUBLE_ROUNDING ();
1575 ndigits = strlen (digits);
1577 if (ndigits == precision + 1)
1579 if (ndigits < precision
1580 || ndigits > precision + 2)
1581 /* The exponent was not guessed
1582 precisely enough. */
1585 /* None of two values of exponent is
1586 the right one. Prevent an endless
1590 if (ndigits == precision)
1597 /* Here ndigits = precision+1. */
1598 *p++ = digits[--ndigits];
1599 if ((flags & FLAG_ALT) || precision > 0)
1601 *p++ = decimal_point_char ();
1605 *p++ = digits[ndigits];
1612 *p++ = dp->conversion; /* 'e' or 'E' */
1613 # if WIDE_CHAR_VERSION
1615 static const wchar_t decimal_format[] =
1616 { '%', '+', '.', '2', 'd', '\0' };
1617 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1620 sprintf (p, "%+.2d", exponent);
1625 else if (dp->conversion == 'g' || dp->conversion == 'G')
1629 /* precision >= 1. */
1632 /* The exponent is 0, >= -4, < precision.
1633 Use fixed-point notation. */
1635 size_t ndigits = precision;
1636 /* Number of trailing zeroes that have to be
1639 (flags & FLAG_ALT ? 0 : precision - 1);
1643 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1645 *p++ = decimal_point_char ();
1646 while (ndigits > nzeroes)
1662 exponent = floorlog10l (arg);
1667 scale10_round_decimal_long_double (arg,
1668 (int)(precision - 1) - exponent);
1671 END_LONG_DOUBLE_ROUNDING ();
1674 ndigits = strlen (digits);
1676 if (ndigits == precision)
1678 if (ndigits < precision - 1
1679 || ndigits > precision + 1)
1680 /* The exponent was not guessed
1681 precisely enough. */
1684 /* None of two values of exponent is
1685 the right one. Prevent an endless
1689 if (ndigits < precision)
1695 /* Here ndigits = precision. */
1697 /* Determine the number of trailing zeroes
1698 that have to be dropped. */
1700 if ((flags & FLAG_ALT) == 0)
1701 while (nzeroes < ndigits
1702 && digits[nzeroes] == '0')
1705 /* The exponent is now determined. */
1707 && exponent < (long)precision)
1709 /* Fixed-point notation:
1710 max(exponent,0)+1 digits, then the
1711 decimal point, then the remaining
1712 digits without trailing zeroes. */
1715 size_t count = exponent + 1;
1716 /* Note: count <= precision = ndigits. */
1717 for (; count > 0; count--)
1718 *p++ = digits[--ndigits];
1719 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1721 *p++ = decimal_point_char ();
1722 while (ndigits > nzeroes)
1725 *p++ = digits[ndigits];
1731 size_t count = -exponent - 1;
1733 *p++ = decimal_point_char ();
1734 for (; count > 0; count--)
1736 while (ndigits > nzeroes)
1739 *p++ = digits[ndigits];
1745 /* Exponential notation. */
1746 *p++ = digits[--ndigits];
1747 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1749 *p++ = decimal_point_char ();
1750 while (ndigits > nzeroes)
1753 *p++ = digits[ndigits];
1756 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
1757 # if WIDE_CHAR_VERSION
1759 static const wchar_t decimal_format[] =
1760 { '%', '+', '.', '2', 'd', '\0' };
1761 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1764 sprintf (p, "%+.2d", exponent);
1776 /* arg is finite. */
1781 END_LONG_DOUBLE_ROUNDING ();
1784 # if NEED_PRINTF_INFINITE_DOUBLE
1788 # if NEED_PRINTF_INFINITE_DOUBLE
1790 /* Simpler than above: handle only NaN, Infinity, zero. */
1791 double arg = a.arg[dp->arg_index].a.a_double;
1795 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1797 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1801 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1808 if (signbit (arg)) /* arg < 0.0L or negative zero */
1816 else if (flags & FLAG_SHOWSIGN)
1818 else if (flags & FLAG_SPACE)
1821 if (arg > 0.0 && arg + arg == arg)
1823 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1825 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1829 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1839 if (dp->conversion == 'f' || dp->conversion == 'F')
1842 if ((flags & FLAG_ALT) || precision > 0)
1844 *p++ = decimal_point_char ();
1845 for (; precision > 0; precision--)
1849 else if (dp->conversion == 'e' || dp->conversion == 'E')
1852 if ((flags & FLAG_ALT) || precision > 0)
1854 *p++ = decimal_point_char ();
1855 for (; precision > 0; precision--)
1858 *p++ = dp->conversion; /* 'e' or 'E' */
1860 /* Produce the same number of exponent digits as
1861 the native printf implementation. */
1862 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
1868 else if (dp->conversion == 'g' || dp->conversion == 'G')
1871 if (flags & FLAG_ALT)
1874 (precision > 0 ? precision - 1 : 0);
1875 *p++ = decimal_point_char ();
1876 for (; ndigits > 0; --ndigits)
1887 /* The generated string now extends from tmp to p, with the
1888 zero padding insertion point being at pad_ptr. */
1889 if (has_width && p - tmp < width)
1891 size_t pad = width - (p - tmp);
1892 CHAR_T *end = p + pad;
1894 if (flags & FLAG_LEFT)
1896 /* Pad with spaces on the right. */
1897 for (; pad > 0; pad--)
1900 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
1902 /* Pad with zeroes. */
1907 for (; pad > 0; pad--)
1912 /* Pad with spaces on the left. */
1917 for (; pad > 0; pad--)
1925 size_t count = p - tmp;
1927 if (count >= tmp_length)
1928 /* tmp_length was incorrectly calculated - fix the
1932 /* Make room for the result. */
1933 if (count >= allocated - length)
1935 size_t n = xsum (length, count);
1937 ENSURE_ALLOCATION (n);
1940 /* Append the result. */
1941 memcpy (result + length, tmp, count * sizeof (CHAR_T));
1948 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
1949 else if (dp->conversion == 'a' || dp->conversion == 'A')
1951 arg_type type = a.arg[dp->arg_index].type;
1952 int flags = dp->flags;
1965 if (dp->width_start != dp->width_end)
1967 if (dp->width_arg_index != ARG_NONE)
1971 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1973 arg = a.arg[dp->width_arg_index].a.a_int;
1976 /* "A negative field width is taken as a '-' flag
1977 followed by a positive field width." */
1979 width = (unsigned int) (-arg);
1986 const CHAR_T *digitp = dp->width_start;
1989 width = xsum (xtimes (width, 10), *digitp++ - '0');
1990 while (digitp != dp->width_end);
1997 if (dp->precision_start != dp->precision_end)
1999 if (dp->precision_arg_index != ARG_NONE)
2003 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2005 arg = a.arg[dp->precision_arg_index].a.a_int;
2006 /* "A negative precision is taken as if the precision
2016 const CHAR_T *digitp = dp->precision_start + 1;
2019 while (digitp != dp->precision_end)
2020 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2025 /* Allocate a temporary buffer of sufficient size. */
2026 if (type == TYPE_LONGDOUBLE)
2028 (unsigned int) ((LDBL_DIG + 1)
2029 * 0.831 /* decimal -> hexadecimal */
2031 + 1; /* turn floor into ceil */
2034 (unsigned int) ((DBL_DIG + 1)
2035 * 0.831 /* decimal -> hexadecimal */
2037 + 1; /* turn floor into ceil */
2038 if (tmp_length < precision)
2039 tmp_length = precision;
2040 /* Account for sign, decimal point etc. */
2041 tmp_length = xsum (tmp_length, 12);
2043 if (tmp_length < width)
2046 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2048 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2052 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2054 if (size_overflow_p (tmp_memsize))
2055 /* Overflow, would lead to out of memory. */
2057 tmp = (CHAR_T *) malloc (tmp_memsize);
2059 /* Out of memory. */
2065 if (type == TYPE_LONGDOUBLE)
2067 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2071 if (dp->conversion == 'A')
2073 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2077 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2083 DECL_LONG_DOUBLE_ROUNDING
2085 BEGIN_LONG_DOUBLE_ROUNDING ();
2087 if (signbit (arg)) /* arg < 0.0L or negative zero */
2095 else if (flags & FLAG_SHOWSIGN)
2097 else if (flags & FLAG_SPACE)
2100 if (arg > 0.0L && arg + arg == arg)
2102 if (dp->conversion == 'A')
2104 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2108 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2114 long double mantissa;
2117 mantissa = printf_frexpl (arg, &exponent);
2125 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2127 /* Round the mantissa. */
2128 long double tail = mantissa;
2131 for (q = precision; ; q--)
2133 int digit = (int) tail;
2137 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2146 for (q = precision; q > 0; q--)
2152 *p++ = dp->conversion - 'A' + 'X';
2157 digit = (int) mantissa;
2160 if ((flags & FLAG_ALT)
2161 || mantissa > 0.0L || precision > 0)
2163 *p++ = decimal_point_char ();
2164 /* This loop terminates because we assume
2165 that FLT_RADIX is a power of 2. */
2166 while (mantissa > 0.0L)
2169 digit = (int) mantissa;
2174 : dp->conversion - 10);
2178 while (precision > 0)
2185 *p++ = dp->conversion - 'A' + 'P';
2186 # if WIDE_CHAR_VERSION
2188 static const wchar_t decimal_format[] =
2189 { '%', '+', 'd', '\0' };
2190 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2193 sprintf (p, "%+d", exponent);
2199 END_LONG_DOUBLE_ROUNDING ();
2204 double arg = a.arg[dp->arg_index].a.a_double;
2208 if (dp->conversion == 'A')
2210 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2214 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2221 if (signbit (arg)) /* arg < 0.0 or negative zero */
2229 else if (flags & FLAG_SHOWSIGN)
2231 else if (flags & FLAG_SPACE)
2234 if (arg > 0.0 && arg + arg == arg)
2236 if (dp->conversion == 'A')
2238 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2242 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2251 mantissa = printf_frexp (arg, &exponent);
2259 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2261 /* Round the mantissa. */
2262 double tail = mantissa;
2265 for (q = precision; ; q--)
2267 int digit = (int) tail;
2271 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2280 for (q = precision; q > 0; q--)
2286 *p++ = dp->conversion - 'A' + 'X';
2291 digit = (int) mantissa;
2294 if ((flags & FLAG_ALT)
2295 || mantissa > 0.0 || precision > 0)
2297 *p++ = decimal_point_char ();
2298 /* This loop terminates because we assume
2299 that FLT_RADIX is a power of 2. */
2300 while (mantissa > 0.0)
2303 digit = (int) mantissa;
2308 : dp->conversion - 10);
2312 while (precision > 0)
2319 *p++ = dp->conversion - 'A' + 'P';
2320 # if WIDE_CHAR_VERSION
2322 static const wchar_t decimal_format[] =
2323 { '%', '+', 'd', '\0' };
2324 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2327 sprintf (p, "%+d", exponent);
2334 /* The generated string now extends from tmp to p, with the
2335 zero padding insertion point being at pad_ptr. */
2336 if (has_width && p - tmp < width)
2338 size_t pad = width - (p - tmp);
2339 CHAR_T *end = p + pad;
2341 if (flags & FLAG_LEFT)
2343 /* Pad with spaces on the right. */
2344 for (; pad > 0; pad--)
2347 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2349 /* Pad with zeroes. */
2354 for (; pad > 0; pad--)
2359 /* Pad with spaces on the left. */
2364 for (; pad > 0; pad--)
2372 size_t count = p - tmp;
2374 if (count >= tmp_length)
2375 /* tmp_length was incorrectly calculated - fix the
2379 /* Make room for the result. */
2380 if (count >= allocated - length)
2382 size_t n = xsum (length, count);
2384 ENSURE_ALLOCATION (n);
2387 /* Append the result. */
2388 memcpy (result + length, tmp, count * sizeof (CHAR_T));
2397 arg_type type = a.arg[dp->arg_index].type;
2398 int flags = dp->flags;
2399 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2403 #if NEED_PRINTF_FLAG_ZERO
2406 # define pad_ourselves 0
2409 unsigned int prefix_count;
2417 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2420 if (dp->width_start != dp->width_end)
2422 if (dp->width_arg_index != ARG_NONE)
2426 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2428 arg = a.arg[dp->width_arg_index].a.a_int;
2431 /* "A negative field width is taken as a '-' flag
2432 followed by a positive field width." */
2434 width = (unsigned int) (-arg);
2441 const CHAR_T *digitp = dp->width_start;
2444 width = xsum (xtimes (width, 10), *digitp++ - '0');
2445 while (digitp != dp->width_end);
2452 /* Allocate a temporary buffer of sufficient size for calling
2458 if (dp->precision_start != dp->precision_end)
2460 if (dp->precision_arg_index != ARG_NONE)
2464 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2466 arg = a.arg[dp->precision_arg_index].a.a_int;
2467 precision = (arg < 0 ? 0 : arg);
2471 const CHAR_T *digitp = dp->precision_start + 1;
2474 while (digitp != dp->precision_end)
2475 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2479 switch (dp->conversion)
2482 case 'd': case 'i': case 'u':
2483 # if HAVE_LONG_LONG_INT
2484 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2486 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2487 * 0.30103 /* binary -> decimal */
2489 + 1; /* turn floor into ceil */
2492 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2494 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2495 * 0.30103 /* binary -> decimal */
2497 + 1; /* turn floor into ceil */
2500 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2501 * 0.30103 /* binary -> decimal */
2503 + 1; /* turn floor into ceil */
2504 if (tmp_length < precision)
2505 tmp_length = precision;
2506 /* Multiply by 2, as an estimate for FLAG_GROUP. */
2507 tmp_length = xsum (tmp_length, tmp_length);
2508 /* Add 1, to account for a leading sign. */
2509 tmp_length = xsum (tmp_length, 1);
2513 # if HAVE_LONG_LONG_INT
2514 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2516 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2517 * 0.333334 /* binary -> octal */
2519 + 1; /* turn floor into ceil */
2522 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2524 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2525 * 0.333334 /* binary -> octal */
2527 + 1; /* turn floor into ceil */
2530 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2531 * 0.333334 /* binary -> octal */
2533 + 1; /* turn floor into ceil */
2534 if (tmp_length < precision)
2535 tmp_length = precision;
2536 /* Add 1, to account for a leading sign. */
2537 tmp_length = xsum (tmp_length, 1);
2541 # if HAVE_LONG_LONG_INT
2542 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2544 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2545 * 0.25 /* binary -> hexadecimal */
2547 + 1; /* turn floor into ceil */
2550 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2552 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2553 * 0.25 /* binary -> hexadecimal */
2555 + 1; /* turn floor into ceil */
2558 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2559 * 0.25 /* binary -> hexadecimal */
2561 + 1; /* turn floor into ceil */
2562 if (tmp_length < precision)
2563 tmp_length = precision;
2564 /* Add 2, to account for a leading sign or alternate form. */
2565 tmp_length = xsum (tmp_length, 2);
2569 if (type == TYPE_LONGDOUBLE)
2571 (unsigned int) (LDBL_MAX_EXP
2572 * 0.30103 /* binary -> decimal */
2573 * 2 /* estimate for FLAG_GROUP */
2575 + 1 /* turn floor into ceil */
2576 + 10; /* sign, decimal point etc. */
2579 (unsigned int) (DBL_MAX_EXP
2580 * 0.30103 /* binary -> decimal */
2581 * 2 /* estimate for FLAG_GROUP */
2583 + 1 /* turn floor into ceil */
2584 + 10; /* sign, decimal point etc. */
2585 tmp_length = xsum (tmp_length, precision);
2588 case 'e': case 'E': case 'g': case 'G':
2590 12; /* sign, decimal point, exponent etc. */
2591 tmp_length = xsum (tmp_length, precision);
2595 if (type == TYPE_LONGDOUBLE)
2597 (unsigned int) (LDBL_DIG
2598 * 0.831 /* decimal -> hexadecimal */
2600 + 1; /* turn floor into ceil */
2603 (unsigned int) (DBL_DIG
2604 * 0.831 /* decimal -> hexadecimal */
2606 + 1; /* turn floor into ceil */
2607 if (tmp_length < precision)
2608 tmp_length = precision;
2609 /* Account for sign, decimal point etc. */
2610 tmp_length = xsum (tmp_length, 12);
2614 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
2615 if (type == TYPE_WIDE_CHAR)
2616 tmp_length = MB_CUR_MAX;
2624 if (type == TYPE_WIDE_STRING)
2627 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
2629 # if !WIDE_CHAR_VERSION
2630 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
2635 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
2640 (unsigned int) (sizeof (void *) * CHAR_BIT
2641 * 0.25 /* binary -> hexadecimal */
2643 + 1 /* turn floor into ceil */
2644 + 2; /* account for leading 0x */
2651 if (tmp_length < width)
2654 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2657 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2661 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2663 if (size_overflow_p (tmp_memsize))
2664 /* Overflow, would lead to out of memory. */
2666 tmp = (CHAR_T *) malloc (tmp_memsize);
2668 /* Out of memory. */
2673 /* Decide whether to perform the padding ourselves. */
2674 #if NEED_PRINTF_FLAG_ZERO
2675 switch (dp->conversion)
2677 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
2687 /* Construct the format string for calling snprintf or
2691 #if NEED_PRINTF_FLAG_GROUPING
2692 /* The underlying implementation doesn't support the ' flag.
2693 Produce no grouping characters in this case; this is
2694 acceptable because the grouping is locale dependent. */
2696 if (flags & FLAG_GROUP)
2699 if (flags & FLAG_LEFT)
2701 if (flags & FLAG_SHOWSIGN)
2703 if (flags & FLAG_SPACE)
2705 if (flags & FLAG_ALT)
2709 if (flags & FLAG_ZERO)
2711 if (dp->width_start != dp->width_end)
2713 size_t n = dp->width_end - dp->width_start;
2714 memcpy (fbp, dp->width_start, n * sizeof (CHAR_T));
2718 if (dp->precision_start != dp->precision_end)
2720 size_t n = dp->precision_end - dp->precision_start;
2721 memcpy (fbp, dp->precision_start, n * sizeof (CHAR_T));
2727 #if HAVE_LONG_LONG_INT
2728 case TYPE_LONGLONGINT:
2729 case TYPE_ULONGLONGINT:
2730 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2743 case TYPE_WIDE_CHAR:
2746 case TYPE_WIDE_STRING:
2750 case TYPE_LONGDOUBLE:
2756 #if NEED_PRINTF_DIRECTIVE_F
2757 if (dp->conversion == 'F')
2761 *fbp = dp->conversion;
2770 /* Construct the arguments for calling snprintf or sprintf. */
2772 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
2774 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2776 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
2778 if (dp->precision_arg_index != ARG_NONE)
2780 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2782 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
2786 /* Prepare checking whether snprintf returns the count
2788 ENSURE_ALLOCATION (xsum (length, 1));
2789 result[length] = '\0';
2798 maxlen = allocated - length;
2803 /* SNPRINTF can fail if maxlen > INT_MAX. */
2804 if (maxlen > INT_MAX)
2806 # define SNPRINTF_BUF(arg) \
2807 switch (prefix_count) \
2810 retcount = SNPRINTF (result + length, maxlen, buf, \
2814 retcount = SNPRINTF (result + length, maxlen, buf, \
2815 prefixes[0], arg, &count); \
2818 retcount = SNPRINTF (result + length, maxlen, buf, \
2819 prefixes[0], prefixes[1], arg, \
2826 # define SNPRINTF_BUF(arg) \
2827 switch (prefix_count) \
2830 count = sprintf (tmp, buf, arg); \
2833 count = sprintf (tmp, buf, prefixes[0], arg); \
2836 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
2848 int arg = a.arg[dp->arg_index].a.a_schar;
2854 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
2860 int arg = a.arg[dp->arg_index].a.a_short;
2866 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
2872 int arg = a.arg[dp->arg_index].a.a_int;
2878 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
2884 long int arg = a.arg[dp->arg_index].a.a_longint;
2890 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
2894 #if HAVE_LONG_LONG_INT
2895 case TYPE_LONGLONGINT:
2897 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
2901 case TYPE_ULONGLONGINT:
2903 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
2910 double arg = a.arg[dp->arg_index].a.a_double;
2914 case TYPE_LONGDOUBLE:
2916 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2922 int arg = a.arg[dp->arg_index].a.a_char;
2927 case TYPE_WIDE_CHAR:
2929 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
2936 const char *arg = a.arg[dp->arg_index].a.a_string;
2941 case TYPE_WIDE_STRING:
2943 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2950 void *arg = a.arg[dp->arg_index].a.a_pointer;
2959 /* Portability: Not all implementations of snprintf()
2960 are ISO C 99 compliant. Determine the number of
2961 bytes that snprintf() has produced or would have
2965 /* Verify that snprintf() has NUL-terminated its
2967 if (count < maxlen && result[length + count] != '\0')
2969 /* Portability hack. */
2970 if (retcount > count)
2975 /* snprintf() doesn't understand the '%n'
2979 /* Don't use the '%n' directive; instead, look
2980 at the snprintf() return value. */
2986 /* Look at the snprintf() return value. */
2989 /* HP-UX 10.20 snprintf() is doubly deficient:
2990 It doesn't understand the '%n' directive,
2991 *and* it returns -1 (rather than the length
2992 that would have been required) when the
2993 buffer is too small. */
2994 size_t bigger_need =
2995 xsum (xtimes (allocated, 2), 12);
2996 ENSURE_ALLOCATION (bigger_need);
3005 /* Attempt to handle failure. */
3008 if (!(result == resultbuf || result == NULL))
3010 if (buf_malloced != NULL)
3011 free (buf_malloced);
3017 /* Make room for the result. */
3018 if (count >= maxlen)
3020 /* Need at least count bytes. But allocate
3021 proportionally, to avoid looping eternally if
3022 snprintf() reports a too small count. */
3024 xmax (xsum (length, count), xtimes (allocated, 2));
3026 ENSURE_ALLOCATION (n);
3030 maxlen = allocated - length;
3034 /* Perform padding. */
3035 #if NEED_PRINTF_FLAG_ZERO
3036 if (pad_ourselves && has_width && count < width)
3039 /* Make room for the result. */
3040 if (width >= maxlen)
3042 /* Need at least width bytes. But allocate
3043 proportionally, to avoid looping eternally if
3044 snprintf() reports a too small count. */
3046 xmax (xsum (length + 1, width),
3047 xtimes (allocated, 2));
3050 ENSURE_ALLOCATION (n);
3052 maxlen = allocated - length; /* > width */
3054 /* Here width < maxlen. */
3058 CHAR_T * const rp = result + length;
3060 CHAR_T * const rp = tmp;
3062 CHAR_T *p = rp + count;
3063 size_t pad = width - count;
3064 CHAR_T *end = p + pad;
3065 CHAR_T *pad_ptr = (*rp == '-' ? rp + 1 : rp);
3066 /* No zero-padding of "inf" and "nan". */
3067 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
3068 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
3070 /* The generated string now extends from rp to p,
3071 with the zero padding insertion point being at
3074 if (flags & FLAG_LEFT)
3076 /* Pad with spaces on the right. */
3077 for (; pad > 0; pad--)
3080 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3082 /* Pad with zeroes. */
3087 for (; pad > 0; pad--)
3092 /* Pad with spaces on the left. */
3097 for (; pad > 0; pad--)
3101 count = width; /* = count + pad = end - rp */
3107 if (count >= tmp_length)
3108 /* tmp_length was incorrectly calculated - fix the
3113 /* Here still count < maxlen. */
3116 /* The snprintf() result did fit. */
3118 /* Append the sprintf() result. */
3119 memcpy (result + length, tmp, count * sizeof (CHAR_T));
3124 #if NEED_PRINTF_DIRECTIVE_F
3125 if (dp->conversion == 'F')
3127 /* Convert the %f result to upper case for %F. */
3128 CHAR_T *rp = result + length;
3130 for (rc = count; rc > 0; rc--, rp++)
3131 if (*rp >= 'a' && *rp <= 'z')
3132 *rp = *rp - 'a' + 'A';
3143 /* Add the final NUL. */
3144 ENSURE_ALLOCATION (xsum (length, 1));
3145 result[length] = '\0';
3147 if (result != resultbuf && length + 1 < allocated)
3149 /* Shrink the allocated memory if possible. */
3152 memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
3157 if (buf_malloced != NULL)
3158 free (buf_malloced);
3161 /* Note that we can produce a big string of a length > INT_MAX. POSIX
3162 says that snprintf() fails with errno = EOVERFLOW in this case, but
3163 that's only because snprintf() returns an 'int'. This function does
3164 not have this limitation. */
3168 if (!(result == resultbuf || result == NULL))
3170 if (buf_malloced != NULL)
3171 free (buf_malloced);
3177 if (!(result == resultbuf || result == NULL))
3179 if (buf_malloced != NULL)
3180 free (buf_malloced);