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, -Inf, and NaN also do so for -0.0.
1301 Therefore we treat this case 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 /* Some systems produce wrong output for Inf,
1310 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
1314 # if NEED_PRINTF_INFINITE_DOUBLE && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
1315 arg_type type = a.arg[dp->arg_index].type;
1317 int flags = dp->flags;
1330 if (dp->width_start != dp->width_end)
1332 if (dp->width_arg_index != ARG_NONE)
1336 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1338 arg = a.arg[dp->width_arg_index].a.a_int;
1341 /* "A negative field width is taken as a '-' flag
1342 followed by a positive field width." */
1344 width = (unsigned int) (-arg);
1351 const CHAR_T *digitp = dp->width_start;
1354 width = xsum (xtimes (width, 10), *digitp++ - '0');
1355 while (digitp != dp->width_end);
1362 if (dp->precision_start != dp->precision_end)
1364 if (dp->precision_arg_index != ARG_NONE)
1368 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1370 arg = a.arg[dp->precision_arg_index].a.a_int;
1371 /* "A negative precision is taken as if the precision
1381 const CHAR_T *digitp = dp->precision_start + 1;
1384 while (digitp != dp->precision_end)
1385 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1390 /* POSIX specifies the default precision to be 6 for %f, %F,
1391 %e, %E, but not for %g, %G. Implementations appear to use
1392 the same default precision also for %g, %G. */
1396 /* Allocate a temporary buffer of sufficient size. */
1397 # if NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
1398 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
1399 # elif NEED_PRINTF_LONG_DOUBLE
1400 tmp_length = LDBL_DIG + 1;
1404 if (tmp_length < precision)
1405 tmp_length = precision;
1406 # if NEED_PRINTF_LONG_DOUBLE
1407 # if NEED_PRINTF_INFINITE_DOUBLE
1408 if (type == TYPE_LONGDOUBLE)
1410 if (dp->conversion == 'f' || dp->conversion == 'F')
1412 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1413 if (!(isnanl (arg) || arg + arg == arg))
1415 /* arg is finite and nonzero. */
1416 int exponent = floorlog10l (arg < 0 ? -arg : arg);
1417 if (exponent >= 0 && tmp_length < exponent + precision)
1418 tmp_length = exponent + precision;
1422 /* Account for sign, decimal point etc. */
1423 tmp_length = xsum (tmp_length, 12);
1425 if (tmp_length < width)
1428 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1430 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1434 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1436 if (size_overflow_p (tmp_memsize))
1437 /* Overflow, would lead to out of memory. */
1439 tmp = (CHAR_T *) malloc (tmp_memsize);
1441 /* Out of memory. */
1448 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
1449 # if NEED_PRINTF_INFINITE_DOUBLE
1450 if (type == TYPE_LONGDOUBLE)
1453 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1457 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1459 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1463 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1469 DECL_LONG_DOUBLE_ROUNDING
1471 BEGIN_LONG_DOUBLE_ROUNDING ();
1473 if (signbit (arg)) /* arg < 0.0L or negative zero */
1481 else if (flags & FLAG_SHOWSIGN)
1483 else if (flags & FLAG_SPACE)
1486 if (arg > 0.0L && arg + arg == arg)
1488 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1490 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1494 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1499 # if NEED_PRINTF_LONG_DOUBLE
1502 if (dp->conversion == 'f' || dp->conversion == 'F')
1508 scale10_round_decimal_long_double (arg, precision);
1511 END_LONG_DOUBLE_ROUNDING ();
1514 ndigits = strlen (digits);
1516 if (ndigits > precision)
1520 *p++ = digits[ndigits];
1522 while (ndigits > precision);
1525 /* Here ndigits <= precision. */
1526 if ((flags & FLAG_ALT) || precision > 0)
1528 *p++ = decimal_point_char ();
1529 for (; precision > ndigits; precision--)
1534 *p++ = digits[ndigits];
1540 else if (dp->conversion == 'e' || dp->conversion == 'E')
1548 if ((flags & FLAG_ALT) || precision > 0)
1550 *p++ = decimal_point_char ();
1551 for (; precision > 0; precision--)
1562 exponent = floorlog10l (arg);
1567 scale10_round_decimal_long_double (arg,
1568 (int)precision - exponent);
1571 END_LONG_DOUBLE_ROUNDING ();
1574 ndigits = strlen (digits);
1576 if (ndigits == precision + 1)
1578 if (ndigits < precision
1579 || ndigits > precision + 2)
1580 /* The exponent was not guessed
1581 precisely enough. */
1584 /* None of two values of exponent is
1585 the right one. Prevent an endless
1589 if (ndigits == precision)
1596 /* Here ndigits = precision+1. */
1597 *p++ = digits[--ndigits];
1598 if ((flags & FLAG_ALT) || precision > 0)
1600 *p++ = decimal_point_char ();
1604 *p++ = digits[ndigits];
1611 *p++ = dp->conversion; /* 'e' or 'E' */
1612 # if WIDE_CHAR_VERSION
1614 static const wchar_t decimal_format[] =
1615 { '%', '+', '.', '2', 'd', '\0' };
1616 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1619 sprintf (p, "%+.2d", exponent);
1624 else if (dp->conversion == 'g' || dp->conversion == 'G')
1628 /* precision >= 1. */
1631 /* The exponent is 0, >= -4, < precision.
1632 Use fixed-point notation. */
1634 size_t ndigits = precision;
1635 /* Number of trailing zeroes that have to be
1638 (flags & FLAG_ALT ? 0 : precision - 1);
1642 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1644 *p++ = decimal_point_char ();
1645 while (ndigits > nzeroes)
1661 exponent = floorlog10l (arg);
1666 scale10_round_decimal_long_double (arg,
1667 (int)(precision - 1) - exponent);
1670 END_LONG_DOUBLE_ROUNDING ();
1673 ndigits = strlen (digits);
1675 if (ndigits == precision)
1677 if (ndigits < precision - 1
1678 || ndigits > precision + 1)
1679 /* The exponent was not guessed
1680 precisely enough. */
1683 /* None of two values of exponent is
1684 the right one. Prevent an endless
1688 if (ndigits < precision)
1694 /* Here ndigits = precision. */
1696 /* Determine the number of trailing zeroes
1697 that have to be dropped. */
1699 if ((flags & FLAG_ALT) == 0)
1700 while (nzeroes < ndigits
1701 && digits[nzeroes] == '0')
1704 /* The exponent is now determined. */
1706 && exponent < (long)precision)
1708 /* Fixed-point notation:
1709 max(exponent,0)+1 digits, then the
1710 decimal point, then the remaining
1711 digits without trailing zeroes. */
1714 size_t count = exponent + 1;
1715 /* Note: count <= precision = ndigits. */
1716 for (; count > 0; count--)
1717 *p++ = digits[--ndigits];
1718 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1720 *p++ = decimal_point_char ();
1721 while (ndigits > nzeroes)
1724 *p++ = digits[ndigits];
1730 size_t count = -exponent - 1;
1732 *p++ = decimal_point_char ();
1733 for (; count > 0; count--)
1735 while (ndigits > nzeroes)
1738 *p++ = digits[ndigits];
1744 /* Exponential notation. */
1745 *p++ = digits[--ndigits];
1746 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1748 *p++ = decimal_point_char ();
1749 while (ndigits > nzeroes)
1752 *p++ = digits[ndigits];
1755 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
1756 # if WIDE_CHAR_VERSION
1758 static const wchar_t decimal_format[] =
1759 { '%', '+', '.', '2', 'd', '\0' };
1760 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1763 sprintf (p, "%+.2d", exponent);
1775 /* arg is finite. */
1780 END_LONG_DOUBLE_ROUNDING ();
1783 # if NEED_PRINTF_INFINITE_DOUBLE
1787 # if NEED_PRINTF_INFINITE_DOUBLE
1789 /* Simpler than above: handle only NaN, Infinity, zero. */
1790 double arg = a.arg[dp->arg_index].a.a_double;
1794 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1796 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1800 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1807 if (signbit (arg)) /* arg < 0.0L or negative zero */
1815 else if (flags & FLAG_SHOWSIGN)
1817 else if (flags & FLAG_SPACE)
1820 if (arg > 0.0 && arg + arg == arg)
1822 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1824 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1828 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1838 if (dp->conversion == 'f' || dp->conversion == 'F')
1841 if ((flags & FLAG_ALT) || precision > 0)
1843 *p++ = decimal_point_char ();
1844 for (; precision > 0; precision--)
1848 else if (dp->conversion == 'e' || dp->conversion == 'E')
1851 if ((flags & FLAG_ALT) || precision > 0)
1853 *p++ = decimal_point_char ();
1854 for (; precision > 0; precision--)
1857 *p++ = dp->conversion; /* 'e' or 'E' */
1859 /* Produce the same number of exponent digits as
1860 the native printf implementation. */
1861 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
1867 else if (dp->conversion == 'g' || dp->conversion == 'G')
1870 if (flags & FLAG_ALT)
1873 (precision > 0 ? precision - 1 : 0);
1874 *p++ = decimal_point_char ();
1875 for (; ndigits > 0; --ndigits)
1886 /* The generated string now extends from tmp to p, with the
1887 zero padding insertion point being at pad_ptr. */
1888 if (has_width && p - tmp < width)
1890 size_t pad = width - (p - tmp);
1891 CHAR_T *end = p + pad;
1893 if (flags & FLAG_LEFT)
1895 /* Pad with spaces on the right. */
1896 for (; pad > 0; pad--)
1899 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
1901 /* Pad with zeroes. */
1906 for (; pad > 0; pad--)
1911 /* Pad with spaces on the left. */
1916 for (; pad > 0; pad--)
1924 size_t count = p - tmp;
1926 if (count >= tmp_length)
1927 /* tmp_length was incorrectly calculated - fix the
1931 /* Make room for the result. */
1932 if (count >= allocated - length)
1934 size_t n = xsum (length, count);
1936 ENSURE_ALLOCATION (n);
1939 /* Append the result. */
1940 memcpy (result + length, tmp, count * sizeof (CHAR_T));
1947 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
1948 else if (dp->conversion == 'a' || dp->conversion == 'A')
1950 arg_type type = a.arg[dp->arg_index].type;
1951 int flags = dp->flags;
1964 if (dp->width_start != dp->width_end)
1966 if (dp->width_arg_index != ARG_NONE)
1970 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1972 arg = a.arg[dp->width_arg_index].a.a_int;
1975 /* "A negative field width is taken as a '-' flag
1976 followed by a positive field width." */
1978 width = (unsigned int) (-arg);
1985 const CHAR_T *digitp = dp->width_start;
1988 width = xsum (xtimes (width, 10), *digitp++ - '0');
1989 while (digitp != dp->width_end);
1996 if (dp->precision_start != dp->precision_end)
1998 if (dp->precision_arg_index != ARG_NONE)
2002 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2004 arg = a.arg[dp->precision_arg_index].a.a_int;
2005 /* "A negative precision is taken as if the precision
2015 const CHAR_T *digitp = dp->precision_start + 1;
2018 while (digitp != dp->precision_end)
2019 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2024 /* Allocate a temporary buffer of sufficient size. */
2025 if (type == TYPE_LONGDOUBLE)
2027 (unsigned int) ((LDBL_DIG + 1)
2028 * 0.831 /* decimal -> hexadecimal */
2030 + 1; /* turn floor into ceil */
2033 (unsigned int) ((DBL_DIG + 1)
2034 * 0.831 /* decimal -> hexadecimal */
2036 + 1; /* turn floor into ceil */
2037 if (tmp_length < precision)
2038 tmp_length = precision;
2039 /* Account for sign, decimal point etc. */
2040 tmp_length = xsum (tmp_length, 12);
2042 if (tmp_length < width)
2045 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2047 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2051 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2053 if (size_overflow_p (tmp_memsize))
2054 /* Overflow, would lead to out of memory. */
2056 tmp = (CHAR_T *) malloc (tmp_memsize);
2058 /* Out of memory. */
2064 if (type == TYPE_LONGDOUBLE)
2066 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2070 if (dp->conversion == 'A')
2072 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2076 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2082 DECL_LONG_DOUBLE_ROUNDING
2084 BEGIN_LONG_DOUBLE_ROUNDING ();
2086 if (signbit (arg)) /* arg < 0.0L or negative zero */
2094 else if (flags & FLAG_SHOWSIGN)
2096 else if (flags & FLAG_SPACE)
2099 if (arg > 0.0L && arg + arg == arg)
2101 if (dp->conversion == 'A')
2103 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2107 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2113 long double mantissa;
2116 mantissa = printf_frexpl (arg, &exponent);
2124 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2126 /* Round the mantissa. */
2127 long double tail = mantissa;
2130 for (q = precision; ; q--)
2132 int digit = (int) tail;
2136 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2145 for (q = precision; q > 0; q--)
2151 *p++ = dp->conversion - 'A' + 'X';
2156 digit = (int) mantissa;
2159 if ((flags & FLAG_ALT)
2160 || mantissa > 0.0L || precision > 0)
2162 *p++ = decimal_point_char ();
2163 /* This loop terminates because we assume
2164 that FLT_RADIX is a power of 2. */
2165 while (mantissa > 0.0L)
2168 digit = (int) mantissa;
2173 : dp->conversion - 10);
2177 while (precision > 0)
2184 *p++ = dp->conversion - 'A' + 'P';
2185 # if WIDE_CHAR_VERSION
2187 static const wchar_t decimal_format[] =
2188 { '%', '+', 'd', '\0' };
2189 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2192 sprintf (p, "%+d", exponent);
2198 END_LONG_DOUBLE_ROUNDING ();
2203 double arg = a.arg[dp->arg_index].a.a_double;
2207 if (dp->conversion == 'A')
2209 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2213 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2220 if (signbit (arg)) /* arg < 0.0 or negative zero */
2228 else if (flags & FLAG_SHOWSIGN)
2230 else if (flags & FLAG_SPACE)
2233 if (arg > 0.0 && arg + arg == arg)
2235 if (dp->conversion == 'A')
2237 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2241 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2250 mantissa = printf_frexp (arg, &exponent);
2258 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2260 /* Round the mantissa. */
2261 double tail = mantissa;
2264 for (q = precision; ; q--)
2266 int digit = (int) tail;
2270 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2279 for (q = precision; q > 0; q--)
2285 *p++ = dp->conversion - 'A' + 'X';
2290 digit = (int) mantissa;
2293 if ((flags & FLAG_ALT)
2294 || mantissa > 0.0 || precision > 0)
2296 *p++ = decimal_point_char ();
2297 /* This loop terminates because we assume
2298 that FLT_RADIX is a power of 2. */
2299 while (mantissa > 0.0)
2302 digit = (int) mantissa;
2307 : dp->conversion - 10);
2311 while (precision > 0)
2318 *p++ = dp->conversion - 'A' + 'P';
2319 # if WIDE_CHAR_VERSION
2321 static const wchar_t decimal_format[] =
2322 { '%', '+', 'd', '\0' };
2323 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2326 sprintf (p, "%+d", exponent);
2333 /* The generated string now extends from tmp to p, with the
2334 zero padding insertion point being at pad_ptr. */
2335 if (has_width && p - tmp < width)
2337 size_t pad = width - (p - tmp);
2338 CHAR_T *end = p + pad;
2340 if (flags & FLAG_LEFT)
2342 /* Pad with spaces on the right. */
2343 for (; pad > 0; pad--)
2346 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2348 /* Pad with zeroes. */
2353 for (; pad > 0; pad--)
2358 /* Pad with spaces on the left. */
2363 for (; pad > 0; pad--)
2371 size_t count = p - tmp;
2373 if (count >= tmp_length)
2374 /* tmp_length was incorrectly calculated - fix the
2378 /* Make room for the result. */
2379 if (count >= allocated - length)
2381 size_t n = xsum (length, count);
2383 ENSURE_ALLOCATION (n);
2386 /* Append the result. */
2387 memcpy (result + length, tmp, count * sizeof (CHAR_T));
2396 arg_type type = a.arg[dp->arg_index].type;
2397 int flags = dp->flags;
2398 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2402 #if NEED_PRINTF_FLAG_ZERO
2405 # define pad_ourselves 0
2408 unsigned int prefix_count;
2416 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2419 if (dp->width_start != dp->width_end)
2421 if (dp->width_arg_index != ARG_NONE)
2425 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2427 arg = a.arg[dp->width_arg_index].a.a_int;
2430 /* "A negative field width is taken as a '-' flag
2431 followed by a positive field width." */
2433 width = (unsigned int) (-arg);
2440 const CHAR_T *digitp = dp->width_start;
2443 width = xsum (xtimes (width, 10), *digitp++ - '0');
2444 while (digitp != dp->width_end);
2451 /* Allocate a temporary buffer of sufficient size for calling
2457 if (dp->precision_start != dp->precision_end)
2459 if (dp->precision_arg_index != ARG_NONE)
2463 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2465 arg = a.arg[dp->precision_arg_index].a.a_int;
2466 precision = (arg < 0 ? 0 : arg);
2470 const CHAR_T *digitp = dp->precision_start + 1;
2473 while (digitp != dp->precision_end)
2474 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2478 switch (dp->conversion)
2481 case 'd': case 'i': case 'u':
2482 # if HAVE_LONG_LONG_INT
2483 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2485 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2486 * 0.30103 /* binary -> decimal */
2488 + 1; /* turn floor into ceil */
2491 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2493 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2494 * 0.30103 /* binary -> decimal */
2496 + 1; /* turn floor into ceil */
2499 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2500 * 0.30103 /* binary -> decimal */
2502 + 1; /* turn floor into ceil */
2503 if (tmp_length < precision)
2504 tmp_length = precision;
2505 /* Multiply by 2, as an estimate for FLAG_GROUP. */
2506 tmp_length = xsum (tmp_length, tmp_length);
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.333334 /* binary -> octal */
2518 + 1; /* turn floor into ceil */
2521 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2523 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2524 * 0.333334 /* binary -> octal */
2526 + 1; /* turn floor into ceil */
2529 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2530 * 0.333334 /* binary -> octal */
2532 + 1; /* turn floor into ceil */
2533 if (tmp_length < precision)
2534 tmp_length = precision;
2535 /* Add 1, to account for a leading sign. */
2536 tmp_length = xsum (tmp_length, 1);
2540 # if HAVE_LONG_LONG_INT
2541 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2543 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2544 * 0.25 /* binary -> hexadecimal */
2546 + 1; /* turn floor into ceil */
2549 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2551 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2552 * 0.25 /* binary -> hexadecimal */
2554 + 1; /* turn floor into ceil */
2557 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2558 * 0.25 /* binary -> hexadecimal */
2560 + 1; /* turn floor into ceil */
2561 if (tmp_length < precision)
2562 tmp_length = precision;
2563 /* Add 2, to account for a leading sign or alternate form. */
2564 tmp_length = xsum (tmp_length, 2);
2568 if (type == TYPE_LONGDOUBLE)
2570 (unsigned int) (LDBL_MAX_EXP
2571 * 0.30103 /* binary -> decimal */
2572 * 2 /* estimate for FLAG_GROUP */
2574 + 1 /* turn floor into ceil */
2575 + 10; /* sign, decimal point etc. */
2578 (unsigned int) (DBL_MAX_EXP
2579 * 0.30103 /* binary -> decimal */
2580 * 2 /* estimate for FLAG_GROUP */
2582 + 1 /* turn floor into ceil */
2583 + 10; /* sign, decimal point etc. */
2584 tmp_length = xsum (tmp_length, precision);
2587 case 'e': case 'E': case 'g': case 'G':
2589 12; /* sign, decimal point, exponent etc. */
2590 tmp_length = xsum (tmp_length, precision);
2594 if (type == TYPE_LONGDOUBLE)
2596 (unsigned int) (LDBL_DIG
2597 * 0.831 /* decimal -> hexadecimal */
2599 + 1; /* turn floor into ceil */
2602 (unsigned int) (DBL_DIG
2603 * 0.831 /* decimal -> hexadecimal */
2605 + 1; /* turn floor into ceil */
2606 if (tmp_length < precision)
2607 tmp_length = precision;
2608 /* Account for sign, decimal point etc. */
2609 tmp_length = xsum (tmp_length, 12);
2613 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
2614 if (type == TYPE_WIDE_CHAR)
2615 tmp_length = MB_CUR_MAX;
2623 if (type == TYPE_WIDE_STRING)
2626 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
2628 # if !WIDE_CHAR_VERSION
2629 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
2634 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
2639 (unsigned int) (sizeof (void *) * CHAR_BIT
2640 * 0.25 /* binary -> hexadecimal */
2642 + 1 /* turn floor into ceil */
2643 + 2; /* account for leading 0x */
2650 if (tmp_length < width)
2653 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2656 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2660 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2662 if (size_overflow_p (tmp_memsize))
2663 /* Overflow, would lead to out of memory. */
2665 tmp = (CHAR_T *) malloc (tmp_memsize);
2667 /* Out of memory. */
2672 /* Decide whether to perform the padding ourselves. */
2673 #if NEED_PRINTF_FLAG_ZERO
2674 switch (dp->conversion)
2676 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
2686 /* Construct the format string for calling snprintf or
2690 #if NEED_PRINTF_FLAG_GROUPING
2691 /* The underlying implementation doesn't support the ' flag.
2692 Produce no grouping characters in this case; this is
2693 acceptable because the grouping is locale dependent. */
2695 if (flags & FLAG_GROUP)
2698 if (flags & FLAG_LEFT)
2700 if (flags & FLAG_SHOWSIGN)
2702 if (flags & FLAG_SPACE)
2704 if (flags & FLAG_ALT)
2708 if (flags & FLAG_ZERO)
2710 if (dp->width_start != dp->width_end)
2712 size_t n = dp->width_end - dp->width_start;
2713 memcpy (fbp, dp->width_start, n * sizeof (CHAR_T));
2717 if (dp->precision_start != dp->precision_end)
2719 size_t n = dp->precision_end - dp->precision_start;
2720 memcpy (fbp, dp->precision_start, n * sizeof (CHAR_T));
2726 #if HAVE_LONG_LONG_INT
2727 case TYPE_LONGLONGINT:
2728 case TYPE_ULONGLONGINT:
2729 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2742 case TYPE_WIDE_CHAR:
2745 case TYPE_WIDE_STRING:
2749 case TYPE_LONGDOUBLE:
2755 #if NEED_PRINTF_DIRECTIVE_F
2756 if (dp->conversion == 'F')
2760 *fbp = dp->conversion;
2769 /* Construct the arguments for calling snprintf or sprintf. */
2771 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
2773 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2775 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
2777 if (dp->precision_arg_index != ARG_NONE)
2779 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2781 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
2785 /* Prepare checking whether snprintf returns the count
2787 ENSURE_ALLOCATION (xsum (length, 1));
2788 result[length] = '\0';
2797 maxlen = allocated - length;
2802 /* SNPRINTF can fail if maxlen > INT_MAX. */
2803 if (maxlen > INT_MAX)
2805 # define SNPRINTF_BUF(arg) \
2806 switch (prefix_count) \
2809 retcount = SNPRINTF (result + length, maxlen, buf, \
2813 retcount = SNPRINTF (result + length, maxlen, buf, \
2814 prefixes[0], arg, &count); \
2817 retcount = SNPRINTF (result + length, maxlen, buf, \
2818 prefixes[0], prefixes[1], arg, \
2825 # define SNPRINTF_BUF(arg) \
2826 switch (prefix_count) \
2829 count = sprintf (tmp, buf, arg); \
2832 count = sprintf (tmp, buf, prefixes[0], arg); \
2835 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
2847 int arg = a.arg[dp->arg_index].a.a_schar;
2853 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
2859 int arg = a.arg[dp->arg_index].a.a_short;
2865 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
2871 int arg = a.arg[dp->arg_index].a.a_int;
2877 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
2883 long int arg = a.arg[dp->arg_index].a.a_longint;
2889 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
2893 #if HAVE_LONG_LONG_INT
2894 case TYPE_LONGLONGINT:
2896 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
2900 case TYPE_ULONGLONGINT:
2902 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
2909 double arg = a.arg[dp->arg_index].a.a_double;
2913 case TYPE_LONGDOUBLE:
2915 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2921 int arg = a.arg[dp->arg_index].a.a_char;
2926 case TYPE_WIDE_CHAR:
2928 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
2935 const char *arg = a.arg[dp->arg_index].a.a_string;
2940 case TYPE_WIDE_STRING:
2942 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2949 void *arg = a.arg[dp->arg_index].a.a_pointer;
2958 /* Portability: Not all implementations of snprintf()
2959 are ISO C 99 compliant. Determine the number of
2960 bytes that snprintf() has produced or would have
2964 /* Verify that snprintf() has NUL-terminated its
2966 if (count < maxlen && result[length + count] != '\0')
2968 /* Portability hack. */
2969 if (retcount > count)
2974 /* snprintf() doesn't understand the '%n'
2978 /* Don't use the '%n' directive; instead, look
2979 at the snprintf() return value. */
2985 /* Look at the snprintf() return value. */
2988 /* HP-UX 10.20 snprintf() is doubly deficient:
2989 It doesn't understand the '%n' directive,
2990 *and* it returns -1 (rather than the length
2991 that would have been required) when the
2992 buffer is too small. */
2993 size_t bigger_need =
2994 xsum (xtimes (allocated, 2), 12);
2995 ENSURE_ALLOCATION (bigger_need);
3004 /* Attempt to handle failure. */
3007 if (!(result == resultbuf || result == NULL))
3009 if (buf_malloced != NULL)
3010 free (buf_malloced);
3016 /* Make room for the result. */
3017 if (count >= maxlen)
3019 /* Need at least count bytes. But allocate
3020 proportionally, to avoid looping eternally if
3021 snprintf() reports a too small count. */
3023 xmax (xsum (length, count), xtimes (allocated, 2));
3025 ENSURE_ALLOCATION (n);
3029 maxlen = allocated - length;
3033 /* Perform padding. */
3034 #if NEED_PRINTF_FLAG_ZERO
3035 if (pad_ourselves && has_width && count < width)
3038 /* Make room for the result. */
3039 if (width >= maxlen)
3041 /* Need at least width bytes. But allocate
3042 proportionally, to avoid looping eternally if
3043 snprintf() reports a too small count. */
3045 xmax (xsum (length + 1, width),
3046 xtimes (allocated, 2));
3049 ENSURE_ALLOCATION (n);
3051 maxlen = allocated - length; /* > width */
3053 /* Here width < maxlen. */
3057 CHAR_T * const rp = result + length;
3059 CHAR_T * const rp = tmp;
3061 CHAR_T *p = rp + count;
3062 size_t pad = width - count;
3063 CHAR_T *end = p + pad;
3064 CHAR_T *pad_ptr = (*rp == '-' ? rp + 1 : rp);
3065 /* No zero-padding of "inf" and "nan". */
3066 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
3067 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
3069 /* The generated string now extends from rp to p,
3070 with the zero padding insertion point being at
3073 if (flags & FLAG_LEFT)
3075 /* Pad with spaces on the right. */
3076 for (; pad > 0; pad--)
3079 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3081 /* Pad with zeroes. */
3086 for (; pad > 0; pad--)
3091 /* Pad with spaces on the left. */
3096 for (; pad > 0; pad--)
3100 count = width; /* = count + pad = end - rp */
3106 if (count >= tmp_length)
3107 /* tmp_length was incorrectly calculated - fix the
3112 /* Here still count < maxlen. */
3115 /* The snprintf() result did fit. */
3117 /* Append the sprintf() result. */
3118 memcpy (result + length, tmp, count * sizeof (CHAR_T));
3123 #if NEED_PRINTF_DIRECTIVE_F
3124 if (dp->conversion == 'F')
3126 /* Convert the %f result to upper case for %F. */
3127 CHAR_T *rp = result + length;
3129 for (rc = count; rc > 0; rc--, rp++)
3130 if (*rp >= 'a' && *rp <= 'z')
3131 *rp = *rp - 'a' + 'A';
3142 /* Add the final NUL. */
3143 ENSURE_ALLOCATION (xsum (length, 1));
3144 result[length] = '\0';
3146 if (result != resultbuf && length + 1 < allocated)
3148 /* Shrink the allocated memory if possible. */
3151 memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
3156 if (buf_malloced != NULL)
3157 free (buf_malloced);
3160 /* Note that we can produce a big string of a length > INT_MAX. POSIX
3161 says that snprintf() fails with errno = EOVERFLOW in this case, but
3162 that's only because snprintf() returns an 'int'. This function does
3163 not have this limitation. */
3167 if (!(result == resultbuf || result == NULL))
3169 if (buf_malloced != NULL)
3170 free (buf_malloced);
3176 if (!(result == resultbuf || result == NULL))
3178 if (buf_malloced != NULL)
3179 free (buf_malloced);