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_INFINITE && !defined IN_LIBINTL
61 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
66 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
69 # include "printf-frexp.h"
70 # include "isnanl-nolibm.h"
71 # include "printf-frexpl.h"
75 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
77 # define EOVERFLOW E2BIG
82 # define local_wcslen wcslen
84 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
85 a dependency towards this library, here is a local substitute.
86 Define this substitute only once, even if this file is included
87 twice in the same compilation unit. */
88 # ifndef local_wcslen_defined
89 # define local_wcslen_defined 1
91 local_wcslen (const wchar_t *s)
95 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
103 #if WIDE_CHAR_VERSION
104 # define VASNPRINTF vasnwprintf
105 # define CHAR_T wchar_t
106 # define DIRECTIVE wchar_t_directive
107 # define DIRECTIVES wchar_t_directives
108 # define PRINTF_PARSE wprintf_parse
109 # define USE_SNPRINTF 1
110 # if HAVE_DECL__SNWPRINTF
111 /* On Windows, the function swprintf() has a different signature than
112 on Unix; we use the _snwprintf() function instead. */
113 # define SNPRINTF _snwprintf
116 # define SNPRINTF swprintf
119 # define VASNPRINTF vasnprintf
121 # define DIRECTIVE char_directive
122 # define DIRECTIVES char_directives
123 # define PRINTF_PARSE printf_parse
124 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
125 But don't use it on BeOS, since BeOS snprintf produces no output if the
126 size argument is >= 0x3000000. */
127 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
128 # define USE_SNPRINTF 1
130 # define USE_SNPRINTF 0
132 # if HAVE_DECL__SNPRINTF
134 # define SNPRINTF _snprintf
137 # define SNPRINTF snprintf
138 /* Here we need to call the native snprintf, not rpl_snprintf. */
142 /* Here we need to call the native sprintf, not rpl_sprintf. */
145 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
146 /* Determine the decimal-point character according to the current locale. */
147 # ifndef decimal_point_char_defined
148 # define decimal_point_char_defined 1
150 decimal_point_char ()
153 /* Determine it in a multithread-safe way. We know nl_langinfo is
154 multithread-safe on glibc systems, but is not required to be multithread-
155 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
156 is rarely multithread-safe. */
157 # if HAVE_NL_LANGINFO && __GLIBC__
158 point = nl_langinfo (RADIXCHAR);
161 sprintf (pointbuf, "%#.0f", 1.0);
162 point = &pointbuf[1];
164 point = localeconv () -> decimal_point;
166 /* The decimal point is always a single byte: either '.' or ','. */
167 return (point[0] != '\0' ? point[0] : '.');
172 #if NEED_PRINTF_INFINITE && !defined IN_LIBINTL
174 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
176 is_infinite_or_zero (double x)
178 return isnan (x) || x + x == x;
183 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
185 /* Converting 'long double' to decimal without rare rounding bugs requires
186 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
187 (and slower) algorithms. */
189 typedef unsigned int mp_limb_t;
190 # define GMP_LIMB_BITS 32
191 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
193 typedef unsigned long long mp_twolimb_t;
194 # define GMP_TWOLIMB_BITS 64
195 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
197 /* Representation of a bignum >= 0. */
201 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
204 /* Compute the product of two bignums >= 0.
205 Return the allocated memory in case of success, NULL in case of memory
206 allocation failure. */
208 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
215 if (src1.nlimbs <= src2.nlimbs)
229 /* Now 0 <= len1 <= len2. */
232 /* src1 or src2 is zero. */
234 dest->limbs = (mp_limb_t *) malloc (1);
238 /* Here 1 <= len1 <= len2. */
244 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
247 for (k = len2; k > 0; )
249 for (i = 0; i < len1; i++)
251 mp_limb_t digit1 = p1[i];
252 mp_twolimb_t carry = 0;
253 for (j = 0; j < len2; j++)
255 mp_limb_t digit2 = p2[j];
256 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
258 dp[i + j] = (mp_limb_t) carry;
259 carry = carry >> GMP_LIMB_BITS;
261 dp[i + len2] = (mp_limb_t) carry;
264 while (dlen > 0 && dp[dlen - 1] == 0)
272 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
273 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
275 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
277 Return the allocated memory in case of success, NULL in case of memory
278 allocation failure. */
280 divide (mpn_t a, mpn_t b, mpn_t *q)
283 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
284 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
285 If m<n, then q:=0 and r:=a.
286 If m>=n=1, perform a single-precision division:
289 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
290 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
291 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
292 Normalise [q[m-1],...,q[0]], yields q.
293 If m>=n>1, perform a multiple-precision division:
294 We have a/b < beta^(m-n+1).
295 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
296 Shift a and b left by s bits, copying them. r:=a.
297 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
298 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
300 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
301 In case of overflow (q* >= beta) set q* := beta-1.
302 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
303 and c3 := b[n-2] * q*.
304 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
305 occurred. Furthermore 0 <= c3 < beta^2.
306 If there was overflow and
307 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
308 the next test can be skipped.}
309 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
310 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
312 Put r := r - b * q* * beta^j. In detail:
313 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
314 hence: u:=0, for i:=0 to n-1 do
316 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
317 u:=u div beta (+ 1, if carry in subtraction)
319 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
321 the carry u does not overflow.}
322 If a negative carry occurs, put q* := q* - 1
323 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
325 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
326 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
328 The room for q[j] can be allocated at the memory location of r[n+j].
329 Finally, round-to-even:
330 Shift r left by 1 bit.
331 If r > b or if r = b and q[0] is odd, q := q+1.
333 const mp_limb_t *a_ptr = a.limbs;
334 size_t a_len = a.nlimbs;
335 const mp_limb_t *b_ptr = b.limbs;
336 size_t b_len = b.nlimbs;
338 mp_limb_t *tmp_roomptr = NULL;
344 /* Allocate room for a_len+2 digits.
345 (Need a_len+1 digits for the real division and 1 more digit for the
346 final rounding of q.) */
347 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
352 while (a_len > 0 && a_ptr[a_len - 1] == 0)
359 /* Division by zero. */
361 if (b_ptr[b_len - 1] == 0)
367 /* Here m = a_len >= 0 and n = b_len > 0. */
371 /* m<n: trivial case. q=0, r := copy of a. */
374 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
375 q_ptr = roomptr + a_len;
380 /* n=1: single precision division.
381 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
385 mp_limb_t den = b_ptr[0];
386 mp_limb_t remainder = 0;
387 const mp_limb_t *sourceptr = a_ptr + a_len;
388 mp_limb_t *destptr = q_ptr + a_len;
390 for (count = a_len; count > 0; count--)
393 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
394 *--destptr = num / den;
395 remainder = num % den;
397 /* Normalise and store r. */
400 r_ptr[0] = remainder;
407 if (q_ptr[q_len - 1] == 0)
413 /* n>1: multiple precision division.
414 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
415 beta^(m-n-1) <= a/b < beta^(m-n+1). */
419 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
447 /* 0 <= s < GMP_LIMB_BITS.
448 Copy b, shifting it left by s bits. */
451 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
452 if (tmp_roomptr == NULL)
458 const mp_limb_t *sourceptr = b_ptr;
459 mp_limb_t *destptr = tmp_roomptr;
460 mp_twolimb_t accu = 0;
462 for (count = b_len; count > 0; count--)
464 accu += (mp_twolimb_t) *sourceptr++ << s;
465 *destptr++ = (mp_limb_t) accu;
466 accu = accu >> GMP_LIMB_BITS;
468 /* accu must be zero, since that was how s was determined. */
474 /* Copy a, shifting it left by s bits, yields r.
476 At the beginning: r = roomptr[0..a_len],
477 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
481 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
486 const mp_limb_t *sourceptr = a_ptr;
487 mp_limb_t *destptr = r_ptr;
488 mp_twolimb_t accu = 0;
490 for (count = a_len; count > 0; count--)
492 accu += (mp_twolimb_t) *sourceptr++ << s;
493 *destptr++ = (mp_limb_t) accu;
494 accu = accu >> GMP_LIMB_BITS;
496 *destptr++ = (mp_limb_t) accu;
498 q_ptr = roomptr + b_len;
499 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
501 size_t j = a_len - b_len; /* m-n */
502 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
503 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
504 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
505 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
506 /* Division loop, traversed m-n+1 times.
507 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
512 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
514 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
516 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
517 | r_ptr[j + b_len - 1];
518 q_star = num / b_msd;
523 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
524 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
525 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
526 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
527 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
529 If yes, jump directly to the subtraction loop.
530 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
531 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
532 if (r_ptr[j + b_len] > b_msd
533 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
534 /* r[j+n] >= b[n-1]+1 or
535 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
540 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
542 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
543 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
544 mp_twolimb_t c3 = /* b[n-2] * q* */
545 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
546 /* While c2 < c3, increase c2 and decrease c3.
547 Consider c3-c2. While it is > 0, decrease it by
548 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
549 this can happen only twice. */
552 q_star = q_star - 1; /* q* := q* - 1 */
553 if (c3 - c2 > b_msdd)
554 q_star = q_star - 1; /* q* := q* - 1 */
560 /* Subtract r := r - b * q* * beta^j. */
563 const mp_limb_t *sourceptr = b_ptr;
564 mp_limb_t *destptr = r_ptr + j;
565 mp_twolimb_t carry = 0;
567 for (count = b_len; count > 0; count--)
569 /* Here 0 <= carry <= q*. */
572 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
573 + (mp_limb_t) ~(*destptr);
574 /* Here 0 <= carry <= beta*q* + beta-1. */
575 *destptr++ = ~(mp_limb_t) carry;
576 carry = carry >> GMP_LIMB_BITS; /* <= q* */
578 cr = (mp_limb_t) carry;
580 /* Subtract cr from r_ptr[j + b_len], then forget about
582 if (cr > r_ptr[j + b_len])
584 /* Subtraction gave a carry. */
585 q_star = q_star - 1; /* q* := q* - 1 */
588 const mp_limb_t *sourceptr = b_ptr;
589 mp_limb_t *destptr = r_ptr + j;
592 for (count = b_len; count > 0; count--)
594 mp_limb_t source1 = *sourceptr++;
595 mp_limb_t source2 = *destptr;
596 *destptr++ = source1 + source2 + carry;
599 ? source1 >= (mp_limb_t) ~source2
600 : source1 > (mp_limb_t) ~source2);
603 /* Forget about the carry and about r[j+n]. */
606 /* q* is determined. Store it as q[j]. */
615 if (q_ptr[q_len - 1] == 0)
617 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
618 b is shifted left by s bits. */
619 /* Shift r right by s bits. */
622 mp_limb_t ptr = r_ptr + r_len;
623 mp_twolimb_t accu = 0;
625 for (count = r_len; count > 0; count--)
627 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
628 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
629 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
634 while (r_len > 0 && r_ptr[r_len - 1] == 0)
637 /* Compare r << 1 with b. */
645 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
646 | (i < r_len ? r_ptr[i] << 1 : 0);
647 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
657 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
662 for (i = 0; i < q_len; i++)
663 if (++(q_ptr[i]) != 0)
668 if (tmp_roomptr != NULL)
675 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
677 Destroys the contents of a.
678 Return the allocated memory - containing the decimal digits in low-to-high
679 order, terminated with a NUL character - in case of success, NULL in case
680 of memory allocation failure. */
682 convert_to_decimal (mpn_t a, size_t extra_zeroes)
684 mp_limb_t *a_ptr = a.limbs;
685 size_t a_len = a.nlimbs;
686 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
687 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
688 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
692 for (; extra_zeroes > 0; extra_zeroes--)
696 /* Divide a by 10^9, in-place. */
697 mp_limb_t remainder = 0;
698 mp_limb_t *ptr = a_ptr + a_len;
700 for (count = a_len; count > 0; count--)
703 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
704 *ptr = num / 1000000000;
705 remainder = num % 1000000000;
707 /* Store the remainder as 9 decimal digits. */
708 for (count = 9; count > 0; count--)
710 *d_ptr++ = '0' + (remainder % 10);
711 remainder = remainder / 10;
714 if (a_ptr[a_len - 1] == 0)
717 /* Remove leading zeroes. */
718 while (d_ptr > c_ptr && d_ptr[-1] == '0')
720 /* But keep at least one zero. */
723 /* Terminate the string. */
729 /* Assuming x is finite and >= 0:
730 write x as x = 2^e * m, where m is a bignum.
731 Return the allocated memory in case of success, NULL in case of memory
732 allocation failure. */
734 decode_long_double (long double x, int *ep, mpn_t *mp)
741 /* Allocate memory for result. */
742 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
743 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
746 /* Split into exponential part and mantissa. */
747 y = frexpl (x, &exp);
748 if (!(y >= 0.0L && y < 1.0L))
750 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
751 latter is an integer. */
752 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
753 I'm not sure whether it's safe to cast a 'long double' value between
754 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
755 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
757 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
758 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
761 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
764 if (!(y >= 0.0L && y < 1.0L))
766 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
769 if (!(y >= 0.0L && y < 1.0L))
771 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
776 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
779 if (!(y >= 0.0L && y < 1.0L))
781 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
785 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
788 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
791 if (!(y >= 0.0L && y < 1.0L))
793 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
796 if (!(y >= 0.0L && y < 1.0L))
798 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
803 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
806 *ep = exp - LDBL_MANT_BIT;
810 /* Assuming x is finite and >= 0, and n is an integer:
811 Returns the decimal representation of round (x * 10^n).
812 Return the allocated memory - containing the decimal digits in low-to-high
813 order, terminated with a NUL character - in case of success, NULL in case
814 of memory allocation failure. */
816 scale10_round_decimal_long_double (long double x, int n)
820 void *memory = decode_long_double (x, &e, &m);
827 unsigned int s_limbs;
836 /* x = 2^e * m, hence
837 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
838 = round (2^s * 5^n * m). */
841 /* Factor out a common power of 10 if possible. */
844 extra_zeroes = (s < n ? s : n);
848 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
849 Before converting to decimal, we need to compute
850 z = round (2^s * 5^n * m). */
851 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
852 sign. 2.322 is slightly larger than log(5)/log(2). */
853 abs_n = (n >= 0 ? n : -n);
854 abs_s = (s >= 0 ? s : -s);
855 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
856 + abs_s / GMP_LIMB_BITS + 1)
857 * sizeof (mp_limb_t));
858 if (pow5_ptr == NULL)
863 /* Initialize with 1. */
866 /* Multiply with 5^|n|. */
869 static mp_limb_t const small_pow5[13 + 1] =
871 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
872 48828125, 244140625, 1220703125
875 for (n13 = 0; n13 <= abs_n; n13 += 13)
877 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
879 mp_twolimb_t carry = 0;
880 for (j = 0; j < pow5_len; j++)
882 mp_limb_t digit2 = pow5_ptr[j];
883 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
884 pow5_ptr[j] = (mp_limb_t) carry;
885 carry = carry >> GMP_LIMB_BITS;
888 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
891 s_limbs = abs_s / GMP_LIMB_BITS;
892 s_bits = abs_s % GMP_LIMB_BITS;
893 if (n >= 0 ? s >= 0 : s <= 0)
895 /* Multiply with 2^|s|. */
898 mp_limb_t *ptr = pow5_ptr;
899 mp_twolimb_t accu = 0;
901 for (count = pow5_len; count > 0; count--)
903 accu += (mp_twolimb_t) *ptr << s_bits;
904 *ptr++ = (mp_limb_t) accu;
905 accu = accu >> GMP_LIMB_BITS;
909 *ptr = (mp_limb_t) accu;
916 for (count = pow5_len; count > 0;)
919 pow5_ptr[s_limbs + count] = pow5_ptr[count];
921 for (count = s_limbs; count > 0;)
928 pow5.limbs = pow5_ptr;
929 pow5.nlimbs = pow5_len;
932 /* Multiply m with pow5. No division needed. */
933 z_memory = multiply (m, pow5, &z);
937 /* Divide m by pow5 and round. */
938 z_memory = divide (m, pow5, &z);
943 pow5.limbs = pow5_ptr;
944 pow5.nlimbs = pow5_len;
948 Multiply m with pow5, then divide by 2^|s|. */
952 tmp_memory = multiply (m, pow5, &numerator);
953 if (tmp_memory == NULL)
959 /* Construct 2^|s|. */
961 mp_limb_t *ptr = pow5_ptr + pow5_len;
963 for (i = 0; i < s_limbs; i++)
965 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
966 denominator.limbs = ptr;
967 denominator.nlimbs = s_limbs + 1;
969 z_memory = divide (numerator, denominator, &z);
975 Multiply m with 2^s, then divide by pow5. */
978 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
979 * sizeof (mp_limb_t));
987 mp_limb_t *destptr = num_ptr;
990 for (i = 0; i < s_limbs; i++)
995 const mp_limb_t *sourceptr = m.limbs;
996 mp_twolimb_t accu = 0;
998 for (count = m.nlimbs; count > 0; count--)
1000 accu += (mp_twolimb_t) *sourceptr++ << s;
1001 *destptr++ = (mp_limb_t) accu;
1002 accu = accu >> GMP_LIMB_BITS;
1005 *destptr++ = (mp_limb_t) accu;
1009 const mp_limb_t *sourceptr = m.limbs;
1011 for (count = m.nlimbs; count > 0; count--)
1012 *destptr++ = *sourceptr++;
1014 numerator.limbs = num_ptr;
1015 numerator.nlimbs = destptr - num_ptr;
1017 z_memory = divide (numerator, pow5, &z);
1024 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1026 if (z_memory == NULL)
1028 digits = convert_to_decimal (z, extra_zeroes);
1033 /* Assuming x is finite and > 0:
1034 Return an approximation for n with 10^n <= x < 10^(n+1).
1035 The approximation is usually the right n, but may be off by 1 sometimes. */
1037 floorlog10l (long double x)
1044 /* Split into exponential part and mantissa. */
1045 y = frexpl (x, &exp);
1046 if (!(y >= 0.0L && y < 1.0L))
1052 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1054 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1055 exp -= GMP_LIMB_BITS;
1057 if (y < (1.0L / (1 << 16)))
1059 y *= 1.0L * (1 << 16);
1062 if (y < (1.0L / (1 << 8)))
1064 y *= 1.0L * (1 << 8);
1067 if (y < (1.0L / (1 << 4)))
1069 y *= 1.0L * (1 << 4);
1072 if (y < (1.0L / (1 << 2)))
1074 y *= 1.0L * (1 << 2);
1077 if (y < (1.0L / (1 << 1)))
1079 y *= 1.0L * (1 << 1);
1083 if (!(y >= 0.5L && y < 1.0L))
1085 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1088 if (z < 0.70710678118654752444)
1090 z *= 1.4142135623730950488;
1093 if (z < 0.8408964152537145431)
1095 z *= 1.1892071150027210667;
1098 if (z < 0.91700404320467123175)
1100 z *= 1.0905077326652576592;
1103 if (z < 0.9576032806985736469)
1105 z *= 1.0442737824274138403;
1108 /* Now 0.95 <= z <= 1.01. */
1110 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1111 Four terms are enough to get an approximation with error < 10^-7. */
1112 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1113 /* Finally multiply with log(2)/log(10), yields an approximation for
1115 l *= 0.30102999566398119523;
1116 /* Round down to the next integer. */
1117 return (int) l + (l < 0 ? -1 : 0);
1123 VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list args)
1128 if (PRINTF_PARSE (format, &d, &a) < 0)
1139 if (printf_fetchargs (args, &a) < 0)
1147 size_t buf_neededlength;
1149 CHAR_T *buf_malloced;
1153 /* Output string accumulator. */
1158 /* Allocate a small buffer that will hold a directive passed to
1159 sprintf or snprintf. */
1161 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1163 if (buf_neededlength < 4000 / sizeof (CHAR_T))
1165 buf = (CHAR_T *) alloca (buf_neededlength * sizeof (CHAR_T));
1166 buf_malloced = NULL;
1171 size_t buf_memsize = xtimes (buf_neededlength, sizeof (CHAR_T));
1172 if (size_overflow_p (buf_memsize))
1173 goto out_of_memory_1;
1174 buf = (CHAR_T *) malloc (buf_memsize);
1176 goto out_of_memory_1;
1180 if (resultbuf != NULL)
1183 allocated = *lengthp;
1192 result is either == resultbuf or == NULL or malloc-allocated.
1193 If length > 0, then result != NULL. */
1195 /* Ensures that allocated >= needed. Aborts through a jump to
1196 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1197 #define ENSURE_ALLOCATION(needed) \
1198 if ((needed) > allocated) \
1200 size_t memory_size; \
1203 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1204 if ((needed) > allocated) \
1205 allocated = (needed); \
1206 memory_size = xtimes (allocated, sizeof (CHAR_T)); \
1207 if (size_overflow_p (memory_size)) \
1208 goto out_of_memory; \
1209 if (result == resultbuf || result == NULL) \
1210 memory = (CHAR_T *) malloc (memory_size); \
1212 memory = (CHAR_T *) realloc (result, memory_size); \
1213 if (memory == NULL) \
1214 goto out_of_memory; \
1215 if (result == resultbuf && length > 0) \
1216 memcpy (memory, result, length * sizeof (CHAR_T)); \
1220 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1222 if (cp != dp->dir_start)
1224 size_t n = dp->dir_start - cp;
1225 size_t augmented_length = xsum (length, n);
1227 ENSURE_ALLOCATION (augmented_length);
1228 memcpy (result + length, cp, n * sizeof (CHAR_T));
1229 length = augmented_length;
1234 /* Execute a single directive. */
1235 if (dp->conversion == '%')
1237 size_t augmented_length;
1239 if (!(dp->arg_index == ARG_NONE))
1241 augmented_length = xsum (length, 1);
1242 ENSURE_ALLOCATION (augmented_length);
1243 result[length] = '%';
1244 length = augmented_length;
1248 if (!(dp->arg_index != ARG_NONE))
1251 if (dp->conversion == 'n')
1253 switch (a.arg[dp->arg_index].type)
1255 case TYPE_COUNT_SCHAR_POINTER:
1256 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1258 case TYPE_COUNT_SHORT_POINTER:
1259 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1261 case TYPE_COUNT_INT_POINTER:
1262 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1264 case TYPE_COUNT_LONGINT_POINTER:
1265 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1267 #if HAVE_LONG_LONG_INT
1268 case TYPE_COUNT_LONGLONGINT_POINTER:
1269 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1276 #if (NEED_PRINTF_INFINITE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
1277 else if ((dp->conversion == 'f' || dp->conversion == 'F'
1278 || dp->conversion == 'e' || dp->conversion == 'E'
1279 || dp->conversion == 'g' || dp->conversion == 'G')
1281 # if NEED_PRINTF_INFINITE
1282 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
1283 /* The systems (mingw) which produce wrong output
1284 for Inf and -Inf also do so for NaN and -0.0.
1285 Therefore we treat these cases here as well. */
1286 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
1288 # if NEED_PRINTF_LONG_DOUBLE
1289 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
1293 arg_type type = a.arg[dp->arg_index].type;
1294 int flags = dp->flags;
1307 if (dp->width_start != dp->width_end)
1309 if (dp->width_arg_index != ARG_NONE)
1313 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1315 arg = a.arg[dp->width_arg_index].a.a_int;
1318 /* "A negative field width is taken as a '-' flag
1319 followed by a positive field width." */
1321 width = (unsigned int) (-arg);
1328 const CHAR_T *digitp = dp->width_start;
1331 width = xsum (xtimes (width, 10), *digitp++ - '0');
1332 while (digitp != dp->width_end);
1339 if (dp->precision_start != dp->precision_end)
1341 if (dp->precision_arg_index != ARG_NONE)
1345 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1347 arg = a.arg[dp->precision_arg_index].a.a_int;
1348 /* "A negative precision is taken as if the precision
1358 const CHAR_T *digitp = dp->precision_start + 1;
1361 while (digitp != dp->precision_end)
1362 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1367 /* POSIX specifies the default precision to be 6 for %f, %F,
1368 %e, %E, but not for %g, %G. Implementations appear to use
1369 the same default precision also for %g, %G. */
1373 /* Allocate a temporary buffer of sufficient size. */
1374 # if NEED_PRINTF_INFINITE && NEED_PRINTF_LONG_DOUBLE
1375 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
1376 # elif NEED_PRINTF_LONG_DOUBLE
1377 tmp_length = LDBL_DIG + 1;
1378 # elif NEED_PRINTF_INFINITE
1381 if (tmp_length < precision)
1382 tmp_length = precision;
1383 # if NEED_PRINTF_LONG_DOUBLE
1384 # if NEED_PRINTF_INFINITE
1385 if (type == TYPE_LONGDOUBLE)
1387 if (dp->conversion == 'f' || dp->conversion == 'F')
1389 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1390 if (!(isnanl (arg) || arg + arg == arg))
1392 /* arg is finite and nonzero. */
1393 int exponent = floorlog10l (arg < 0 ? -arg : arg);
1394 if (exponent >= 0 && tmp_length < exponent + precision)
1395 tmp_length = exponent + precision;
1399 /* Account for sign, decimal point etc. */
1400 tmp_length = xsum (tmp_length, 12);
1402 if (tmp_length < width)
1405 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1407 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1411 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1413 if (size_overflow_p (tmp_memsize))
1414 /* Overflow, would lead to out of memory. */
1416 tmp = (CHAR_T *) malloc (tmp_memsize);
1418 /* Out of memory. */
1425 # if NEED_PRINTF_LONG_DOUBLE
1426 # if NEED_PRINTF_INFINITE
1427 if (type == TYPE_LONGDOUBLE)
1430 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1434 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1436 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1440 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1446 DECL_LONG_DOUBLE_ROUNDING
1448 BEGIN_LONG_DOUBLE_ROUNDING ();
1450 if (signbit (arg)) /* arg < 0.0L or negative zero */
1458 else if (flags & FLAG_SHOWSIGN)
1460 else if (flags & FLAG_SPACE)
1463 if (arg > 0.0L && arg + arg == arg)
1465 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1467 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1471 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1478 if (dp->conversion == 'f' || dp->conversion == 'F')
1484 scale10_round_decimal_long_double (arg, precision);
1487 END_LONG_DOUBLE_ROUNDING ();
1490 ndigits = strlen (digits);
1492 if (ndigits > precision)
1496 *p++ = digits[ndigits];
1498 while (ndigits > precision);
1501 /* Here ndigits <= precision. */
1502 if ((flags & FLAG_ALT) || precision > 0)
1504 *p++ = decimal_point_char ();
1505 for (; precision > ndigits; precision--)
1510 *p++ = digits[ndigits];
1516 else if (dp->conversion == 'e' || dp->conversion == 'E')
1524 if ((flags & FLAG_ALT) || precision > 0)
1526 *p++ = decimal_point_char ();
1527 for (; precision > 0; precision--)
1538 exponent = floorlog10l (arg);
1543 scale10_round_decimal_long_double (arg,
1544 (int)precision - exponent);
1547 END_LONG_DOUBLE_ROUNDING ();
1550 ndigits = strlen (digits);
1552 if (ndigits == precision + 1)
1554 if (ndigits < precision
1555 || ndigits > precision + 2)
1556 /* The exponent was not guessed
1557 precisely enough. */
1560 /* None of two values of exponent is
1561 the right one. Prevent an endless
1565 if (ndigits == precision)
1572 /* Here ndigits = precision+1. */
1573 *p++ = digits[--ndigits];
1574 if ((flags & FLAG_ALT) || precision > 0)
1576 *p++ = decimal_point_char ();
1580 *p++ = digits[ndigits];
1587 *p++ = dp->conversion; /* 'e' or 'E' */
1588 # if WIDE_CHAR_VERSION
1590 static const wchar_t decimal_format[] =
1591 { '%', '+', '.', '2', 'd', '\0' };
1592 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1595 sprintf (p, "%+.2d", exponent);
1600 else if (dp->conversion == 'g' || dp->conversion == 'G')
1604 /* precision >= 1. */
1607 /* The exponent is 0, >= -4, < precision.
1608 Use fixed-point notation. */
1610 size_t ndigits = precision;
1611 /* Number of trailing zeroes that have to be
1614 (flags & FLAG_ALT ? 0 : precision - 1);
1618 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1620 *p++ = decimal_point_char ();
1621 while (ndigits > nzeroes)
1637 exponent = floorlog10l (arg);
1642 scale10_round_decimal_long_double (arg,
1643 (int)(precision - 1) - exponent);
1646 END_LONG_DOUBLE_ROUNDING ();
1649 ndigits = strlen (digits);
1651 if (ndigits == precision)
1653 if (ndigits < precision - 1
1654 || ndigits > precision + 1)
1655 /* The exponent was not guessed
1656 precisely enough. */
1659 /* None of two values of exponent is
1660 the right one. Prevent an endless
1664 if (ndigits < precision)
1670 /* Here ndigits = precision. */
1672 /* Determine the number of trailing zeroes
1673 that have to be dropped. */
1675 if ((flags & FLAG_ALT) == 0)
1676 while (nzeroes < ndigits
1677 && digits[nzeroes] == '0')
1680 /* The exponent is now determined. */
1682 && exponent < (long)precision)
1684 /* Fixed-point notation:
1685 max(exponent,0)+1 digits, then the
1686 decimal point, then the remaining
1687 digits without trailing zeroes. */
1690 size_t count = exponent + 1;
1691 /* Note: count <= precision = ndigits. */
1692 for (; count > 0; count--)
1693 *p++ = digits[--ndigits];
1694 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1696 *p++ = decimal_point_char ();
1697 while (ndigits > nzeroes)
1700 *p++ = digits[ndigits];
1706 size_t count = -exponent - 1;
1708 *p++ = decimal_point_char ();
1709 for (; count > 0; count--)
1711 while (ndigits > nzeroes)
1714 *p++ = digits[ndigits];
1720 /* Exponential notation. */
1721 *p++ = digits[--ndigits];
1722 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1724 *p++ = decimal_point_char ();
1725 while (ndigits > nzeroes)
1728 *p++ = digits[ndigits];
1731 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
1732 # if WIDE_CHAR_VERSION
1734 static const wchar_t decimal_format[] =
1735 { '%', '+', '.', '2', 'd', '\0' };
1736 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1739 sprintf (p, "%+.2d", exponent);
1752 END_LONG_DOUBLE_ROUNDING ();
1755 # if NEED_PRINTF_INFINITE
1759 # if NEED_PRINTF_INFINITE
1761 /* Simpler than above: handle only NaN, Infinity, zero. */
1762 double arg = a.arg[dp->arg_index].a.a_double;
1766 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1768 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1772 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1779 if (signbit (arg)) /* arg < 0.0L or negative zero */
1787 else if (flags & FLAG_SHOWSIGN)
1789 else if (flags & FLAG_SPACE)
1792 if (arg > 0.0 && arg + arg == arg)
1794 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1796 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1800 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1810 if (dp->conversion == 'f' || dp->conversion == 'F')
1813 if ((flags & FLAG_ALT) || precision > 0)
1815 *p++ = decimal_point_char ();
1816 for (; precision > 0; precision--)
1820 else if (dp->conversion == 'e' || dp->conversion == 'E')
1823 if ((flags & FLAG_ALT) || precision > 0)
1825 *p++ = decimal_point_char ();
1826 for (; precision > 0; precision--)
1829 *p++ = dp->conversion; /* 'e' or 'E' */
1831 /* Produce the same number of exponent digits as
1832 the native printf implementation. */
1833 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
1839 else if (dp->conversion == 'g' || dp->conversion == 'G')
1842 if (flags & FLAG_ALT)
1845 (precision > 0 ? precision - 1 : 0);
1846 *p++ = decimal_point_char ();
1847 for (; ndigits > 0; --ndigits)
1858 /* The generated string now extends from tmp to p, with the
1859 zero padding insertion point being at pad_ptr. */
1860 if (has_width && p - tmp < width)
1862 size_t pad = width - (p - tmp);
1863 CHAR_T *end = p + pad;
1865 if (flags & FLAG_LEFT)
1867 /* Pad with spaces on the right. */
1868 for (; pad > 0; pad--)
1871 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
1873 /* Pad with zeroes. */
1878 for (; pad > 0; pad--)
1883 /* Pad with spaces on the left. */
1888 for (; pad > 0; pad--)
1896 size_t count = p - tmp;
1898 if (count >= tmp_length)
1899 /* tmp_length was incorrectly calculated - fix the
1903 /* Make room for the result. */
1904 if (count >= allocated - length)
1906 size_t n = xsum (length, count);
1908 ENSURE_ALLOCATION (n);
1911 /* Append the result. */
1912 memcpy (result + length, tmp, count * sizeof (CHAR_T));
1919 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
1920 else if (dp->conversion == 'a' || dp->conversion == 'A')
1922 arg_type type = a.arg[dp->arg_index].type;
1923 int flags = dp->flags;
1936 if (dp->width_start != dp->width_end)
1938 if (dp->width_arg_index != ARG_NONE)
1942 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1944 arg = a.arg[dp->width_arg_index].a.a_int;
1947 /* "A negative field width is taken as a '-' flag
1948 followed by a positive field width." */
1950 width = (unsigned int) (-arg);
1957 const CHAR_T *digitp = dp->width_start;
1960 width = xsum (xtimes (width, 10), *digitp++ - '0');
1961 while (digitp != dp->width_end);
1968 if (dp->precision_start != dp->precision_end)
1970 if (dp->precision_arg_index != ARG_NONE)
1974 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1976 arg = a.arg[dp->precision_arg_index].a.a_int;
1977 /* "A negative precision is taken as if the precision
1987 const CHAR_T *digitp = dp->precision_start + 1;
1990 while (digitp != dp->precision_end)
1991 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1996 /* Allocate a temporary buffer of sufficient size. */
1997 if (type == TYPE_LONGDOUBLE)
1999 (unsigned int) ((LDBL_DIG + 1)
2000 * 0.831 /* decimal -> hexadecimal */
2002 + 1; /* turn floor into ceil */
2005 (unsigned int) ((DBL_DIG + 1)
2006 * 0.831 /* decimal -> hexadecimal */
2008 + 1; /* turn floor into ceil */
2009 if (tmp_length < precision)
2010 tmp_length = precision;
2011 /* Account for sign, decimal point etc. */
2012 tmp_length = xsum (tmp_length, 12);
2014 if (tmp_length < width)
2017 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2019 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2023 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2025 if (size_overflow_p (tmp_memsize))
2026 /* Overflow, would lead to out of memory. */
2028 tmp = (CHAR_T *) malloc (tmp_memsize);
2030 /* Out of memory. */
2036 if (type == TYPE_LONGDOUBLE)
2038 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2042 if (dp->conversion == 'A')
2044 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2048 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2054 DECL_LONG_DOUBLE_ROUNDING
2056 BEGIN_LONG_DOUBLE_ROUNDING ();
2058 if (signbit (arg)) /* arg < 0.0L or negative zero */
2066 else if (flags & FLAG_SHOWSIGN)
2068 else if (flags & FLAG_SPACE)
2071 if (arg > 0.0L && arg + arg == arg)
2073 if (dp->conversion == 'A')
2075 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2079 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2085 long double mantissa;
2088 mantissa = printf_frexpl (arg, &exponent);
2096 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2098 /* Round the mantissa. */
2099 long double tail = mantissa;
2102 for (q = precision; ; q--)
2104 int digit = (int) tail;
2108 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2117 for (q = precision; q > 0; q--)
2123 *p++ = dp->conversion - 'A' + 'X';
2128 digit = (int) mantissa;
2131 if ((flags & FLAG_ALT)
2132 || mantissa > 0.0L || precision > 0)
2134 *p++ = decimal_point_char ();
2135 /* This loop terminates because we assume
2136 that FLT_RADIX is a power of 2. */
2137 while (mantissa > 0.0L)
2140 digit = (int) mantissa;
2145 : dp->conversion - 10);
2149 while (precision > 0)
2156 *p++ = dp->conversion - 'A' + 'P';
2157 # if WIDE_CHAR_VERSION
2159 static const wchar_t decimal_format[] =
2160 { '%', '+', 'd', '\0' };
2161 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2164 sprintf (p, "%+d", exponent);
2170 END_LONG_DOUBLE_ROUNDING ();
2175 double arg = a.arg[dp->arg_index].a.a_double;
2179 if (dp->conversion == 'A')
2181 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2185 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2192 if (signbit (arg)) /* arg < 0.0 or negative zero */
2200 else if (flags & FLAG_SHOWSIGN)
2202 else if (flags & FLAG_SPACE)
2205 if (arg > 0.0 && arg + arg == arg)
2207 if (dp->conversion == 'A')
2209 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2213 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2222 mantissa = printf_frexp (arg, &exponent);
2230 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2232 /* Round the mantissa. */
2233 double tail = mantissa;
2236 for (q = precision; ; q--)
2238 int digit = (int) tail;
2242 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2251 for (q = precision; q > 0; q--)
2257 *p++ = dp->conversion - 'A' + 'X';
2262 digit = (int) mantissa;
2265 if ((flags & FLAG_ALT)
2266 || mantissa > 0.0 || precision > 0)
2268 *p++ = decimal_point_char ();
2269 /* This loop terminates because we assume
2270 that FLT_RADIX is a power of 2. */
2271 while (mantissa > 0.0)
2274 digit = (int) mantissa;
2279 : dp->conversion - 10);
2283 while (precision > 0)
2290 *p++ = dp->conversion - 'A' + 'P';
2291 # if WIDE_CHAR_VERSION
2293 static const wchar_t decimal_format[] =
2294 { '%', '+', 'd', '\0' };
2295 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2298 sprintf (p, "%+d", exponent);
2305 /* The generated string now extends from tmp to p, with the
2306 zero padding insertion point being at pad_ptr. */
2307 if (has_width && p - tmp < width)
2309 size_t pad = width - (p - tmp);
2310 CHAR_T *end = p + pad;
2312 if (flags & FLAG_LEFT)
2314 /* Pad with spaces on the right. */
2315 for (; pad > 0; pad--)
2318 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2320 /* Pad with zeroes. */
2325 for (; pad > 0; pad--)
2330 /* Pad with spaces on the left. */
2335 for (; pad > 0; pad--)
2343 size_t count = p - tmp;
2345 if (count >= tmp_length)
2346 /* tmp_length was incorrectly calculated - fix the
2350 /* Make room for the result. */
2351 if (count >= allocated - length)
2353 size_t n = xsum (length, count);
2355 ENSURE_ALLOCATION (n);
2358 /* Append the result. */
2359 memcpy (result + length, tmp, count * sizeof (CHAR_T));
2368 arg_type type = a.arg[dp->arg_index].type;
2369 int flags = dp->flags;
2370 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2374 #if NEED_PRINTF_FLAG_ZERO
2377 # define pad_ourselves 0
2380 unsigned int prefix_count;
2388 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2391 if (dp->width_start != dp->width_end)
2393 if (dp->width_arg_index != ARG_NONE)
2397 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2399 arg = a.arg[dp->width_arg_index].a.a_int;
2402 /* "A negative field width is taken as a '-' flag
2403 followed by a positive field width." */
2405 width = (unsigned int) (-arg);
2412 const CHAR_T *digitp = dp->width_start;
2415 width = xsum (xtimes (width, 10), *digitp++ - '0');
2416 while (digitp != dp->width_end);
2423 /* Allocate a temporary buffer of sufficient size for calling
2429 if (dp->precision_start != dp->precision_end)
2431 if (dp->precision_arg_index != ARG_NONE)
2435 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2437 arg = a.arg[dp->precision_arg_index].a.a_int;
2438 precision = (arg < 0 ? 0 : arg);
2442 const CHAR_T *digitp = dp->precision_start + 1;
2445 while (digitp != dp->precision_end)
2446 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2450 switch (dp->conversion)
2453 case 'd': case 'i': case 'u':
2454 # if HAVE_LONG_LONG_INT
2455 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2457 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2458 * 0.30103 /* binary -> decimal */
2460 + 1; /* turn floor into ceil */
2463 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2465 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2466 * 0.30103 /* binary -> decimal */
2468 + 1; /* turn floor into ceil */
2471 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2472 * 0.30103 /* binary -> decimal */
2474 + 1; /* turn floor into ceil */
2475 if (tmp_length < precision)
2476 tmp_length = precision;
2477 /* Multiply by 2, as an estimate for FLAG_GROUP. */
2478 tmp_length = xsum (tmp_length, tmp_length);
2479 /* Add 1, to account for a leading sign. */
2480 tmp_length = xsum (tmp_length, 1);
2484 # if HAVE_LONG_LONG_INT
2485 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2487 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2488 * 0.333334 /* binary -> octal */
2490 + 1; /* turn floor into ceil */
2493 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2495 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2496 * 0.333334 /* binary -> octal */
2498 + 1; /* turn floor into ceil */
2501 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2502 * 0.333334 /* binary -> octal */
2504 + 1; /* turn floor into ceil */
2505 if (tmp_length < precision)
2506 tmp_length = precision;
2507 /* Add 1, to account for a leading sign. */
2508 tmp_length = xsum (tmp_length, 1);
2512 # if HAVE_LONG_LONG_INT
2513 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2515 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2516 * 0.25 /* binary -> hexadecimal */
2518 + 1; /* turn floor into ceil */
2521 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2523 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2524 * 0.25 /* binary -> hexadecimal */
2526 + 1; /* turn floor into ceil */
2529 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2530 * 0.25 /* binary -> hexadecimal */
2532 + 1; /* turn floor into ceil */
2533 if (tmp_length < precision)
2534 tmp_length = precision;
2535 /* Add 2, to account for a leading sign or alternate form. */
2536 tmp_length = xsum (tmp_length, 2);
2540 if (type == TYPE_LONGDOUBLE)
2542 (unsigned int) (LDBL_MAX_EXP
2543 * 0.30103 /* binary -> decimal */
2544 * 2 /* estimate for FLAG_GROUP */
2546 + 1 /* turn floor into ceil */
2547 + 10; /* sign, decimal point etc. */
2550 (unsigned int) (DBL_MAX_EXP
2551 * 0.30103 /* binary -> decimal */
2552 * 2 /* estimate for FLAG_GROUP */
2554 + 1 /* turn floor into ceil */
2555 + 10; /* sign, decimal point etc. */
2556 tmp_length = xsum (tmp_length, precision);
2559 case 'e': case 'E': case 'g': case 'G':
2561 12; /* sign, decimal point, exponent etc. */
2562 tmp_length = xsum (tmp_length, precision);
2566 if (type == TYPE_LONGDOUBLE)
2568 (unsigned int) (LDBL_DIG
2569 * 0.831 /* decimal -> hexadecimal */
2571 + 1; /* turn floor into ceil */
2574 (unsigned int) (DBL_DIG
2575 * 0.831 /* decimal -> hexadecimal */
2577 + 1; /* turn floor into ceil */
2578 if (tmp_length < precision)
2579 tmp_length = precision;
2580 /* Account for sign, decimal point etc. */
2581 tmp_length = xsum (tmp_length, 12);
2585 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
2586 if (type == TYPE_WIDE_CHAR)
2587 tmp_length = MB_CUR_MAX;
2595 if (type == TYPE_WIDE_STRING)
2598 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
2600 # if !WIDE_CHAR_VERSION
2601 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
2606 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
2611 (unsigned int) (sizeof (void *) * CHAR_BIT
2612 * 0.25 /* binary -> hexadecimal */
2614 + 1 /* turn floor into ceil */
2615 + 2; /* account for leading 0x */
2622 if (tmp_length < width)
2625 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2628 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2632 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2634 if (size_overflow_p (tmp_memsize))
2635 /* Overflow, would lead to out of memory. */
2637 tmp = (CHAR_T *) malloc (tmp_memsize);
2639 /* Out of memory. */
2644 /* Decide whether to perform the padding ourselves. */
2645 #if NEED_PRINTF_FLAG_ZERO
2646 switch (dp->conversion)
2648 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
2658 /* Construct the format string for calling snprintf or
2662 #if NEED_PRINTF_FLAG_GROUPING
2663 /* The underlying implementation doesn't support the ' flag.
2664 Produce no grouping characters in this case; this is
2665 acceptable because the grouping is locale dependent. */
2667 if (flags & FLAG_GROUP)
2670 if (flags & FLAG_LEFT)
2672 if (flags & FLAG_SHOWSIGN)
2674 if (flags & FLAG_SPACE)
2676 if (flags & FLAG_ALT)
2680 if (flags & FLAG_ZERO)
2682 if (dp->width_start != dp->width_end)
2684 size_t n = dp->width_end - dp->width_start;
2685 memcpy (fbp, dp->width_start, n * sizeof (CHAR_T));
2689 if (dp->precision_start != dp->precision_end)
2691 size_t n = dp->precision_end - dp->precision_start;
2692 memcpy (fbp, dp->precision_start, n * sizeof (CHAR_T));
2698 #if HAVE_LONG_LONG_INT
2699 case TYPE_LONGLONGINT:
2700 case TYPE_ULONGLONGINT:
2701 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2714 case TYPE_WIDE_CHAR:
2717 case TYPE_WIDE_STRING:
2721 case TYPE_LONGDOUBLE:
2727 #if NEED_PRINTF_DIRECTIVE_F
2728 if (dp->conversion == 'F')
2732 *fbp = dp->conversion;
2741 /* Construct the arguments for calling snprintf or sprintf. */
2743 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
2745 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2747 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
2749 if (dp->precision_arg_index != ARG_NONE)
2751 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2753 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
2757 /* Prepare checking whether snprintf returns the count
2759 ENSURE_ALLOCATION (xsum (length, 1));
2760 result[length] = '\0';
2769 maxlen = allocated - length;
2774 /* SNPRINTF can fail if maxlen > INT_MAX. */
2775 if (maxlen > INT_MAX)
2777 # define SNPRINTF_BUF(arg) \
2778 switch (prefix_count) \
2781 retcount = SNPRINTF (result + length, maxlen, buf, \
2785 retcount = SNPRINTF (result + length, maxlen, buf, \
2786 prefixes[0], arg, &count); \
2789 retcount = SNPRINTF (result + length, maxlen, buf, \
2790 prefixes[0], prefixes[1], arg, \
2797 # define SNPRINTF_BUF(arg) \
2798 switch (prefix_count) \
2801 count = sprintf (tmp, buf, arg); \
2804 count = sprintf (tmp, buf, prefixes[0], arg); \
2807 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
2819 int arg = a.arg[dp->arg_index].a.a_schar;
2825 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
2831 int arg = a.arg[dp->arg_index].a.a_short;
2837 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
2843 int arg = a.arg[dp->arg_index].a.a_int;
2849 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
2855 long int arg = a.arg[dp->arg_index].a.a_longint;
2861 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
2865 #if HAVE_LONG_LONG_INT
2866 case TYPE_LONGLONGINT:
2868 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
2872 case TYPE_ULONGLONGINT:
2874 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
2881 double arg = a.arg[dp->arg_index].a.a_double;
2885 case TYPE_LONGDOUBLE:
2887 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2893 int arg = a.arg[dp->arg_index].a.a_char;
2898 case TYPE_WIDE_CHAR:
2900 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
2907 const char *arg = a.arg[dp->arg_index].a.a_string;
2912 case TYPE_WIDE_STRING:
2914 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2921 void *arg = a.arg[dp->arg_index].a.a_pointer;
2930 /* Portability: Not all implementations of snprintf()
2931 are ISO C 99 compliant. Determine the number of
2932 bytes that snprintf() has produced or would have
2936 /* Verify that snprintf() has NUL-terminated its
2938 if (count < maxlen && result[length + count] != '\0')
2940 /* Portability hack. */
2941 if (retcount > count)
2946 /* snprintf() doesn't understand the '%n'
2950 /* Don't use the '%n' directive; instead, look
2951 at the snprintf() return value. */
2957 /* Look at the snprintf() return value. */
2960 /* HP-UX 10.20 snprintf() is doubly deficient:
2961 It doesn't understand the '%n' directive,
2962 *and* it returns -1 (rather than the length
2963 that would have been required) when the
2964 buffer is too small. */
2965 size_t bigger_need =
2966 xsum (xtimes (allocated, 2), 12);
2967 ENSURE_ALLOCATION (bigger_need);
2976 /* Attempt to handle failure. */
2979 if (!(result == resultbuf || result == NULL))
2981 if (buf_malloced != NULL)
2982 free (buf_malloced);
2988 /* Make room for the result. */
2989 if (count >= maxlen)
2991 /* Need at least count bytes. But allocate
2992 proportionally, to avoid looping eternally if
2993 snprintf() reports a too small count. */
2995 xmax (xsum (length, count), xtimes (allocated, 2));
2997 ENSURE_ALLOCATION (n);
3001 maxlen = allocated - length;
3005 /* Perform padding. */
3006 #if NEED_PRINTF_FLAG_ZERO
3007 if (pad_ourselves && has_width && count < width)
3010 /* Make room for the result. */
3011 if (width >= maxlen)
3013 /* Need at least width bytes. But allocate
3014 proportionally, to avoid looping eternally if
3015 snprintf() reports a too small count. */
3017 xmax (xsum (length + 1, width),
3018 xtimes (allocated, 2));
3021 ENSURE_ALLOCATION (n);
3023 maxlen = allocated - length; /* > width */
3025 /* Here width < maxlen. */
3029 CHAR_T * const rp = result + length;
3031 CHAR_T * const rp = tmp;
3033 CHAR_T *p = rp + count;
3034 size_t pad = width - count;
3035 CHAR_T *end = p + pad;
3036 CHAR_T *pad_ptr = (*rp == '-' ? rp + 1 : rp);
3037 /* No zero-padding of "inf" and "nan". */
3038 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
3039 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
3041 /* The generated string now extends from rp to p,
3042 with the zero padding insertion point being at
3045 if (flags & FLAG_LEFT)
3047 /* Pad with spaces on the right. */
3048 for (; pad > 0; pad--)
3051 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3053 /* Pad with zeroes. */
3058 for (; pad > 0; pad--)
3063 /* Pad with spaces on the left. */
3068 for (; pad > 0; pad--)
3072 count = width; /* = count + pad = end - rp */
3078 if (count >= tmp_length)
3079 /* tmp_length was incorrectly calculated - fix the
3084 /* Here still count < maxlen. */
3087 /* The snprintf() result did fit. */
3089 /* Append the sprintf() result. */
3090 memcpy (result + length, tmp, count * sizeof (CHAR_T));
3095 #if NEED_PRINTF_DIRECTIVE_F
3096 if (dp->conversion == 'F')
3098 /* Convert the %f result to upper case for %F. */
3099 CHAR_T *rp = result + length;
3101 for (rc = count; rc > 0; rc--, rp++)
3102 if (*rp >= 'a' && *rp <= 'z')
3103 *rp = *rp - 'a' + 'A';
3114 /* Add the final NUL. */
3115 ENSURE_ALLOCATION (xsum (length, 1));
3116 result[length] = '\0';
3118 if (result != resultbuf && length + 1 < allocated)
3120 /* Shrink the allocated memory if possible. */
3123 memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
3128 if (buf_malloced != NULL)
3129 free (buf_malloced);
3132 /* Note that we can produce a big string of a length > INT_MAX. POSIX
3133 says that snprintf() fails with errno = EOVERFLOW in this case, but
3134 that's only because snprintf() returns an 'int'. This function does
3135 not have this limitation. */
3139 if (!(result == resultbuf || result == NULL))
3141 if (buf_malloced != NULL)
3142 free (buf_malloced);
3148 if (!(result == resultbuf || result == NULL))
3150 if (buf_malloced != NULL)
3151 free (buf_malloced);