1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2007 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
19 This must come before <config.h> because <config.h> may include
20 <features.h>, and once <features.h> has been included, it's too late. */
22 # define _GNU_SOURCE 1
32 # include "vasnwprintf.h"
34 # include "vasnprintf.h"
37 #include <locale.h> /* localeconv() */
38 #include <stdio.h> /* snprintf(), sprintf() */
39 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
40 #include <string.h> /* memcpy(), strlen() */
41 #include <errno.h> /* errno */
42 #include <limits.h> /* CHAR_BIT */
43 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
45 # include <langinfo.h>
48 # include "wprintf-parse.h"
50 # include "printf-parse.h"
53 /* Checked size_t computations. */
56 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
62 #if NEED_PRINTF_INFINITE_DOUBLE && !defined IN_LIBINTL
67 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !defined IN_LIBINTL
69 # include "isnanl-nolibm.h"
73 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
76 # include "printf-frexp.h"
77 # include "isnanl-nolibm.h"
78 # include "printf-frexpl.h"
82 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
84 # define EOVERFLOW E2BIG
89 # define local_wcslen wcslen
91 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
92 a dependency towards this library, here is a local substitute.
93 Define this substitute only once, even if this file is included
94 twice in the same compilation unit. */
95 # ifndef local_wcslen_defined
96 # define local_wcslen_defined 1
98 local_wcslen (const wchar_t *s)
102 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
110 #if WIDE_CHAR_VERSION
111 # define VASNPRINTF vasnwprintf
112 # define CHAR_T wchar_t
113 # define DIRECTIVE wchar_t_directive
114 # define DIRECTIVES wchar_t_directives
115 # define PRINTF_PARSE wprintf_parse
116 # define USE_SNPRINTF 1
117 # if HAVE_DECL__SNWPRINTF
118 /* On Windows, the function swprintf() has a different signature than
119 on Unix; we use the _snwprintf() function instead. */
120 # define SNPRINTF _snwprintf
123 # define SNPRINTF swprintf
126 # define VASNPRINTF vasnprintf
128 # define DIRECTIVE char_directive
129 # define DIRECTIVES char_directives
130 # define PRINTF_PARSE printf_parse
131 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
132 But don't use it on BeOS, since BeOS snprintf produces no output if the
133 size argument is >= 0x3000000. */
134 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
135 # define USE_SNPRINTF 1
137 # define USE_SNPRINTF 0
139 # if HAVE_DECL__SNPRINTF
141 # define SNPRINTF _snprintf
144 # define SNPRINTF snprintf
145 /* Here we need to call the native snprintf, not rpl_snprintf. */
149 /* Here we need to call the native sprintf, not rpl_sprintf. */
152 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
153 /* Determine the decimal-point character according to the current locale. */
154 # ifndef decimal_point_char_defined
155 # define decimal_point_char_defined 1
157 decimal_point_char ()
160 /* Determine it in a multithread-safe way. We know nl_langinfo is
161 multithread-safe on glibc systems, but is not required to be multithread-
162 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
163 is rarely multithread-safe. */
164 # if HAVE_NL_LANGINFO && __GLIBC__
165 point = nl_langinfo (RADIXCHAR);
168 sprintf (pointbuf, "%#.0f", 1.0);
169 point = &pointbuf[1];
171 point = localeconv () -> decimal_point;
173 /* The decimal point is always a single byte: either '.' or ','. */
174 return (point[0] != '\0' ? point[0] : '.');
179 #if NEED_PRINTF_INFINITE_DOUBLE && !defined IN_LIBINTL
181 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
183 is_infinite_or_zero (double x)
185 return isnan (x) || x + x == x;
190 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !defined IN_LIBINTL
192 /* Equivalent to !isfinite(x), but does not require libm. */
194 is_infinitel (long double x)
196 return isnanl (x) || (x + x == x && x != 0.0L);
201 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
203 /* Converting 'long double' to decimal without rare rounding bugs requires
204 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
205 (and slower) algorithms. */
207 typedef unsigned int mp_limb_t;
208 # define GMP_LIMB_BITS 32
209 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
211 typedef unsigned long long mp_twolimb_t;
212 # define GMP_TWOLIMB_BITS 64
213 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
215 /* Representation of a bignum >= 0. */
219 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
222 /* Compute the product of two bignums >= 0.
223 Return the allocated memory in case of success, NULL in case of memory
224 allocation failure. */
226 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
233 if (src1.nlimbs <= src2.nlimbs)
247 /* Now 0 <= len1 <= len2. */
250 /* src1 or src2 is zero. */
252 dest->limbs = (mp_limb_t *) malloc (1);
256 /* Here 1 <= len1 <= len2. */
262 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
265 for (k = len2; k > 0; )
267 for (i = 0; i < len1; i++)
269 mp_limb_t digit1 = p1[i];
270 mp_twolimb_t carry = 0;
271 for (j = 0; j < len2; j++)
273 mp_limb_t digit2 = p2[j];
274 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
276 dp[i + j] = (mp_limb_t) carry;
277 carry = carry >> GMP_LIMB_BITS;
279 dp[i + len2] = (mp_limb_t) carry;
282 while (dlen > 0 && dp[dlen - 1] == 0)
290 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
291 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
293 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
295 Return the allocated memory in case of success, NULL in case of memory
296 allocation failure. */
298 divide (mpn_t a, mpn_t b, mpn_t *q)
301 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
302 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
303 If m<n, then q:=0 and r:=a.
304 If m>=n=1, perform a single-precision division:
307 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
308 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
309 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
310 Normalise [q[m-1],...,q[0]], yields q.
311 If m>=n>1, perform a multiple-precision division:
312 We have a/b < beta^(m-n+1).
313 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
314 Shift a and b left by s bits, copying them. r:=a.
315 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
316 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
318 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
319 In case of overflow (q* >= beta) set q* := beta-1.
320 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
321 and c3 := b[n-2] * q*.
322 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
323 occurred. Furthermore 0 <= c3 < beta^2.
324 If there was overflow and
325 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
326 the next test can be skipped.}
327 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
328 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
330 Put r := r - b * q* * beta^j. In detail:
331 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
332 hence: u:=0, for i:=0 to n-1 do
334 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
335 u:=u div beta (+ 1, if carry in subtraction)
337 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
339 the carry u does not overflow.}
340 If a negative carry occurs, put q* := q* - 1
341 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
343 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
344 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
346 The room for q[j] can be allocated at the memory location of r[n+j].
347 Finally, round-to-even:
348 Shift r left by 1 bit.
349 If r > b or if r = b and q[0] is odd, q := q+1.
351 const mp_limb_t *a_ptr = a.limbs;
352 size_t a_len = a.nlimbs;
353 const mp_limb_t *b_ptr = b.limbs;
354 size_t b_len = b.nlimbs;
356 mp_limb_t *tmp_roomptr = NULL;
362 /* Allocate room for a_len+2 digits.
363 (Need a_len+1 digits for the real division and 1 more digit for the
364 final rounding of q.) */
365 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
370 while (a_len > 0 && a_ptr[a_len - 1] == 0)
377 /* Division by zero. */
379 if (b_ptr[b_len - 1] == 0)
385 /* Here m = a_len >= 0 and n = b_len > 0. */
389 /* m<n: trivial case. q=0, r := copy of a. */
392 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
393 q_ptr = roomptr + a_len;
398 /* n=1: single precision division.
399 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
403 mp_limb_t den = b_ptr[0];
404 mp_limb_t remainder = 0;
405 const mp_limb_t *sourceptr = a_ptr + a_len;
406 mp_limb_t *destptr = q_ptr + a_len;
408 for (count = a_len; count > 0; count--)
411 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
412 *--destptr = num / den;
413 remainder = num % den;
415 /* Normalise and store r. */
418 r_ptr[0] = remainder;
425 if (q_ptr[q_len - 1] == 0)
431 /* n>1: multiple precision division.
432 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
433 beta^(m-n-1) <= a/b < beta^(m-n+1). */
437 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
465 /* 0 <= s < GMP_LIMB_BITS.
466 Copy b, shifting it left by s bits. */
469 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
470 if (tmp_roomptr == NULL)
476 const mp_limb_t *sourceptr = b_ptr;
477 mp_limb_t *destptr = tmp_roomptr;
478 mp_twolimb_t accu = 0;
480 for (count = b_len; count > 0; count--)
482 accu += (mp_twolimb_t) *sourceptr++ << s;
483 *destptr++ = (mp_limb_t) accu;
484 accu = accu >> GMP_LIMB_BITS;
486 /* accu must be zero, since that was how s was determined. */
492 /* Copy a, shifting it left by s bits, yields r.
494 At the beginning: r = roomptr[0..a_len],
495 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
499 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
504 const mp_limb_t *sourceptr = a_ptr;
505 mp_limb_t *destptr = r_ptr;
506 mp_twolimb_t accu = 0;
508 for (count = a_len; count > 0; count--)
510 accu += (mp_twolimb_t) *sourceptr++ << s;
511 *destptr++ = (mp_limb_t) accu;
512 accu = accu >> GMP_LIMB_BITS;
514 *destptr++ = (mp_limb_t) accu;
516 q_ptr = roomptr + b_len;
517 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
519 size_t j = a_len - b_len; /* m-n */
520 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
521 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
522 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
523 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
524 /* Division loop, traversed m-n+1 times.
525 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
530 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
532 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
534 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
535 | r_ptr[j + b_len - 1];
536 q_star = num / b_msd;
541 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
542 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
543 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
544 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
545 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
547 If yes, jump directly to the subtraction loop.
548 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
549 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
550 if (r_ptr[j + b_len] > b_msd
551 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
552 /* r[j+n] >= b[n-1]+1 or
553 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
558 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
560 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
561 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
562 mp_twolimb_t c3 = /* b[n-2] * q* */
563 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
564 /* While c2 < c3, increase c2 and decrease c3.
565 Consider c3-c2. While it is > 0, decrease it by
566 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
567 this can happen only twice. */
570 q_star = q_star - 1; /* q* := q* - 1 */
571 if (c3 - c2 > b_msdd)
572 q_star = q_star - 1; /* q* := q* - 1 */
578 /* Subtract r := r - b * q* * beta^j. */
581 const mp_limb_t *sourceptr = b_ptr;
582 mp_limb_t *destptr = r_ptr + j;
583 mp_twolimb_t carry = 0;
585 for (count = b_len; count > 0; count--)
587 /* Here 0 <= carry <= q*. */
590 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
591 + (mp_limb_t) ~(*destptr);
592 /* Here 0 <= carry <= beta*q* + beta-1. */
593 *destptr++ = ~(mp_limb_t) carry;
594 carry = carry >> GMP_LIMB_BITS; /* <= q* */
596 cr = (mp_limb_t) carry;
598 /* Subtract cr from r_ptr[j + b_len], then forget about
600 if (cr > r_ptr[j + b_len])
602 /* Subtraction gave a carry. */
603 q_star = q_star - 1; /* q* := q* - 1 */
606 const mp_limb_t *sourceptr = b_ptr;
607 mp_limb_t *destptr = r_ptr + j;
610 for (count = b_len; count > 0; count--)
612 mp_limb_t source1 = *sourceptr++;
613 mp_limb_t source2 = *destptr;
614 *destptr++ = source1 + source2 + carry;
617 ? source1 >= (mp_limb_t) ~source2
618 : source1 > (mp_limb_t) ~source2);
621 /* Forget about the carry and about r[j+n]. */
624 /* q* is determined. Store it as q[j]. */
633 if (q_ptr[q_len - 1] == 0)
635 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
636 b is shifted left by s bits. */
637 /* Shift r right by s bits. */
640 mp_limb_t ptr = r_ptr + r_len;
641 mp_twolimb_t accu = 0;
643 for (count = r_len; count > 0; count--)
645 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
646 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
647 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
652 while (r_len > 0 && r_ptr[r_len - 1] == 0)
655 /* Compare r << 1 with b. */
663 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
664 | (i < r_len ? r_ptr[i] << 1 : 0);
665 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
675 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
680 for (i = 0; i < q_len; i++)
681 if (++(q_ptr[i]) != 0)
686 if (tmp_roomptr != NULL)
693 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
695 Destroys the contents of a.
696 Return the allocated memory - containing the decimal digits in low-to-high
697 order, terminated with a NUL character - in case of success, NULL in case
698 of memory allocation failure. */
700 convert_to_decimal (mpn_t a, size_t extra_zeroes)
702 mp_limb_t *a_ptr = a.limbs;
703 size_t a_len = a.nlimbs;
704 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
705 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
706 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
710 for (; extra_zeroes > 0; extra_zeroes--)
714 /* Divide a by 10^9, in-place. */
715 mp_limb_t remainder = 0;
716 mp_limb_t *ptr = a_ptr + a_len;
718 for (count = a_len; count > 0; count--)
721 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
722 *ptr = num / 1000000000;
723 remainder = num % 1000000000;
725 /* Store the remainder as 9 decimal digits. */
726 for (count = 9; count > 0; count--)
728 *d_ptr++ = '0' + (remainder % 10);
729 remainder = remainder / 10;
732 if (a_ptr[a_len - 1] == 0)
735 /* Remove leading zeroes. */
736 while (d_ptr > c_ptr && d_ptr[-1] == '0')
738 /* But keep at least one zero. */
741 /* Terminate the string. */
747 /* Assuming x is finite and >= 0:
748 write x as x = 2^e * m, where m is a bignum.
749 Return the allocated memory in case of success, NULL in case of memory
750 allocation failure. */
752 decode_long_double (long double x, int *ep, mpn_t *mp)
759 /* Allocate memory for result. */
760 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
761 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
764 /* Split into exponential part and mantissa. */
765 y = frexpl (x, &exp);
766 if (!(y >= 0.0L && y < 1.0L))
768 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
769 latter is an integer. */
770 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
771 I'm not sure whether it's safe to cast a 'long double' value between
772 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
773 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
775 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
776 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
779 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
782 if (!(y >= 0.0L && y < 1.0L))
784 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
787 if (!(y >= 0.0L && y < 1.0L))
789 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
794 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
797 if (!(y >= 0.0L && y < 1.0L))
799 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
803 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
806 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
809 if (!(y >= 0.0L && y < 1.0L))
811 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
814 if (!(y >= 0.0L && y < 1.0L))
816 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
821 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
824 *ep = exp - LDBL_MANT_BIT;
828 /* Assuming x is finite and >= 0, and n is an integer:
829 Returns the decimal representation of round (x * 10^n).
830 Return the allocated memory - containing the decimal digits in low-to-high
831 order, terminated with a NUL character - in case of success, NULL in case
832 of memory allocation failure. */
834 scale10_round_decimal_long_double (long double x, int n)
838 void *memory = decode_long_double (x, &e, &m);
845 unsigned int s_limbs;
854 /* x = 2^e * m, hence
855 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
856 = round (2^s * 5^n * m). */
859 /* Factor out a common power of 10 if possible. */
862 extra_zeroes = (s < n ? s : n);
866 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
867 Before converting to decimal, we need to compute
868 z = round (2^s * 5^n * m). */
869 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
870 sign. 2.322 is slightly larger than log(5)/log(2). */
871 abs_n = (n >= 0 ? n : -n);
872 abs_s = (s >= 0 ? s : -s);
873 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
874 + abs_s / GMP_LIMB_BITS + 1)
875 * sizeof (mp_limb_t));
876 if (pow5_ptr == NULL)
881 /* Initialize with 1. */
884 /* Multiply with 5^|n|. */
887 static mp_limb_t const small_pow5[13 + 1] =
889 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
890 48828125, 244140625, 1220703125
893 for (n13 = 0; n13 <= abs_n; n13 += 13)
895 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
897 mp_twolimb_t carry = 0;
898 for (j = 0; j < pow5_len; j++)
900 mp_limb_t digit2 = pow5_ptr[j];
901 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
902 pow5_ptr[j] = (mp_limb_t) carry;
903 carry = carry >> GMP_LIMB_BITS;
906 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
909 s_limbs = abs_s / GMP_LIMB_BITS;
910 s_bits = abs_s % GMP_LIMB_BITS;
911 if (n >= 0 ? s >= 0 : s <= 0)
913 /* Multiply with 2^|s|. */
916 mp_limb_t *ptr = pow5_ptr;
917 mp_twolimb_t accu = 0;
919 for (count = pow5_len; count > 0; count--)
921 accu += (mp_twolimb_t) *ptr << s_bits;
922 *ptr++ = (mp_limb_t) accu;
923 accu = accu >> GMP_LIMB_BITS;
927 *ptr = (mp_limb_t) accu;
934 for (count = pow5_len; count > 0;)
937 pow5_ptr[s_limbs + count] = pow5_ptr[count];
939 for (count = s_limbs; count > 0;)
946 pow5.limbs = pow5_ptr;
947 pow5.nlimbs = pow5_len;
950 /* Multiply m with pow5. No division needed. */
951 z_memory = multiply (m, pow5, &z);
955 /* Divide m by pow5 and round. */
956 z_memory = divide (m, pow5, &z);
961 pow5.limbs = pow5_ptr;
962 pow5.nlimbs = pow5_len;
966 Multiply m with pow5, then divide by 2^|s|. */
970 tmp_memory = multiply (m, pow5, &numerator);
971 if (tmp_memory == NULL)
977 /* Construct 2^|s|. */
979 mp_limb_t *ptr = pow5_ptr + pow5_len;
981 for (i = 0; i < s_limbs; i++)
983 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
984 denominator.limbs = ptr;
985 denominator.nlimbs = s_limbs + 1;
987 z_memory = divide (numerator, denominator, &z);
993 Multiply m with 2^s, then divide by pow5. */
996 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
997 * sizeof (mp_limb_t));
1005 mp_limb_t *destptr = num_ptr;
1008 for (i = 0; i < s_limbs; i++)
1013 const mp_limb_t *sourceptr = m.limbs;
1014 mp_twolimb_t accu = 0;
1016 for (count = m.nlimbs; count > 0; count--)
1018 accu += (mp_twolimb_t) *sourceptr++ << s;
1019 *destptr++ = (mp_limb_t) accu;
1020 accu = accu >> GMP_LIMB_BITS;
1023 *destptr++ = (mp_limb_t) accu;
1027 const mp_limb_t *sourceptr = m.limbs;
1029 for (count = m.nlimbs; count > 0; count--)
1030 *destptr++ = *sourceptr++;
1032 numerator.limbs = num_ptr;
1033 numerator.nlimbs = destptr - num_ptr;
1035 z_memory = divide (numerator, pow5, &z);
1042 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1044 if (z_memory == NULL)
1046 digits = convert_to_decimal (z, extra_zeroes);
1051 /* Assuming x is finite and > 0:
1052 Return an approximation for n with 10^n <= x < 10^(n+1).
1053 The approximation is usually the right n, but may be off by 1 sometimes. */
1055 floorlog10l (long double x)
1062 /* Split into exponential part and mantissa. */
1063 y = frexpl (x, &exp);
1064 if (!(y >= 0.0L && y < 1.0L))
1070 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1072 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1073 exp -= GMP_LIMB_BITS;
1075 if (y < (1.0L / (1 << 16)))
1077 y *= 1.0L * (1 << 16);
1080 if (y < (1.0L / (1 << 8)))
1082 y *= 1.0L * (1 << 8);
1085 if (y < (1.0L / (1 << 4)))
1087 y *= 1.0L * (1 << 4);
1090 if (y < (1.0L / (1 << 2)))
1092 y *= 1.0L * (1 << 2);
1095 if (y < (1.0L / (1 << 1)))
1097 y *= 1.0L * (1 << 1);
1101 if (!(y >= 0.5L && y < 1.0L))
1103 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1106 if (z < 0.70710678118654752444)
1108 z *= 1.4142135623730950488;
1111 if (z < 0.8408964152537145431)
1113 z *= 1.1892071150027210667;
1116 if (z < 0.91700404320467123175)
1118 z *= 1.0905077326652576592;
1121 if (z < 0.9576032806985736469)
1123 z *= 1.0442737824274138403;
1126 /* Now 0.95 <= z <= 1.01. */
1128 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1129 Four terms are enough to get an approximation with error < 10^-7. */
1130 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1131 /* Finally multiply with log(2)/log(10), yields an approximation for
1133 l *= 0.30102999566398119523;
1134 /* Round down to the next integer. */
1135 return (int) l + (l < 0 ? -1 : 0);
1141 VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list args)
1146 if (PRINTF_PARSE (format, &d, &a) < 0)
1157 if (printf_fetchargs (args, &a) < 0)
1165 size_t buf_neededlength;
1167 CHAR_T *buf_malloced;
1171 /* Output string accumulator. */
1176 /* Allocate a small buffer that will hold a directive passed to
1177 sprintf or snprintf. */
1179 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1181 if (buf_neededlength < 4000 / sizeof (CHAR_T))
1183 buf = (CHAR_T *) alloca (buf_neededlength * sizeof (CHAR_T));
1184 buf_malloced = NULL;
1189 size_t buf_memsize = xtimes (buf_neededlength, sizeof (CHAR_T));
1190 if (size_overflow_p (buf_memsize))
1191 goto out_of_memory_1;
1192 buf = (CHAR_T *) malloc (buf_memsize);
1194 goto out_of_memory_1;
1198 if (resultbuf != NULL)
1201 allocated = *lengthp;
1210 result is either == resultbuf or == NULL or malloc-allocated.
1211 If length > 0, then result != NULL. */
1213 /* Ensures that allocated >= needed. Aborts through a jump to
1214 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1215 #define ENSURE_ALLOCATION(needed) \
1216 if ((needed) > allocated) \
1218 size_t memory_size; \
1221 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1222 if ((needed) > allocated) \
1223 allocated = (needed); \
1224 memory_size = xtimes (allocated, sizeof (CHAR_T)); \
1225 if (size_overflow_p (memory_size)) \
1226 goto out_of_memory; \
1227 if (result == resultbuf || result == NULL) \
1228 memory = (CHAR_T *) malloc (memory_size); \
1230 memory = (CHAR_T *) realloc (result, memory_size); \
1231 if (memory == NULL) \
1232 goto out_of_memory; \
1233 if (result == resultbuf && length > 0) \
1234 memcpy (memory, result, length * sizeof (CHAR_T)); \
1238 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1240 if (cp != dp->dir_start)
1242 size_t n = dp->dir_start - cp;
1243 size_t augmented_length = xsum (length, n);
1245 ENSURE_ALLOCATION (augmented_length);
1246 memcpy (result + length, cp, n * sizeof (CHAR_T));
1247 length = augmented_length;
1252 /* Execute a single directive. */
1253 if (dp->conversion == '%')
1255 size_t augmented_length;
1257 if (!(dp->arg_index == ARG_NONE))
1259 augmented_length = xsum (length, 1);
1260 ENSURE_ALLOCATION (augmented_length);
1261 result[length] = '%';
1262 length = augmented_length;
1266 if (!(dp->arg_index != ARG_NONE))
1269 if (dp->conversion == 'n')
1271 switch (a.arg[dp->arg_index].type)
1273 case TYPE_COUNT_SCHAR_POINTER:
1274 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1276 case TYPE_COUNT_SHORT_POINTER:
1277 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1279 case TYPE_COUNT_INT_POINTER:
1280 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1282 case TYPE_COUNT_LONGINT_POINTER:
1283 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1285 #if HAVE_LONG_LONG_INT
1286 case TYPE_COUNT_LONGLONGINT_POINTER:
1287 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1294 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
1295 else if ((dp->conversion == 'f' || dp->conversion == 'F'
1296 || dp->conversion == 'e' || dp->conversion == 'E'
1297 || dp->conversion == 'g' || dp->conversion == 'G')
1299 # if NEED_PRINTF_INFINITE_DOUBLE
1300 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
1301 /* The systems (mingw) which produce wrong output
1302 for Inf, -Inf, and NaN also do so for -0.0.
1303 Therefore we treat this case here as well. */
1304 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
1306 # if NEED_PRINTF_LONG_DOUBLE
1307 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
1308 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
1309 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
1310 /* Some systems produce wrong output for Inf,
1312 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
1316 # if NEED_PRINTF_INFINITE_DOUBLE && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
1317 arg_type type = a.arg[dp->arg_index].type;
1319 int flags = dp->flags;
1332 if (dp->width_start != dp->width_end)
1334 if (dp->width_arg_index != ARG_NONE)
1338 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1340 arg = a.arg[dp->width_arg_index].a.a_int;
1343 /* "A negative field width is taken as a '-' flag
1344 followed by a positive field width." */
1346 width = (unsigned int) (-arg);
1353 const CHAR_T *digitp = dp->width_start;
1356 width = xsum (xtimes (width, 10), *digitp++ - '0');
1357 while (digitp != dp->width_end);
1364 if (dp->precision_start != dp->precision_end)
1366 if (dp->precision_arg_index != ARG_NONE)
1370 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1372 arg = a.arg[dp->precision_arg_index].a.a_int;
1373 /* "A negative precision is taken as if the precision
1383 const CHAR_T *digitp = dp->precision_start + 1;
1386 while (digitp != dp->precision_end)
1387 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1392 /* POSIX specifies the default precision to be 6 for %f, %F,
1393 %e, %E, but not for %g, %G. Implementations appear to use
1394 the same default precision also for %g, %G. */
1398 /* Allocate a temporary buffer of sufficient size. */
1399 # if NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
1400 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
1401 # elif NEED_PRINTF_LONG_DOUBLE
1402 tmp_length = LDBL_DIG + 1;
1406 if (tmp_length < precision)
1407 tmp_length = precision;
1408 # if NEED_PRINTF_LONG_DOUBLE
1409 # if NEED_PRINTF_INFINITE_DOUBLE
1410 if (type == TYPE_LONGDOUBLE)
1412 if (dp->conversion == 'f' || dp->conversion == 'F')
1414 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1415 if (!(isnanl (arg) || arg + arg == arg))
1417 /* arg is finite and nonzero. */
1418 int exponent = floorlog10l (arg < 0 ? -arg : arg);
1419 if (exponent >= 0 && tmp_length < exponent + precision)
1420 tmp_length = exponent + precision;
1424 /* Account for sign, decimal point etc. */
1425 tmp_length = xsum (tmp_length, 12);
1427 if (tmp_length < width)
1430 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1432 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1436 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1438 if (size_overflow_p (tmp_memsize))
1439 /* Overflow, would lead to out of memory. */
1441 tmp = (CHAR_T *) malloc (tmp_memsize);
1443 /* Out of memory. */
1450 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
1451 # if NEED_PRINTF_INFINITE_DOUBLE
1452 if (type == TYPE_LONGDOUBLE)
1455 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1459 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1461 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1465 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1471 DECL_LONG_DOUBLE_ROUNDING
1473 BEGIN_LONG_DOUBLE_ROUNDING ();
1475 if (signbit (arg)) /* arg < 0.0L or negative zero */
1483 else if (flags & FLAG_SHOWSIGN)
1485 else if (flags & FLAG_SPACE)
1488 if (arg > 0.0L && arg + arg == arg)
1490 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1492 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1496 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1501 # if NEED_PRINTF_LONG_DOUBLE
1504 if (dp->conversion == 'f' || dp->conversion == 'F')
1510 scale10_round_decimal_long_double (arg, precision);
1513 END_LONG_DOUBLE_ROUNDING ();
1516 ndigits = strlen (digits);
1518 if (ndigits > precision)
1522 *p++ = digits[ndigits];
1524 while (ndigits > precision);
1527 /* Here ndigits <= precision. */
1528 if ((flags & FLAG_ALT) || precision > 0)
1530 *p++ = decimal_point_char ();
1531 for (; precision > ndigits; precision--)
1536 *p++ = digits[ndigits];
1542 else if (dp->conversion == 'e' || dp->conversion == 'E')
1550 if ((flags & FLAG_ALT) || precision > 0)
1552 *p++ = decimal_point_char ();
1553 for (; precision > 0; precision--)
1564 exponent = floorlog10l (arg);
1569 scale10_round_decimal_long_double (arg,
1570 (int)precision - exponent);
1573 END_LONG_DOUBLE_ROUNDING ();
1576 ndigits = strlen (digits);
1578 if (ndigits == precision + 1)
1580 if (ndigits < precision
1581 || ndigits > precision + 2)
1582 /* The exponent was not guessed
1583 precisely enough. */
1586 /* None of two values of exponent is
1587 the right one. Prevent an endless
1591 if (ndigits == precision)
1598 /* Here ndigits = precision+1. */
1599 *p++ = digits[--ndigits];
1600 if ((flags & FLAG_ALT) || precision > 0)
1602 *p++ = decimal_point_char ();
1606 *p++ = digits[ndigits];
1613 *p++ = dp->conversion; /* 'e' or 'E' */
1614 # if WIDE_CHAR_VERSION
1616 static const wchar_t decimal_format[] =
1617 { '%', '+', '.', '2', 'd', '\0' };
1618 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1621 sprintf (p, "%+.2d", exponent);
1626 else if (dp->conversion == 'g' || dp->conversion == 'G')
1630 /* precision >= 1. */
1633 /* The exponent is 0, >= -4, < precision.
1634 Use fixed-point notation. */
1636 size_t ndigits = precision;
1637 /* Number of trailing zeroes that have to be
1640 (flags & FLAG_ALT ? 0 : precision - 1);
1644 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1646 *p++ = decimal_point_char ();
1647 while (ndigits > nzeroes)
1663 exponent = floorlog10l (arg);
1668 scale10_round_decimal_long_double (arg,
1669 (int)(precision - 1) - exponent);
1672 END_LONG_DOUBLE_ROUNDING ();
1675 ndigits = strlen (digits);
1677 if (ndigits == precision)
1679 if (ndigits < precision - 1
1680 || ndigits > precision + 1)
1681 /* The exponent was not guessed
1682 precisely enough. */
1685 /* None of two values of exponent is
1686 the right one. Prevent an endless
1690 if (ndigits < precision)
1696 /* Here ndigits = precision. */
1698 /* Determine the number of trailing zeroes
1699 that have to be dropped. */
1701 if ((flags & FLAG_ALT) == 0)
1702 while (nzeroes < ndigits
1703 && digits[nzeroes] == '0')
1706 /* The exponent is now determined. */
1708 && exponent < (long)precision)
1710 /* Fixed-point notation:
1711 max(exponent,0)+1 digits, then the
1712 decimal point, then the remaining
1713 digits without trailing zeroes. */
1716 size_t count = exponent + 1;
1717 /* Note: count <= precision = ndigits. */
1718 for (; count > 0; count--)
1719 *p++ = digits[--ndigits];
1720 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1722 *p++ = decimal_point_char ();
1723 while (ndigits > nzeroes)
1726 *p++ = digits[ndigits];
1732 size_t count = -exponent - 1;
1734 *p++ = decimal_point_char ();
1735 for (; count > 0; count--)
1737 while (ndigits > nzeroes)
1740 *p++ = digits[ndigits];
1746 /* Exponential notation. */
1747 *p++ = digits[--ndigits];
1748 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1750 *p++ = decimal_point_char ();
1751 while (ndigits > nzeroes)
1754 *p++ = digits[ndigits];
1757 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
1758 # if WIDE_CHAR_VERSION
1760 static const wchar_t decimal_format[] =
1761 { '%', '+', '.', '2', 'd', '\0' };
1762 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1765 sprintf (p, "%+.2d", exponent);
1777 /* arg is finite. */
1782 END_LONG_DOUBLE_ROUNDING ();
1785 # if NEED_PRINTF_INFINITE_DOUBLE
1789 # if NEED_PRINTF_INFINITE_DOUBLE
1791 /* Simpler than above: handle only NaN, Infinity, zero. */
1792 double arg = a.arg[dp->arg_index].a.a_double;
1796 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1798 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1802 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1809 if (signbit (arg)) /* arg < 0.0L or negative zero */
1817 else if (flags & FLAG_SHOWSIGN)
1819 else if (flags & FLAG_SPACE)
1822 if (arg > 0.0 && arg + arg == arg)
1824 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1826 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1830 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1840 if (dp->conversion == 'f' || dp->conversion == 'F')
1843 if ((flags & FLAG_ALT) || precision > 0)
1845 *p++ = decimal_point_char ();
1846 for (; precision > 0; precision--)
1850 else if (dp->conversion == 'e' || dp->conversion == 'E')
1853 if ((flags & FLAG_ALT) || precision > 0)
1855 *p++ = decimal_point_char ();
1856 for (; precision > 0; precision--)
1859 *p++ = dp->conversion; /* 'e' or 'E' */
1861 /* Produce the same number of exponent digits as
1862 the native printf implementation. */
1863 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
1869 else if (dp->conversion == 'g' || dp->conversion == 'G')
1872 if (flags & FLAG_ALT)
1875 (precision > 0 ? precision - 1 : 0);
1876 *p++ = decimal_point_char ();
1877 for (; ndigits > 0; --ndigits)
1888 /* The generated string now extends from tmp to p, with the
1889 zero padding insertion point being at pad_ptr. */
1890 if (has_width && p - tmp < width)
1892 size_t pad = width - (p - tmp);
1893 CHAR_T *end = p + pad;
1895 if (flags & FLAG_LEFT)
1897 /* Pad with spaces on the right. */
1898 for (; pad > 0; pad--)
1901 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
1903 /* Pad with zeroes. */
1908 for (; pad > 0; pad--)
1913 /* Pad with spaces on the left. */
1918 for (; pad > 0; pad--)
1926 size_t count = p - tmp;
1928 if (count >= tmp_length)
1929 /* tmp_length was incorrectly calculated - fix the
1933 /* Make room for the result. */
1934 if (count >= allocated - length)
1936 size_t n = xsum (length, count);
1938 ENSURE_ALLOCATION (n);
1941 /* Append the result. */
1942 memcpy (result + length, tmp, count * sizeof (CHAR_T));
1949 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
1950 else if (dp->conversion == 'a' || dp->conversion == 'A')
1952 arg_type type = a.arg[dp->arg_index].type;
1953 int flags = dp->flags;
1966 if (dp->width_start != dp->width_end)
1968 if (dp->width_arg_index != ARG_NONE)
1972 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1974 arg = a.arg[dp->width_arg_index].a.a_int;
1977 /* "A negative field width is taken as a '-' flag
1978 followed by a positive field width." */
1980 width = (unsigned int) (-arg);
1987 const CHAR_T *digitp = dp->width_start;
1990 width = xsum (xtimes (width, 10), *digitp++ - '0');
1991 while (digitp != dp->width_end);
1998 if (dp->precision_start != dp->precision_end)
2000 if (dp->precision_arg_index != ARG_NONE)
2004 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2006 arg = a.arg[dp->precision_arg_index].a.a_int;
2007 /* "A negative precision is taken as if the precision
2017 const CHAR_T *digitp = dp->precision_start + 1;
2020 while (digitp != dp->precision_end)
2021 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2026 /* Allocate a temporary buffer of sufficient size. */
2027 if (type == TYPE_LONGDOUBLE)
2029 (unsigned int) ((LDBL_DIG + 1)
2030 * 0.831 /* decimal -> hexadecimal */
2032 + 1; /* turn floor into ceil */
2035 (unsigned int) ((DBL_DIG + 1)
2036 * 0.831 /* decimal -> hexadecimal */
2038 + 1; /* turn floor into ceil */
2039 if (tmp_length < precision)
2040 tmp_length = precision;
2041 /* Account for sign, decimal point etc. */
2042 tmp_length = xsum (tmp_length, 12);
2044 if (tmp_length < width)
2047 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2049 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2053 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2055 if (size_overflow_p (tmp_memsize))
2056 /* Overflow, would lead to out of memory. */
2058 tmp = (CHAR_T *) malloc (tmp_memsize);
2060 /* Out of memory. */
2066 if (type == TYPE_LONGDOUBLE)
2068 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2072 if (dp->conversion == 'A')
2074 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2078 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2084 DECL_LONG_DOUBLE_ROUNDING
2086 BEGIN_LONG_DOUBLE_ROUNDING ();
2088 if (signbit (arg)) /* arg < 0.0L or negative zero */
2096 else if (flags & FLAG_SHOWSIGN)
2098 else if (flags & FLAG_SPACE)
2101 if (arg > 0.0L && arg + arg == arg)
2103 if (dp->conversion == 'A')
2105 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2109 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2115 long double mantissa;
2118 mantissa = printf_frexpl (arg, &exponent);
2126 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2128 /* Round the mantissa. */
2129 long double tail = mantissa;
2132 for (q = precision; ; q--)
2134 int digit = (int) tail;
2138 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2147 for (q = precision; q > 0; q--)
2153 *p++ = dp->conversion - 'A' + 'X';
2158 digit = (int) mantissa;
2161 if ((flags & FLAG_ALT)
2162 || mantissa > 0.0L || precision > 0)
2164 *p++ = decimal_point_char ();
2165 /* This loop terminates because we assume
2166 that FLT_RADIX is a power of 2. */
2167 while (mantissa > 0.0L)
2170 digit = (int) mantissa;
2175 : dp->conversion - 10);
2179 while (precision > 0)
2186 *p++ = dp->conversion - 'A' + 'P';
2187 # if WIDE_CHAR_VERSION
2189 static const wchar_t decimal_format[] =
2190 { '%', '+', 'd', '\0' };
2191 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2194 sprintf (p, "%+d", exponent);
2200 END_LONG_DOUBLE_ROUNDING ();
2205 double arg = a.arg[dp->arg_index].a.a_double;
2209 if (dp->conversion == 'A')
2211 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2215 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2222 if (signbit (arg)) /* arg < 0.0 or negative zero */
2230 else if (flags & FLAG_SHOWSIGN)
2232 else if (flags & FLAG_SPACE)
2235 if (arg > 0.0 && arg + arg == arg)
2237 if (dp->conversion == 'A')
2239 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2243 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2252 mantissa = printf_frexp (arg, &exponent);
2260 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2262 /* Round the mantissa. */
2263 double tail = mantissa;
2266 for (q = precision; ; q--)
2268 int digit = (int) tail;
2272 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2281 for (q = precision; q > 0; q--)
2287 *p++ = dp->conversion - 'A' + 'X';
2292 digit = (int) mantissa;
2295 if ((flags & FLAG_ALT)
2296 || mantissa > 0.0 || precision > 0)
2298 *p++ = decimal_point_char ();
2299 /* This loop terminates because we assume
2300 that FLT_RADIX is a power of 2. */
2301 while (mantissa > 0.0)
2304 digit = (int) mantissa;
2309 : dp->conversion - 10);
2313 while (precision > 0)
2320 *p++ = dp->conversion - 'A' + 'P';
2321 # if WIDE_CHAR_VERSION
2323 static const wchar_t decimal_format[] =
2324 { '%', '+', 'd', '\0' };
2325 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2328 sprintf (p, "%+d", exponent);
2335 /* The generated string now extends from tmp to p, with the
2336 zero padding insertion point being at pad_ptr. */
2337 if (has_width && p - tmp < width)
2339 size_t pad = width - (p - tmp);
2340 CHAR_T *end = p + pad;
2342 if (flags & FLAG_LEFT)
2344 /* Pad with spaces on the right. */
2345 for (; pad > 0; pad--)
2348 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2350 /* Pad with zeroes. */
2355 for (; pad > 0; pad--)
2360 /* Pad with spaces on the left. */
2365 for (; pad > 0; pad--)
2373 size_t count = p - tmp;
2375 if (count >= tmp_length)
2376 /* tmp_length was incorrectly calculated - fix the
2380 /* Make room for the result. */
2381 if (count >= allocated - length)
2383 size_t n = xsum (length, count);
2385 ENSURE_ALLOCATION (n);
2388 /* Append the result. */
2389 memcpy (result + length, tmp, count * sizeof (CHAR_T));
2398 arg_type type = a.arg[dp->arg_index].type;
2399 int flags = dp->flags;
2400 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2404 #if NEED_PRINTF_FLAG_ZERO
2407 # define pad_ourselves 0
2410 unsigned int prefix_count;
2418 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2421 if (dp->width_start != dp->width_end)
2423 if (dp->width_arg_index != ARG_NONE)
2427 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2429 arg = a.arg[dp->width_arg_index].a.a_int;
2432 /* "A negative field width is taken as a '-' flag
2433 followed by a positive field width." */
2435 width = (unsigned int) (-arg);
2442 const CHAR_T *digitp = dp->width_start;
2445 width = xsum (xtimes (width, 10), *digitp++ - '0');
2446 while (digitp != dp->width_end);
2453 /* Allocate a temporary buffer of sufficient size for calling
2459 if (dp->precision_start != dp->precision_end)
2461 if (dp->precision_arg_index != ARG_NONE)
2465 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2467 arg = a.arg[dp->precision_arg_index].a.a_int;
2468 precision = (arg < 0 ? 0 : arg);
2472 const CHAR_T *digitp = dp->precision_start + 1;
2475 while (digitp != dp->precision_end)
2476 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2480 switch (dp->conversion)
2483 case 'd': case 'i': case 'u':
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.30103 /* binary -> decimal */
2490 + 1; /* turn floor into ceil */
2493 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2495 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2496 * 0.30103 /* binary -> decimal */
2498 + 1; /* turn floor into ceil */
2501 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2502 * 0.30103 /* binary -> decimal */
2504 + 1; /* turn floor into ceil */
2505 if (tmp_length < precision)
2506 tmp_length = precision;
2507 /* Multiply by 2, as an estimate for FLAG_GROUP. */
2508 tmp_length = xsum (tmp_length, tmp_length);
2509 /* Add 1, to account for a leading sign. */
2510 tmp_length = xsum (tmp_length, 1);
2514 # if HAVE_LONG_LONG_INT
2515 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2517 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2518 * 0.333334 /* binary -> octal */
2520 + 1; /* turn floor into ceil */
2523 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2525 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2526 * 0.333334 /* binary -> octal */
2528 + 1; /* turn floor into ceil */
2531 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2532 * 0.333334 /* binary -> octal */
2534 + 1; /* turn floor into ceil */
2535 if (tmp_length < precision)
2536 tmp_length = precision;
2537 /* Add 1, to account for a leading sign. */
2538 tmp_length = xsum (tmp_length, 1);
2542 # if HAVE_LONG_LONG_INT
2543 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2545 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2546 * 0.25 /* binary -> hexadecimal */
2548 + 1; /* turn floor into ceil */
2551 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2553 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2554 * 0.25 /* binary -> hexadecimal */
2556 + 1; /* turn floor into ceil */
2559 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2560 * 0.25 /* binary -> hexadecimal */
2562 + 1; /* turn floor into ceil */
2563 if (tmp_length < precision)
2564 tmp_length = precision;
2565 /* Add 2, to account for a leading sign or alternate form. */
2566 tmp_length = xsum (tmp_length, 2);
2570 if (type == TYPE_LONGDOUBLE)
2572 (unsigned int) (LDBL_MAX_EXP
2573 * 0.30103 /* binary -> decimal */
2574 * 2 /* estimate for FLAG_GROUP */
2576 + 1 /* turn floor into ceil */
2577 + 10; /* sign, decimal point etc. */
2580 (unsigned int) (DBL_MAX_EXP
2581 * 0.30103 /* binary -> decimal */
2582 * 2 /* estimate for FLAG_GROUP */
2584 + 1 /* turn floor into ceil */
2585 + 10; /* sign, decimal point etc. */
2586 tmp_length = xsum (tmp_length, precision);
2589 case 'e': case 'E': case 'g': case 'G':
2591 12; /* sign, decimal point, exponent etc. */
2592 tmp_length = xsum (tmp_length, precision);
2596 if (type == TYPE_LONGDOUBLE)
2598 (unsigned int) (LDBL_DIG
2599 * 0.831 /* decimal -> hexadecimal */
2601 + 1; /* turn floor into ceil */
2604 (unsigned int) (DBL_DIG
2605 * 0.831 /* decimal -> hexadecimal */
2607 + 1; /* turn floor into ceil */
2608 if (tmp_length < precision)
2609 tmp_length = precision;
2610 /* Account for sign, decimal point etc. */
2611 tmp_length = xsum (tmp_length, 12);
2615 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
2616 if (type == TYPE_WIDE_CHAR)
2617 tmp_length = MB_CUR_MAX;
2625 if (type == TYPE_WIDE_STRING)
2628 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
2630 # if !WIDE_CHAR_VERSION
2631 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
2636 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
2641 (unsigned int) (sizeof (void *) * CHAR_BIT
2642 * 0.25 /* binary -> hexadecimal */
2644 + 1 /* turn floor into ceil */
2645 + 2; /* account for leading 0x */
2652 if (tmp_length < width)
2655 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2658 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2662 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2664 if (size_overflow_p (tmp_memsize))
2665 /* Overflow, would lead to out of memory. */
2667 tmp = (CHAR_T *) malloc (tmp_memsize);
2669 /* Out of memory. */
2674 /* Decide whether to perform the padding ourselves. */
2675 #if NEED_PRINTF_FLAG_ZERO
2676 switch (dp->conversion)
2678 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
2688 /* Construct the format string for calling snprintf or
2692 #if NEED_PRINTF_FLAG_GROUPING
2693 /* The underlying implementation doesn't support the ' flag.
2694 Produce no grouping characters in this case; this is
2695 acceptable because the grouping is locale dependent. */
2697 if (flags & FLAG_GROUP)
2700 if (flags & FLAG_LEFT)
2702 if (flags & FLAG_SHOWSIGN)
2704 if (flags & FLAG_SPACE)
2706 if (flags & FLAG_ALT)
2710 if (flags & FLAG_ZERO)
2712 if (dp->width_start != dp->width_end)
2714 size_t n = dp->width_end - dp->width_start;
2715 memcpy (fbp, dp->width_start, n * sizeof (CHAR_T));
2719 if (dp->precision_start != dp->precision_end)
2721 size_t n = dp->precision_end - dp->precision_start;
2722 memcpy (fbp, dp->precision_start, n * sizeof (CHAR_T));
2728 #if HAVE_LONG_LONG_INT
2729 case TYPE_LONGLONGINT:
2730 case TYPE_ULONGLONGINT:
2731 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2744 case TYPE_WIDE_CHAR:
2747 case TYPE_WIDE_STRING:
2751 case TYPE_LONGDOUBLE:
2757 #if NEED_PRINTF_DIRECTIVE_F
2758 if (dp->conversion == 'F')
2762 *fbp = dp->conversion;
2771 /* Construct the arguments for calling snprintf or sprintf. */
2773 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
2775 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2777 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
2779 if (dp->precision_arg_index != ARG_NONE)
2781 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2783 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
2787 /* Prepare checking whether snprintf returns the count
2789 ENSURE_ALLOCATION (xsum (length, 1));
2790 result[length] = '\0';
2799 maxlen = allocated - length;
2804 /* SNPRINTF can fail if maxlen > INT_MAX. */
2805 if (maxlen > INT_MAX)
2807 # define SNPRINTF_BUF(arg) \
2808 switch (prefix_count) \
2811 retcount = SNPRINTF (result + length, maxlen, buf, \
2815 retcount = SNPRINTF (result + length, maxlen, buf, \
2816 prefixes[0], arg, &count); \
2819 retcount = SNPRINTF (result + length, maxlen, buf, \
2820 prefixes[0], prefixes[1], arg, \
2827 # define SNPRINTF_BUF(arg) \
2828 switch (prefix_count) \
2831 count = sprintf (tmp, buf, arg); \
2834 count = sprintf (tmp, buf, prefixes[0], arg); \
2837 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
2849 int arg = a.arg[dp->arg_index].a.a_schar;
2855 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
2861 int arg = a.arg[dp->arg_index].a.a_short;
2867 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
2873 int arg = a.arg[dp->arg_index].a.a_int;
2879 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
2885 long int arg = a.arg[dp->arg_index].a.a_longint;
2891 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
2895 #if HAVE_LONG_LONG_INT
2896 case TYPE_LONGLONGINT:
2898 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
2902 case TYPE_ULONGLONGINT:
2904 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
2911 double arg = a.arg[dp->arg_index].a.a_double;
2915 case TYPE_LONGDOUBLE:
2917 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2923 int arg = a.arg[dp->arg_index].a.a_char;
2928 case TYPE_WIDE_CHAR:
2930 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
2937 const char *arg = a.arg[dp->arg_index].a.a_string;
2942 case TYPE_WIDE_STRING:
2944 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2951 void *arg = a.arg[dp->arg_index].a.a_pointer;
2960 /* Portability: Not all implementations of snprintf()
2961 are ISO C 99 compliant. Determine the number of
2962 bytes that snprintf() has produced or would have
2966 /* Verify that snprintf() has NUL-terminated its
2968 if (count < maxlen && result[length + count] != '\0')
2970 /* Portability hack. */
2971 if (retcount > count)
2976 /* snprintf() doesn't understand the '%n'
2980 /* Don't use the '%n' directive; instead, look
2981 at the snprintf() return value. */
2987 /* Look at the snprintf() return value. */
2990 /* HP-UX 10.20 snprintf() is doubly deficient:
2991 It doesn't understand the '%n' directive,
2992 *and* it returns -1 (rather than the length
2993 that would have been required) when the
2994 buffer is too small. */
2995 size_t bigger_need =
2996 xsum (xtimes (allocated, 2), 12);
2997 ENSURE_ALLOCATION (bigger_need);
3006 /* Attempt to handle failure. */
3009 if (!(result == resultbuf || result == NULL))
3011 if (buf_malloced != NULL)
3012 free (buf_malloced);
3018 /* Make room for the result. */
3019 if (count >= maxlen)
3021 /* Need at least count bytes. But allocate
3022 proportionally, to avoid looping eternally if
3023 snprintf() reports a too small count. */
3025 xmax (xsum (length, count), xtimes (allocated, 2));
3027 ENSURE_ALLOCATION (n);
3031 maxlen = allocated - length;
3035 /* Perform padding. */
3036 #if NEED_PRINTF_FLAG_ZERO
3037 if (pad_ourselves && has_width && count < width)
3040 /* Make room for the result. */
3041 if (width >= maxlen)
3043 /* Need at least width bytes. But allocate
3044 proportionally, to avoid looping eternally if
3045 snprintf() reports a too small count. */
3047 xmax (xsum (length + 1, width),
3048 xtimes (allocated, 2));
3051 ENSURE_ALLOCATION (n);
3053 maxlen = allocated - length; /* > width */
3055 /* Here width < maxlen. */
3059 CHAR_T * const rp = result + length;
3061 CHAR_T * const rp = tmp;
3063 CHAR_T *p = rp + count;
3064 size_t pad = width - count;
3065 CHAR_T *end = p + pad;
3066 CHAR_T *pad_ptr = (*rp == '-' ? rp + 1 : rp);
3067 /* No zero-padding of "inf" and "nan". */
3068 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
3069 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
3071 /* The generated string now extends from rp to p,
3072 with the zero padding insertion point being at
3075 if (flags & FLAG_LEFT)
3077 /* Pad with spaces on the right. */
3078 for (; pad > 0; pad--)
3081 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3083 /* Pad with zeroes. */
3088 for (; pad > 0; pad--)
3093 /* Pad with spaces on the left. */
3098 for (; pad > 0; pad--)
3102 count = width; /* = count + pad = end - rp */
3108 if (count >= tmp_length)
3109 /* tmp_length was incorrectly calculated - fix the
3114 /* Here still count < maxlen. */
3117 /* The snprintf() result did fit. */
3119 /* Append the sprintf() result. */
3120 memcpy (result + length, tmp, count * sizeof (CHAR_T));
3125 #if NEED_PRINTF_DIRECTIVE_F
3126 if (dp->conversion == 'F')
3128 /* Convert the %f result to upper case for %F. */
3129 CHAR_T *rp = result + length;
3131 for (rc = count; rc > 0; rc--, rp++)
3132 if (*rp >= 'a' && *rp <= 'z')
3133 *rp = *rp - 'a' + 'A';
3144 /* Add the final NUL. */
3145 ENSURE_ALLOCATION (xsum (length, 1));
3146 result[length] = '\0';
3148 if (result != resultbuf && length + 1 < allocated)
3150 /* Shrink the allocated memory if possible. */
3153 memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
3158 if (buf_malloced != NULL)
3159 free (buf_malloced);
3162 /* Note that we can produce a big string of a length > INT_MAX. POSIX
3163 says that snprintf() fails with errno = EOVERFLOW in this case, but
3164 that's only because snprintf() returns an 'int'. This function does
3165 not have this limitation. */
3169 if (!(result == resultbuf || result == NULL))
3171 if (buf_malloced != NULL)
3172 free (buf_malloced);
3178 if (!(result == resultbuf || result == NULL))
3180 if (buf_malloced != NULL)
3181 free (buf_malloced);