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 /* Define some macros that parametrize the code:
111 VASNPRINTF The name of the function being defined.
112 FCHAR_T The element type of the format string.
113 DCHAR_T The element type of the destination (result) string.
114 TCHAR_T The element type of the temporary buffer that is
115 filled with a simple format directive, executed by
116 the system's sprintf/snprintf (or similar) function.
117 DIRECTIVE Structure denoting a format directive.
119 DIRECTIVES Structure denoting the set of format directives of a
120 format string. Depends on FCHAR_T.
121 PRINTF_PARSE Function that parses a format string.
123 SNPRINTF The system's snprintf (or similar) function.
124 Depends on DCHAR_T. */
125 #if WIDE_CHAR_VERSION
126 # define VASNPRINTF vasnwprintf
127 # define FCHAR_T wchar_t
128 # define DCHAR_T wchar_t
129 # define TCHAR_T wchar_t
130 # define DIRECTIVE wchar_t_directive
131 # define DIRECTIVES wchar_t_directives
132 # define PRINTF_PARSE wprintf_parse
133 # define USE_SNPRINTF 1
134 # if HAVE_DECL__SNWPRINTF
135 /* On Windows, the function swprintf() has a different signature than
136 on Unix; we use the _snwprintf() function instead. */
137 # define SNPRINTF _snwprintf
140 # define SNPRINTF swprintf
143 # define VASNPRINTF vasnprintf
144 # define FCHAR_T char
145 # define DCHAR_T char
146 # define TCHAR_T char
147 # define DIRECTIVE char_directive
148 # define DIRECTIVES char_directives
149 # define PRINTF_PARSE printf_parse
150 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
151 But don't use it on BeOS, since BeOS snprintf produces no output if the
152 size argument is >= 0x3000000. */
153 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
154 # define USE_SNPRINTF 1
156 # define USE_SNPRINTF 0
158 # if HAVE_DECL__SNPRINTF
160 # define SNPRINTF _snprintf
163 # define SNPRINTF snprintf
164 /* Here we need to call the native snprintf, not rpl_snprintf. */
168 /* Here we need to call the native sprintf, not rpl_sprintf. */
171 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
172 /* Determine the decimal-point character according to the current locale. */
173 # ifndef decimal_point_char_defined
174 # define decimal_point_char_defined 1
176 decimal_point_char ()
179 /* Determine it in a multithread-safe way. We know nl_langinfo is
180 multithread-safe on glibc systems, but is not required to be multithread-
181 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
182 is rarely multithread-safe. */
183 # if HAVE_NL_LANGINFO && __GLIBC__
184 point = nl_langinfo (RADIXCHAR);
187 sprintf (pointbuf, "%#.0f", 1.0);
188 point = &pointbuf[1];
190 point = localeconv () -> decimal_point;
192 /* The decimal point is always a single byte: either '.' or ','. */
193 return (point[0] != '\0' ? point[0] : '.');
198 #if NEED_PRINTF_INFINITE_DOUBLE && !defined IN_LIBINTL
200 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
202 is_infinite_or_zero (double x)
204 return isnan (x) || x + x == x;
209 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !defined IN_LIBINTL
211 /* Equivalent to !isfinite(x), but does not require libm. */
213 is_infinitel (long double x)
215 return isnanl (x) || (x + x == x && x != 0.0L);
220 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
222 /* Converting 'long double' to decimal without rare rounding bugs requires
223 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
224 (and slower) algorithms. */
226 typedef unsigned int mp_limb_t;
227 # define GMP_LIMB_BITS 32
228 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
230 typedef unsigned long long mp_twolimb_t;
231 # define GMP_TWOLIMB_BITS 64
232 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
234 /* Representation of a bignum >= 0. */
238 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
241 /* Compute the product of two bignums >= 0.
242 Return the allocated memory in case of success, NULL in case of memory
243 allocation failure. */
245 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
252 if (src1.nlimbs <= src2.nlimbs)
266 /* Now 0 <= len1 <= len2. */
269 /* src1 or src2 is zero. */
271 dest->limbs = (mp_limb_t *) malloc (1);
275 /* Here 1 <= len1 <= len2. */
281 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
284 for (k = len2; k > 0; )
286 for (i = 0; i < len1; i++)
288 mp_limb_t digit1 = p1[i];
289 mp_twolimb_t carry = 0;
290 for (j = 0; j < len2; j++)
292 mp_limb_t digit2 = p2[j];
293 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
295 dp[i + j] = (mp_limb_t) carry;
296 carry = carry >> GMP_LIMB_BITS;
298 dp[i + len2] = (mp_limb_t) carry;
301 while (dlen > 0 && dp[dlen - 1] == 0)
309 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
310 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
312 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
314 Return the allocated memory in case of success, NULL in case of memory
315 allocation failure. */
317 divide (mpn_t a, mpn_t b, mpn_t *q)
320 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
321 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
322 If m<n, then q:=0 and r:=a.
323 If m>=n=1, perform a single-precision division:
326 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
327 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
328 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
329 Normalise [q[m-1],...,q[0]], yields q.
330 If m>=n>1, perform a multiple-precision division:
331 We have a/b < beta^(m-n+1).
332 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
333 Shift a and b left by s bits, copying them. r:=a.
334 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
335 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
337 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
338 In case of overflow (q* >= beta) set q* := beta-1.
339 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
340 and c3 := b[n-2] * q*.
341 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
342 occurred. Furthermore 0 <= c3 < beta^2.
343 If there was overflow and
344 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
345 the next test can be skipped.}
346 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
347 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
349 Put r := r - b * q* * beta^j. In detail:
350 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
351 hence: u:=0, for i:=0 to n-1 do
353 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
354 u:=u div beta (+ 1, if carry in subtraction)
356 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
358 the carry u does not overflow.}
359 If a negative carry occurs, put q* := q* - 1
360 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
362 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
363 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
365 The room for q[j] can be allocated at the memory location of r[n+j].
366 Finally, round-to-even:
367 Shift r left by 1 bit.
368 If r > b or if r = b and q[0] is odd, q := q+1.
370 const mp_limb_t *a_ptr = a.limbs;
371 size_t a_len = a.nlimbs;
372 const mp_limb_t *b_ptr = b.limbs;
373 size_t b_len = b.nlimbs;
375 mp_limb_t *tmp_roomptr = NULL;
381 /* Allocate room for a_len+2 digits.
382 (Need a_len+1 digits for the real division and 1 more digit for the
383 final rounding of q.) */
384 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
389 while (a_len > 0 && a_ptr[a_len - 1] == 0)
396 /* Division by zero. */
398 if (b_ptr[b_len - 1] == 0)
404 /* Here m = a_len >= 0 and n = b_len > 0. */
408 /* m<n: trivial case. q=0, r := copy of a. */
411 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
412 q_ptr = roomptr + a_len;
417 /* n=1: single precision division.
418 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
422 mp_limb_t den = b_ptr[0];
423 mp_limb_t remainder = 0;
424 const mp_limb_t *sourceptr = a_ptr + a_len;
425 mp_limb_t *destptr = q_ptr + a_len;
427 for (count = a_len; count > 0; count--)
430 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
431 *--destptr = num / den;
432 remainder = num % den;
434 /* Normalise and store r. */
437 r_ptr[0] = remainder;
444 if (q_ptr[q_len - 1] == 0)
450 /* n>1: multiple precision division.
451 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
452 beta^(m-n-1) <= a/b < beta^(m-n+1). */
456 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
484 /* 0 <= s < GMP_LIMB_BITS.
485 Copy b, shifting it left by s bits. */
488 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
489 if (tmp_roomptr == NULL)
495 const mp_limb_t *sourceptr = b_ptr;
496 mp_limb_t *destptr = tmp_roomptr;
497 mp_twolimb_t accu = 0;
499 for (count = b_len; count > 0; count--)
501 accu += (mp_twolimb_t) *sourceptr++ << s;
502 *destptr++ = (mp_limb_t) accu;
503 accu = accu >> GMP_LIMB_BITS;
505 /* accu must be zero, since that was how s was determined. */
511 /* Copy a, shifting it left by s bits, yields r.
513 At the beginning: r = roomptr[0..a_len],
514 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
518 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
523 const mp_limb_t *sourceptr = a_ptr;
524 mp_limb_t *destptr = r_ptr;
525 mp_twolimb_t accu = 0;
527 for (count = a_len; count > 0; count--)
529 accu += (mp_twolimb_t) *sourceptr++ << s;
530 *destptr++ = (mp_limb_t) accu;
531 accu = accu >> GMP_LIMB_BITS;
533 *destptr++ = (mp_limb_t) accu;
535 q_ptr = roomptr + b_len;
536 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
538 size_t j = a_len - b_len; /* m-n */
539 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
540 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
541 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
542 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
543 /* Division loop, traversed m-n+1 times.
544 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
549 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
551 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
553 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
554 | r_ptr[j + b_len - 1];
555 q_star = num / b_msd;
560 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
561 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
562 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
563 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
564 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
566 If yes, jump directly to the subtraction loop.
567 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
568 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
569 if (r_ptr[j + b_len] > b_msd
570 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
571 /* r[j+n] >= b[n-1]+1 or
572 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
577 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
579 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
580 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
581 mp_twolimb_t c3 = /* b[n-2] * q* */
582 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
583 /* While c2 < c3, increase c2 and decrease c3.
584 Consider c3-c2. While it is > 0, decrease it by
585 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
586 this can happen only twice. */
589 q_star = q_star - 1; /* q* := q* - 1 */
590 if (c3 - c2 > b_msdd)
591 q_star = q_star - 1; /* q* := q* - 1 */
597 /* Subtract r := r - b * q* * beta^j. */
600 const mp_limb_t *sourceptr = b_ptr;
601 mp_limb_t *destptr = r_ptr + j;
602 mp_twolimb_t carry = 0;
604 for (count = b_len; count > 0; count--)
606 /* Here 0 <= carry <= q*. */
609 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
610 + (mp_limb_t) ~(*destptr);
611 /* Here 0 <= carry <= beta*q* + beta-1. */
612 *destptr++ = ~(mp_limb_t) carry;
613 carry = carry >> GMP_LIMB_BITS; /* <= q* */
615 cr = (mp_limb_t) carry;
617 /* Subtract cr from r_ptr[j + b_len], then forget about
619 if (cr > r_ptr[j + b_len])
621 /* Subtraction gave a carry. */
622 q_star = q_star - 1; /* q* := q* - 1 */
625 const mp_limb_t *sourceptr = b_ptr;
626 mp_limb_t *destptr = r_ptr + j;
629 for (count = b_len; count > 0; count--)
631 mp_limb_t source1 = *sourceptr++;
632 mp_limb_t source2 = *destptr;
633 *destptr++ = source1 + source2 + carry;
636 ? source1 >= (mp_limb_t) ~source2
637 : source1 > (mp_limb_t) ~source2);
640 /* Forget about the carry and about r[j+n]. */
643 /* q* is determined. Store it as q[j]. */
652 if (q_ptr[q_len - 1] == 0)
654 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
655 b is shifted left by s bits. */
656 /* Shift r right by s bits. */
659 mp_limb_t ptr = r_ptr + r_len;
660 mp_twolimb_t accu = 0;
662 for (count = r_len; count > 0; count--)
664 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
665 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
666 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
671 while (r_len > 0 && r_ptr[r_len - 1] == 0)
674 /* Compare r << 1 with b. */
682 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
683 | (i < r_len ? r_ptr[i] << 1 : 0);
684 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
694 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
699 for (i = 0; i < q_len; i++)
700 if (++(q_ptr[i]) != 0)
705 if (tmp_roomptr != NULL)
712 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
714 Destroys the contents of a.
715 Return the allocated memory - containing the decimal digits in low-to-high
716 order, terminated with a NUL character - in case of success, NULL in case
717 of memory allocation failure. */
719 convert_to_decimal (mpn_t a, size_t extra_zeroes)
721 mp_limb_t *a_ptr = a.limbs;
722 size_t a_len = a.nlimbs;
723 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
724 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
725 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
729 for (; extra_zeroes > 0; extra_zeroes--)
733 /* Divide a by 10^9, in-place. */
734 mp_limb_t remainder = 0;
735 mp_limb_t *ptr = a_ptr + a_len;
737 for (count = a_len; count > 0; count--)
740 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
741 *ptr = num / 1000000000;
742 remainder = num % 1000000000;
744 /* Store the remainder as 9 decimal digits. */
745 for (count = 9; count > 0; count--)
747 *d_ptr++ = '0' + (remainder % 10);
748 remainder = remainder / 10;
751 if (a_ptr[a_len - 1] == 0)
754 /* Remove leading zeroes. */
755 while (d_ptr > c_ptr && d_ptr[-1] == '0')
757 /* But keep at least one zero. */
760 /* Terminate the string. */
766 /* Assuming x is finite and >= 0:
767 write x as x = 2^e * m, where m is a bignum.
768 Return the allocated memory in case of success, NULL in case of memory
769 allocation failure. */
771 decode_long_double (long double x, int *ep, mpn_t *mp)
778 /* Allocate memory for result. */
779 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
780 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
783 /* Split into exponential part and mantissa. */
784 y = frexpl (x, &exp);
785 if (!(y >= 0.0L && y < 1.0L))
787 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
788 latter is an integer. */
789 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
790 I'm not sure whether it's safe to cast a 'long double' value between
791 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
792 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
794 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
795 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
798 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
801 if (!(y >= 0.0L && y < 1.0L))
803 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
806 if (!(y >= 0.0L && y < 1.0L))
808 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
813 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
816 if (!(y >= 0.0L && y < 1.0L))
818 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
822 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
825 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
828 if (!(y >= 0.0L && y < 1.0L))
830 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
833 if (!(y >= 0.0L && y < 1.0L))
835 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
840 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
843 *ep = exp - LDBL_MANT_BIT;
847 /* Assuming x is finite and >= 0, and n is an integer:
848 Returns the decimal representation of round (x * 10^n).
849 Return the allocated memory - containing the decimal digits in low-to-high
850 order, terminated with a NUL character - in case of success, NULL in case
851 of memory allocation failure. */
853 scale10_round_decimal_long_double (long double x, int n)
857 void *memory = decode_long_double (x, &e, &m);
864 unsigned int s_limbs;
873 /* x = 2^e * m, hence
874 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
875 = round (2^s * 5^n * m). */
878 /* Factor out a common power of 10 if possible. */
881 extra_zeroes = (s < n ? s : n);
885 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
886 Before converting to decimal, we need to compute
887 z = round (2^s * 5^n * m). */
888 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
889 sign. 2.322 is slightly larger than log(5)/log(2). */
890 abs_n = (n >= 0 ? n : -n);
891 abs_s = (s >= 0 ? s : -s);
892 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
893 + abs_s / GMP_LIMB_BITS + 1)
894 * sizeof (mp_limb_t));
895 if (pow5_ptr == NULL)
900 /* Initialize with 1. */
903 /* Multiply with 5^|n|. */
906 static mp_limb_t const small_pow5[13 + 1] =
908 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
909 48828125, 244140625, 1220703125
912 for (n13 = 0; n13 <= abs_n; n13 += 13)
914 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
916 mp_twolimb_t carry = 0;
917 for (j = 0; j < pow5_len; j++)
919 mp_limb_t digit2 = pow5_ptr[j];
920 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
921 pow5_ptr[j] = (mp_limb_t) carry;
922 carry = carry >> GMP_LIMB_BITS;
925 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
928 s_limbs = abs_s / GMP_LIMB_BITS;
929 s_bits = abs_s % GMP_LIMB_BITS;
930 if (n >= 0 ? s >= 0 : s <= 0)
932 /* Multiply with 2^|s|. */
935 mp_limb_t *ptr = pow5_ptr;
936 mp_twolimb_t accu = 0;
938 for (count = pow5_len; count > 0; count--)
940 accu += (mp_twolimb_t) *ptr << s_bits;
941 *ptr++ = (mp_limb_t) accu;
942 accu = accu >> GMP_LIMB_BITS;
946 *ptr = (mp_limb_t) accu;
953 for (count = pow5_len; count > 0;)
956 pow5_ptr[s_limbs + count] = pow5_ptr[count];
958 for (count = s_limbs; count > 0;)
965 pow5.limbs = pow5_ptr;
966 pow5.nlimbs = pow5_len;
969 /* Multiply m with pow5. No division needed. */
970 z_memory = multiply (m, pow5, &z);
974 /* Divide m by pow5 and round. */
975 z_memory = divide (m, pow5, &z);
980 pow5.limbs = pow5_ptr;
981 pow5.nlimbs = pow5_len;
985 Multiply m with pow5, then divide by 2^|s|. */
989 tmp_memory = multiply (m, pow5, &numerator);
990 if (tmp_memory == NULL)
996 /* Construct 2^|s|. */
998 mp_limb_t *ptr = pow5_ptr + pow5_len;
1000 for (i = 0; i < s_limbs; i++)
1002 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1003 denominator.limbs = ptr;
1004 denominator.nlimbs = s_limbs + 1;
1006 z_memory = divide (numerator, denominator, &z);
1012 Multiply m with 2^s, then divide by pow5. */
1015 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1016 * sizeof (mp_limb_t));
1017 if (num_ptr == NULL)
1024 mp_limb_t *destptr = num_ptr;
1027 for (i = 0; i < s_limbs; i++)
1032 const mp_limb_t *sourceptr = m.limbs;
1033 mp_twolimb_t accu = 0;
1035 for (count = m.nlimbs; count > 0; count--)
1037 accu += (mp_twolimb_t) *sourceptr++ << s;
1038 *destptr++ = (mp_limb_t) accu;
1039 accu = accu >> GMP_LIMB_BITS;
1042 *destptr++ = (mp_limb_t) accu;
1046 const mp_limb_t *sourceptr = m.limbs;
1048 for (count = m.nlimbs; count > 0; count--)
1049 *destptr++ = *sourceptr++;
1051 numerator.limbs = num_ptr;
1052 numerator.nlimbs = destptr - num_ptr;
1054 z_memory = divide (numerator, pow5, &z);
1061 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1063 if (z_memory == NULL)
1065 digits = convert_to_decimal (z, extra_zeroes);
1070 /* Assuming x is finite and > 0:
1071 Return an approximation for n with 10^n <= x < 10^(n+1).
1072 The approximation is usually the right n, but may be off by 1 sometimes. */
1074 floorlog10l (long double x)
1081 /* Split into exponential part and mantissa. */
1082 y = frexpl (x, &exp);
1083 if (!(y >= 0.0L && y < 1.0L))
1089 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1091 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1092 exp -= GMP_LIMB_BITS;
1094 if (y < (1.0L / (1 << 16)))
1096 y *= 1.0L * (1 << 16);
1099 if (y < (1.0L / (1 << 8)))
1101 y *= 1.0L * (1 << 8);
1104 if (y < (1.0L / (1 << 4)))
1106 y *= 1.0L * (1 << 4);
1109 if (y < (1.0L / (1 << 2)))
1111 y *= 1.0L * (1 << 2);
1114 if (y < (1.0L / (1 << 1)))
1116 y *= 1.0L * (1 << 1);
1120 if (!(y >= 0.5L && y < 1.0L))
1122 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1125 if (z < 0.70710678118654752444)
1127 z *= 1.4142135623730950488;
1130 if (z < 0.8408964152537145431)
1132 z *= 1.1892071150027210667;
1135 if (z < 0.91700404320467123175)
1137 z *= 1.0905077326652576592;
1140 if (z < 0.9576032806985736469)
1142 z *= 1.0442737824274138403;
1145 /* Now 0.95 <= z <= 1.01. */
1147 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1148 Four terms are enough to get an approximation with error < 10^-7. */
1149 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1150 /* Finally multiply with log(2)/log(10), yields an approximation for
1152 l *= 0.30102999566398119523;
1153 /* Round down to the next integer. */
1154 return (int) l + (l < 0 ? -1 : 0);
1160 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp, const FCHAR_T *format, va_list args)
1165 if (PRINTF_PARSE (format, &d, &a) < 0)
1176 if (printf_fetchargs (args, &a) < 0)
1184 size_t buf_neededlength;
1186 TCHAR_T *buf_malloced;
1190 /* Output string accumulator. */
1195 /* Allocate a small buffer that will hold a directive passed to
1196 sprintf or snprintf. */
1198 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1200 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1202 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1203 buf_malloced = NULL;
1208 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1209 if (size_overflow_p (buf_memsize))
1210 goto out_of_memory_1;
1211 buf = (TCHAR_T *) malloc (buf_memsize);
1213 goto out_of_memory_1;
1217 if (resultbuf != NULL)
1220 allocated = *lengthp;
1229 result is either == resultbuf or == NULL or malloc-allocated.
1230 If length > 0, then result != NULL. */
1232 /* Ensures that allocated >= needed. Aborts through a jump to
1233 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1234 #define ENSURE_ALLOCATION(needed) \
1235 if ((needed) > allocated) \
1237 size_t memory_size; \
1240 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1241 if ((needed) > allocated) \
1242 allocated = (needed); \
1243 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1244 if (size_overflow_p (memory_size)) \
1245 goto out_of_memory; \
1246 if (result == resultbuf || result == NULL) \
1247 memory = (DCHAR_T *) malloc (memory_size); \
1249 memory = (DCHAR_T *) realloc (result, memory_size); \
1250 if (memory == NULL) \
1251 goto out_of_memory; \
1252 if (result == resultbuf && length > 0) \
1253 memcpy (memory, result, length * sizeof (DCHAR_T)); \
1257 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1259 if (cp != dp->dir_start)
1261 size_t n = dp->dir_start - cp;
1262 size_t augmented_length = xsum (length, n);
1264 ENSURE_ALLOCATION (augmented_length);
1265 memcpy (result + length, cp, n * sizeof (DCHAR_T));
1266 length = augmented_length;
1271 /* Execute a single directive. */
1272 if (dp->conversion == '%')
1274 size_t augmented_length;
1276 if (!(dp->arg_index == ARG_NONE))
1278 augmented_length = xsum (length, 1);
1279 ENSURE_ALLOCATION (augmented_length);
1280 result[length] = '%';
1281 length = augmented_length;
1285 if (!(dp->arg_index != ARG_NONE))
1288 if (dp->conversion == 'n')
1290 switch (a.arg[dp->arg_index].type)
1292 case TYPE_COUNT_SCHAR_POINTER:
1293 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1295 case TYPE_COUNT_SHORT_POINTER:
1296 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1298 case TYPE_COUNT_INT_POINTER:
1299 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1301 case TYPE_COUNT_LONGINT_POINTER:
1302 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1304 #if HAVE_LONG_LONG_INT
1305 case TYPE_COUNT_LONGLONGINT_POINTER:
1306 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1313 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
1314 else if (dp->conversion == 'a' || dp->conversion == 'A')
1316 arg_type type = a.arg[dp->arg_index].type;
1317 int flags = dp->flags;
1323 DCHAR_T tmpbuf[700];
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 FCHAR_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 FCHAR_T *digitp = dp->precision_start + 1;
1384 while (digitp != dp->precision_end)
1385 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1390 /* Allocate a temporary buffer of sufficient size. */
1391 if (type == TYPE_LONGDOUBLE)
1393 (unsigned int) ((LDBL_DIG + 1)
1394 * 0.831 /* decimal -> hexadecimal */
1396 + 1; /* turn floor into ceil */
1399 (unsigned int) ((DBL_DIG + 1)
1400 * 0.831 /* decimal -> hexadecimal */
1402 + 1; /* turn floor into ceil */
1403 if (tmp_length < precision)
1404 tmp_length = precision;
1405 /* Account for sign, decimal point etc. */
1406 tmp_length = xsum (tmp_length, 12);
1408 if (tmp_length < width)
1411 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1413 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
1417 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
1419 if (size_overflow_p (tmp_memsize))
1420 /* Overflow, would lead to out of memory. */
1422 tmp = (DCHAR_T *) malloc (tmp_memsize);
1424 /* Out of memory. */
1430 if (type == TYPE_LONGDOUBLE)
1432 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1436 if (dp->conversion == 'A')
1438 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1442 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1448 DECL_LONG_DOUBLE_ROUNDING
1450 BEGIN_LONG_DOUBLE_ROUNDING ();
1452 if (signbit (arg)) /* arg < 0.0L or negative zero */
1460 else if (flags & FLAG_SHOWSIGN)
1462 else if (flags & FLAG_SPACE)
1465 if (arg > 0.0L && arg + arg == arg)
1467 if (dp->conversion == 'A')
1469 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1473 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1479 long double mantissa;
1482 mantissa = printf_frexpl (arg, &exponent);
1490 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
1492 /* Round the mantissa. */
1493 long double tail = mantissa;
1496 for (q = precision; ; q--)
1498 int digit = (int) tail;
1502 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
1511 for (q = precision; q > 0; q--)
1517 *p++ = dp->conversion - 'A' + 'X';
1522 digit = (int) mantissa;
1525 if ((flags & FLAG_ALT)
1526 || mantissa > 0.0L || precision > 0)
1528 *p++ = decimal_point_char ();
1529 /* This loop terminates because we assume
1530 that FLT_RADIX is a power of 2. */
1531 while (mantissa > 0.0L)
1534 digit = (int) mantissa;
1539 : dp->conversion - 10);
1543 while (precision > 0)
1550 *p++ = dp->conversion - 'A' + 'P';
1551 # if WIDE_CHAR_VERSION
1553 static const wchar_t decimal_format[] =
1554 { '%', '+', 'd', '\0' };
1555 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1558 sprintf (p, "%+d", exponent);
1564 END_LONG_DOUBLE_ROUNDING ();
1569 double arg = a.arg[dp->arg_index].a.a_double;
1573 if (dp->conversion == 'A')
1575 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1579 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1586 if (signbit (arg)) /* arg < 0.0 or negative zero */
1594 else if (flags & FLAG_SHOWSIGN)
1596 else if (flags & FLAG_SPACE)
1599 if (arg > 0.0 && arg + arg == arg)
1601 if (dp->conversion == 'A')
1603 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1607 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1616 mantissa = printf_frexp (arg, &exponent);
1624 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
1626 /* Round the mantissa. */
1627 double tail = mantissa;
1630 for (q = precision; ; q--)
1632 int digit = (int) tail;
1636 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
1645 for (q = precision; q > 0; q--)
1651 *p++ = dp->conversion - 'A' + 'X';
1656 digit = (int) mantissa;
1659 if ((flags & FLAG_ALT)
1660 || mantissa > 0.0 || precision > 0)
1662 *p++ = decimal_point_char ();
1663 /* This loop terminates because we assume
1664 that FLT_RADIX is a power of 2. */
1665 while (mantissa > 0.0)
1668 digit = (int) mantissa;
1673 : dp->conversion - 10);
1677 while (precision > 0)
1684 *p++ = dp->conversion - 'A' + 'P';
1685 # if WIDE_CHAR_VERSION
1687 static const wchar_t decimal_format[] =
1688 { '%', '+', 'd', '\0' };
1689 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1692 sprintf (p, "%+d", exponent);
1699 /* The generated string now extends from tmp to p, with the
1700 zero padding insertion point being at pad_ptr. */
1701 if (has_width && p - tmp < width)
1703 size_t pad = width - (p - tmp);
1704 DCHAR_T *end = p + pad;
1706 if (flags & FLAG_LEFT)
1708 /* Pad with spaces on the right. */
1709 for (; pad > 0; pad--)
1712 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
1714 /* Pad with zeroes. */
1719 for (; pad > 0; pad--)
1724 /* Pad with spaces on the left. */
1729 for (; pad > 0; pad--)
1737 size_t count = p - tmp;
1739 if (count >= tmp_length)
1740 /* tmp_length was incorrectly calculated - fix the
1744 /* Make room for the result. */
1745 if (count >= allocated - length)
1747 size_t n = xsum (length, count);
1749 ENSURE_ALLOCATION (n);
1752 /* Append the result. */
1753 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
1760 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
1761 else if ((dp->conversion == 'f' || dp->conversion == 'F'
1762 || dp->conversion == 'e' || dp->conversion == 'E'
1763 || dp->conversion == 'g' || dp->conversion == 'G'
1764 || dp->conversion == 'a' || dp->conversion == 'A')
1766 # if NEED_PRINTF_INFINITE_DOUBLE
1767 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
1768 /* The systems (mingw) which produce wrong output
1769 for Inf, -Inf, and NaN also do so for -0.0.
1770 Therefore we treat this case here as well. */
1771 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
1773 # if NEED_PRINTF_LONG_DOUBLE
1774 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
1775 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
1776 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
1777 /* Some systems produce wrong output for Inf,
1779 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
1783 # if NEED_PRINTF_INFINITE_DOUBLE && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
1784 arg_type type = a.arg[dp->arg_index].type;
1786 int flags = dp->flags;
1792 DCHAR_T tmpbuf[700];
1799 if (dp->width_start != dp->width_end)
1801 if (dp->width_arg_index != ARG_NONE)
1805 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1807 arg = a.arg[dp->width_arg_index].a.a_int;
1810 /* "A negative field width is taken as a '-' flag
1811 followed by a positive field width." */
1813 width = (unsigned int) (-arg);
1820 const FCHAR_T *digitp = dp->width_start;
1823 width = xsum (xtimes (width, 10), *digitp++ - '0');
1824 while (digitp != dp->width_end);
1831 if (dp->precision_start != dp->precision_end)
1833 if (dp->precision_arg_index != ARG_NONE)
1837 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1839 arg = a.arg[dp->precision_arg_index].a.a_int;
1840 /* "A negative precision is taken as if the precision
1850 const FCHAR_T *digitp = dp->precision_start + 1;
1853 while (digitp != dp->precision_end)
1854 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1859 /* POSIX specifies the default precision to be 6 for %f, %F,
1860 %e, %E, but not for %g, %G. Implementations appear to use
1861 the same default precision also for %g, %G. */
1865 /* Allocate a temporary buffer of sufficient size. */
1866 # if NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
1867 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
1868 # elif NEED_PRINTF_LONG_DOUBLE
1869 tmp_length = LDBL_DIG + 1;
1873 if (tmp_length < precision)
1874 tmp_length = precision;
1875 # if NEED_PRINTF_LONG_DOUBLE
1876 # if NEED_PRINTF_INFINITE_DOUBLE
1877 if (type == TYPE_LONGDOUBLE)
1879 if (dp->conversion == 'f' || dp->conversion == 'F')
1881 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1882 if (!(isnanl (arg) || arg + arg == arg))
1884 /* arg is finite and nonzero. */
1885 int exponent = floorlog10l (arg < 0 ? -arg : arg);
1886 if (exponent >= 0 && tmp_length < exponent + precision)
1887 tmp_length = exponent + precision;
1891 /* Account for sign, decimal point etc. */
1892 tmp_length = xsum (tmp_length, 12);
1894 if (tmp_length < width)
1897 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1899 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
1903 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
1905 if (size_overflow_p (tmp_memsize))
1906 /* Overflow, would lead to out of memory. */
1908 tmp = (DCHAR_T *) malloc (tmp_memsize);
1910 /* Out of memory. */
1917 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
1918 # if NEED_PRINTF_INFINITE_DOUBLE
1919 if (type == TYPE_LONGDOUBLE)
1922 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1926 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1928 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1932 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1938 DECL_LONG_DOUBLE_ROUNDING
1940 BEGIN_LONG_DOUBLE_ROUNDING ();
1942 if (signbit (arg)) /* arg < 0.0L or negative zero */
1950 else if (flags & FLAG_SHOWSIGN)
1952 else if (flags & FLAG_SPACE)
1955 if (arg > 0.0L && arg + arg == arg)
1957 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1959 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1963 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1968 # if NEED_PRINTF_LONG_DOUBLE
1971 if (dp->conversion == 'f' || dp->conversion == 'F')
1977 scale10_round_decimal_long_double (arg, precision);
1980 END_LONG_DOUBLE_ROUNDING ();
1983 ndigits = strlen (digits);
1985 if (ndigits > precision)
1989 *p++ = digits[ndigits];
1991 while (ndigits > precision);
1994 /* Here ndigits <= precision. */
1995 if ((flags & FLAG_ALT) || precision > 0)
1997 *p++ = decimal_point_char ();
1998 for (; precision > ndigits; precision--)
2003 *p++ = digits[ndigits];
2009 else if (dp->conversion == 'e' || dp->conversion == 'E')
2017 if ((flags & FLAG_ALT) || precision > 0)
2019 *p++ = decimal_point_char ();
2020 for (; precision > 0; precision--)
2031 exponent = floorlog10l (arg);
2036 scale10_round_decimal_long_double (arg,
2037 (int)precision - exponent);
2040 END_LONG_DOUBLE_ROUNDING ();
2043 ndigits = strlen (digits);
2045 if (ndigits == precision + 1)
2047 if (ndigits < precision
2048 || ndigits > precision + 2)
2049 /* The exponent was not guessed
2050 precisely enough. */
2053 /* None of two values of exponent is
2054 the right one. Prevent an endless
2058 if (ndigits == precision)
2065 /* Here ndigits = precision+1. */
2066 *p++ = digits[--ndigits];
2067 if ((flags & FLAG_ALT) || precision > 0)
2069 *p++ = decimal_point_char ();
2073 *p++ = digits[ndigits];
2080 *p++ = dp->conversion; /* 'e' or 'E' */
2081 # if WIDE_CHAR_VERSION
2083 static const wchar_t decimal_format[] =
2084 { '%', '+', '.', '2', 'd', '\0' };
2085 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2088 sprintf (p, "%+.2d", exponent);
2093 else if (dp->conversion == 'g' || dp->conversion == 'G')
2097 /* precision >= 1. */
2100 /* The exponent is 0, >= -4, < precision.
2101 Use fixed-point notation. */
2103 size_t ndigits = precision;
2104 /* Number of trailing zeroes that have to be
2107 (flags & FLAG_ALT ? 0 : precision - 1);
2111 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2113 *p++ = decimal_point_char ();
2114 while (ndigits > nzeroes)
2130 exponent = floorlog10l (arg);
2135 scale10_round_decimal_long_double (arg,
2136 (int)(precision - 1) - exponent);
2139 END_LONG_DOUBLE_ROUNDING ();
2142 ndigits = strlen (digits);
2144 if (ndigits == precision)
2146 if (ndigits < precision - 1
2147 || ndigits > precision + 1)
2148 /* The exponent was not guessed
2149 precisely enough. */
2152 /* None of two values of exponent is
2153 the right one. Prevent an endless
2157 if (ndigits < precision)
2163 /* Here ndigits = precision. */
2165 /* Determine the number of trailing zeroes
2166 that have to be dropped. */
2168 if ((flags & FLAG_ALT) == 0)
2169 while (nzeroes < ndigits
2170 && digits[nzeroes] == '0')
2173 /* The exponent is now determined. */
2175 && exponent < (long)precision)
2177 /* Fixed-point notation:
2178 max(exponent,0)+1 digits, then the
2179 decimal point, then the remaining
2180 digits without trailing zeroes. */
2183 size_t count = exponent + 1;
2184 /* Note: count <= precision = ndigits. */
2185 for (; count > 0; count--)
2186 *p++ = digits[--ndigits];
2187 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2189 *p++ = decimal_point_char ();
2190 while (ndigits > nzeroes)
2193 *p++ = digits[ndigits];
2199 size_t count = -exponent - 1;
2201 *p++ = decimal_point_char ();
2202 for (; count > 0; count--)
2204 while (ndigits > nzeroes)
2207 *p++ = digits[ndigits];
2213 /* Exponential notation. */
2214 *p++ = digits[--ndigits];
2215 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2217 *p++ = decimal_point_char ();
2218 while (ndigits > nzeroes)
2221 *p++ = digits[ndigits];
2224 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
2225 # if WIDE_CHAR_VERSION
2227 static const wchar_t decimal_format[] =
2228 { '%', '+', '.', '2', 'd', '\0' };
2229 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2232 sprintf (p, "%+.2d", exponent);
2244 /* arg is finite. */
2249 END_LONG_DOUBLE_ROUNDING ();
2252 # if NEED_PRINTF_INFINITE_DOUBLE
2256 # if NEED_PRINTF_INFINITE_DOUBLE
2258 /* Simpler than above: handle only NaN, Infinity, zero. */
2259 double arg = a.arg[dp->arg_index].a.a_double;
2263 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2265 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2269 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2276 if (signbit (arg)) /* arg < 0.0L or negative zero */
2284 else if (flags & FLAG_SHOWSIGN)
2286 else if (flags & FLAG_SPACE)
2289 if (arg > 0.0 && arg + arg == arg)
2291 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2293 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2297 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2307 if (dp->conversion == 'f' || dp->conversion == 'F')
2310 if ((flags & FLAG_ALT) || precision > 0)
2312 *p++ = decimal_point_char ();
2313 for (; precision > 0; precision--)
2317 else if (dp->conversion == 'e' || dp->conversion == 'E')
2320 if ((flags & FLAG_ALT) || precision > 0)
2322 *p++ = decimal_point_char ();
2323 for (; precision > 0; precision--)
2326 *p++ = dp->conversion; /* 'e' or 'E' */
2328 /* Produce the same number of exponent digits as
2329 the native printf implementation. */
2330 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2336 else if (dp->conversion == 'g' || dp->conversion == 'G')
2339 if (flags & FLAG_ALT)
2342 (precision > 0 ? precision - 1 : 0);
2343 *p++ = decimal_point_char ();
2344 for (; ndigits > 0; --ndigits)
2355 /* The generated string now extends from tmp to p, with the
2356 zero padding insertion point being at pad_ptr. */
2357 if (has_width && p - tmp < width)
2359 size_t pad = width - (p - tmp);
2360 DCHAR_T *end = p + pad;
2362 if (flags & FLAG_LEFT)
2364 /* Pad with spaces on the right. */
2365 for (; pad > 0; pad--)
2368 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2370 /* Pad with zeroes. */
2375 for (; pad > 0; pad--)
2380 /* Pad with spaces on the left. */
2385 for (; pad > 0; pad--)
2393 size_t count = p - tmp;
2395 if (count >= tmp_length)
2396 /* tmp_length was incorrectly calculated - fix the
2400 /* Make room for the result. */
2401 if (count >= allocated - length)
2403 size_t n = xsum (length, count);
2405 ENSURE_ALLOCATION (n);
2408 /* Append the result. */
2409 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2418 arg_type type = a.arg[dp->arg_index].type;
2419 int flags = dp->flags;
2420 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2424 #if NEED_PRINTF_FLAG_ZERO
2427 # define pad_ourselves 0
2430 unsigned int prefix_count;
2434 DCHAR_T tmpbuf[700];
2438 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2441 if (dp->width_start != dp->width_end)
2443 if (dp->width_arg_index != ARG_NONE)
2447 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2449 arg = a.arg[dp->width_arg_index].a.a_int;
2452 /* "A negative field width is taken as a '-' flag
2453 followed by a positive field width." */
2455 width = (unsigned int) (-arg);
2462 const FCHAR_T *digitp = dp->width_start;
2465 width = xsum (xtimes (width, 10), *digitp++ - '0');
2466 while (digitp != dp->width_end);
2473 /* Allocate a temporary buffer of sufficient size for calling
2479 if (dp->precision_start != dp->precision_end)
2481 if (dp->precision_arg_index != ARG_NONE)
2485 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2487 arg = a.arg[dp->precision_arg_index].a.a_int;
2488 precision = (arg < 0 ? 0 : arg);
2492 const FCHAR_T *digitp = dp->precision_start + 1;
2495 while (digitp != dp->precision_end)
2496 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2500 switch (dp->conversion)
2503 case 'd': case 'i': case 'u':
2504 # if HAVE_LONG_LONG_INT
2505 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2507 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2508 * 0.30103 /* binary -> decimal */
2510 + 1; /* turn floor into ceil */
2513 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2515 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2516 * 0.30103 /* binary -> decimal */
2518 + 1; /* turn floor into ceil */
2521 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2522 * 0.30103 /* binary -> decimal */
2524 + 1; /* turn floor into ceil */
2525 if (tmp_length < precision)
2526 tmp_length = precision;
2527 /* Multiply by 2, as an estimate for FLAG_GROUP. */
2528 tmp_length = xsum (tmp_length, tmp_length);
2529 /* Add 1, to account for a leading sign. */
2530 tmp_length = xsum (tmp_length, 1);
2534 # if HAVE_LONG_LONG_INT
2535 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2537 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2538 * 0.333334 /* binary -> octal */
2540 + 1; /* turn floor into ceil */
2543 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2545 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2546 * 0.333334 /* binary -> octal */
2548 + 1; /* turn floor into ceil */
2551 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2552 * 0.333334 /* binary -> octal */
2554 + 1; /* turn floor into ceil */
2555 if (tmp_length < precision)
2556 tmp_length = precision;
2557 /* Add 1, to account for a leading sign. */
2558 tmp_length = xsum (tmp_length, 1);
2562 # if HAVE_LONG_LONG_INT
2563 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2565 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2566 * 0.25 /* binary -> hexadecimal */
2568 + 1; /* turn floor into ceil */
2571 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2573 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2574 * 0.25 /* binary -> hexadecimal */
2576 + 1; /* turn floor into ceil */
2579 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2580 * 0.25 /* binary -> hexadecimal */
2582 + 1; /* turn floor into ceil */
2583 if (tmp_length < precision)
2584 tmp_length = precision;
2585 /* Add 2, to account for a leading sign or alternate form. */
2586 tmp_length = xsum (tmp_length, 2);
2590 if (type == TYPE_LONGDOUBLE)
2592 (unsigned int) (LDBL_MAX_EXP
2593 * 0.30103 /* binary -> decimal */
2594 * 2 /* estimate for FLAG_GROUP */
2596 + 1 /* turn floor into ceil */
2597 + 10; /* sign, decimal point etc. */
2600 (unsigned int) (DBL_MAX_EXP
2601 * 0.30103 /* binary -> decimal */
2602 * 2 /* estimate for FLAG_GROUP */
2604 + 1 /* turn floor into ceil */
2605 + 10; /* sign, decimal point etc. */
2606 tmp_length = xsum (tmp_length, precision);
2609 case 'e': case 'E': case 'g': case 'G':
2611 12; /* sign, decimal point, exponent etc. */
2612 tmp_length = xsum (tmp_length, precision);
2616 if (type == TYPE_LONGDOUBLE)
2618 (unsigned int) (LDBL_DIG
2619 * 0.831 /* decimal -> hexadecimal */
2621 + 1; /* turn floor into ceil */
2624 (unsigned int) (DBL_DIG
2625 * 0.831 /* decimal -> hexadecimal */
2627 + 1; /* turn floor into ceil */
2628 if (tmp_length < precision)
2629 tmp_length = precision;
2630 /* Account for sign, decimal point etc. */
2631 tmp_length = xsum (tmp_length, 12);
2635 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
2636 if (type == TYPE_WIDE_CHAR)
2637 tmp_length = MB_CUR_MAX;
2645 if (type == TYPE_WIDE_STRING)
2648 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
2650 # if !WIDE_CHAR_VERSION
2651 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
2656 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
2661 (unsigned int) (sizeof (void *) * CHAR_BIT
2662 * 0.25 /* binary -> hexadecimal */
2664 + 1 /* turn floor into ceil */
2665 + 2; /* account for leading 0x */
2672 if (tmp_length < width)
2675 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2678 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2682 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2684 if (size_overflow_p (tmp_memsize))
2685 /* Overflow, would lead to out of memory. */
2687 tmp = (DCHAR_T *) malloc (tmp_memsize);
2689 /* Out of memory. */
2694 /* Decide whether to perform the padding ourselves. */
2695 #if NEED_PRINTF_FLAG_ZERO
2696 switch (dp->conversion)
2698 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
2708 /* Construct the format string for calling snprintf or
2712 #if NEED_PRINTF_FLAG_GROUPING
2713 /* The underlying implementation doesn't support the ' flag.
2714 Produce no grouping characters in this case; this is
2715 acceptable because the grouping is locale dependent. */
2717 if (flags & FLAG_GROUP)
2720 if (flags & FLAG_LEFT)
2722 if (flags & FLAG_SHOWSIGN)
2724 if (flags & FLAG_SPACE)
2726 if (flags & FLAG_ALT)
2730 if (flags & FLAG_ZERO)
2732 if (dp->width_start != dp->width_end)
2734 size_t n = dp->width_end - dp->width_start;
2735 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
2739 if (dp->precision_start != dp->precision_end)
2741 size_t n = dp->precision_end - dp->precision_start;
2742 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
2748 #if HAVE_LONG_LONG_INT
2749 case TYPE_LONGLONGINT:
2750 case TYPE_ULONGLONGINT:
2751 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2764 case TYPE_WIDE_CHAR:
2767 case TYPE_WIDE_STRING:
2771 case TYPE_LONGDOUBLE:
2777 #if NEED_PRINTF_DIRECTIVE_F
2778 if (dp->conversion == 'F')
2782 *fbp = dp->conversion;
2791 /* Construct the arguments for calling snprintf or sprintf. */
2793 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
2795 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2797 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
2799 if (dp->precision_arg_index != ARG_NONE)
2801 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2803 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
2807 /* Prepare checking whether snprintf returns the count
2809 ENSURE_ALLOCATION (xsum (length, 1));
2810 result[length] = '\0';
2819 maxlen = allocated - length;
2824 /* SNPRINTF can fail if maxlen > INT_MAX. */
2825 if (maxlen > INT_MAX)
2827 # define SNPRINTF_BUF(arg) \
2828 switch (prefix_count) \
2831 retcount = SNPRINTF (result + length, maxlen, buf, \
2835 retcount = SNPRINTF (result + length, maxlen, buf, \
2836 prefixes[0], arg, &count); \
2839 retcount = SNPRINTF (result + length, maxlen, buf, \
2840 prefixes[0], prefixes[1], arg, \
2847 # define SNPRINTF_BUF(arg) \
2848 switch (prefix_count) \
2851 count = sprintf (tmp, buf, arg); \
2854 count = sprintf (tmp, buf, prefixes[0], arg); \
2857 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
2869 int arg = a.arg[dp->arg_index].a.a_schar;
2875 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
2881 int arg = a.arg[dp->arg_index].a.a_short;
2887 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
2893 int arg = a.arg[dp->arg_index].a.a_int;
2899 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
2905 long int arg = a.arg[dp->arg_index].a.a_longint;
2911 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
2915 #if HAVE_LONG_LONG_INT
2916 case TYPE_LONGLONGINT:
2918 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
2922 case TYPE_ULONGLONGINT:
2924 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
2931 double arg = a.arg[dp->arg_index].a.a_double;
2935 case TYPE_LONGDOUBLE:
2937 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2943 int arg = a.arg[dp->arg_index].a.a_char;
2948 case TYPE_WIDE_CHAR:
2950 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
2957 const char *arg = a.arg[dp->arg_index].a.a_string;
2962 case TYPE_WIDE_STRING:
2964 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2971 void *arg = a.arg[dp->arg_index].a.a_pointer;
2980 /* Portability: Not all implementations of snprintf()
2981 are ISO C 99 compliant. Determine the number of
2982 bytes that snprintf() has produced or would have
2986 /* Verify that snprintf() has NUL-terminated its
2988 if (count < maxlen && result[length + count] != '\0')
2990 /* Portability hack. */
2991 if (retcount > count)
2996 /* snprintf() doesn't understand the '%n'
3000 /* Don't use the '%n' directive; instead, look
3001 at the snprintf() return value. */
3007 /* Look at the snprintf() return value. */
3010 /* HP-UX 10.20 snprintf() is doubly deficient:
3011 It doesn't understand the '%n' directive,
3012 *and* it returns -1 (rather than the length
3013 that would have been required) when the
3014 buffer is too small. */
3015 size_t bigger_need =
3016 xsum (xtimes (allocated, 2), 12);
3017 ENSURE_ALLOCATION (bigger_need);
3026 /* Attempt to handle failure. */
3029 if (!(result == resultbuf || result == NULL))
3031 if (buf_malloced != NULL)
3032 free (buf_malloced);
3038 /* Make room for the result. */
3039 if (count >= maxlen)
3041 /* Need at least count bytes. But allocate
3042 proportionally, to avoid looping eternally if
3043 snprintf() reports a too small count. */
3045 xmax (xsum (length, count), xtimes (allocated, 2));
3047 ENSURE_ALLOCATION (n);
3051 maxlen = allocated - length;
3055 /* Perform padding. */
3056 #if NEED_PRINTF_FLAG_ZERO
3057 if (pad_ourselves && has_width && count < width)
3060 /* Make room for the result. */
3061 if (width >= maxlen)
3063 /* Need at least width bytes. But allocate
3064 proportionally, to avoid looping eternally if
3065 snprintf() reports a too small count. */
3067 xmax (xsum (length + 1, width),
3068 xtimes (allocated, 2));
3071 ENSURE_ALLOCATION (n);
3073 maxlen = allocated - length; /* > width */
3075 /* Here width < maxlen. */
3079 DCHAR_T * const rp = result + length;
3081 DCHAR_T * const rp = tmp;
3083 DCHAR_T *p = rp + count;
3084 size_t pad = width - count;
3085 DCHAR_T *end = p + pad;
3086 DCHAR_T *pad_ptr = (*rp == '-' ? rp + 1 : rp);
3087 /* No zero-padding of "inf" and "nan". */
3088 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
3089 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
3091 /* The generated string now extends from rp to p,
3092 with the zero padding insertion point being at
3095 if (flags & FLAG_LEFT)
3097 /* Pad with spaces on the right. */
3098 for (; pad > 0; pad--)
3101 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3103 /* Pad with zeroes. */
3108 for (; pad > 0; pad--)
3113 /* Pad with spaces on the left. */
3118 for (; pad > 0; pad--)
3122 count = width; /* = count + pad = end - rp */
3128 if (count >= tmp_length)
3129 /* tmp_length was incorrectly calculated - fix the
3134 /* Here still count < maxlen. */
3137 /* The snprintf() result did fit. */
3139 /* Append the sprintf() result. */
3140 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3145 #if NEED_PRINTF_DIRECTIVE_F
3146 if (dp->conversion == 'F')
3148 /* Convert the %f result to upper case for %F. */
3149 DCHAR_T *rp = result + length;
3151 for (rc = count; rc > 0; rc--, rp++)
3152 if (*rp >= 'a' && *rp <= 'z')
3153 *rp = *rp - 'a' + 'A';
3164 /* Add the final NUL. */
3165 ENSURE_ALLOCATION (xsum (length, 1));
3166 result[length] = '\0';
3168 if (result != resultbuf && length + 1 < allocated)
3170 /* Shrink the allocated memory if possible. */
3173 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
3178 if (buf_malloced != NULL)
3179 free (buf_malloced);
3182 /* Note that we can produce a big string of a length > INT_MAX. POSIX
3183 says that snprintf() fails with errno = EOVERFLOW in this case, but
3184 that's only because snprintf() returns an 'int'. This function does
3185 not have this limitation. */
3189 if (!(result == resultbuf || result == NULL))
3191 if (buf_malloced != NULL)
3192 free (buf_malloced);
3198 if (!(result == resultbuf || result == NULL))
3200 if (buf_malloced != NULL)
3201 free (buf_malloced);