1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2008 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 /* This file can be parametrized with the following macros:
19 VASNPRINTF The name of the function being defined.
20 FCHAR_T The element type of the format string.
21 DCHAR_T The element type of the destination (result) string.
22 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
23 in the format string are ASCII. MUST be set if
24 FCHAR_T and DCHAR_T are not the same type.
25 DIRECTIVE Structure denoting a format directive.
27 DIRECTIVES Structure denoting the set of format directives of a
28 format string. Depends on FCHAR_T.
29 PRINTF_PARSE Function that parses a format string.
31 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
32 DCHAR_SET memset like function for DCHAR_T[] arrays.
33 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
34 SNPRINTF The system's snprintf (or similar) function.
35 This may be either snprintf or swprintf.
36 TCHAR_T The element type of the argument and result string
37 of the said SNPRINTF function. This may be either
38 char or wchar_t. The code exploits that
39 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
40 alignof (TCHAR_T) <= alignof (DCHAR_T).
41 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
42 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
43 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
44 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
45 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
47 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
48 This must come before <config.h> because <config.h> may include
49 <features.h>, and once <features.h> has been included, it's too late. */
51 # define _GNU_SOURCE 1
63 # if WIDE_CHAR_VERSION
64 # include "vasnwprintf.h"
66 # include "vasnprintf.h"
70 #include <locale.h> /* localeconv() */
71 #include <stdio.h> /* snprintf(), sprintf() */
72 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
73 #include <string.h> /* memcpy(), strlen() */
74 #include <errno.h> /* errno */
75 #include <limits.h> /* CHAR_BIT */
76 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
78 # include <langinfo.h>
81 # if WIDE_CHAR_VERSION
82 # include "wprintf-parse.h"
84 # include "printf-parse.h"
88 /* Checked size_t computations. */
91 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
96 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
101 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
103 # include "isnanl-nolibm.h"
107 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
110 # include "printf-frexp.h"
113 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
115 # include "isnanl-nolibm.h"
116 # include "printf-frexpl.h"
120 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
122 # define IF_LINT(Code) Code
124 # define IF_LINT(Code) /* empty */
129 # define local_wcslen wcslen
131 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
132 a dependency towards this library, here is a local substitute.
133 Define this substitute only once, even if this file is included
134 twice in the same compilation unit. */
135 # ifndef local_wcslen_defined
136 # define local_wcslen_defined 1
138 local_wcslen (const wchar_t *s)
142 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
150 /* Default parameters. */
152 # if WIDE_CHAR_VERSION
153 # define VASNPRINTF vasnwprintf
154 # define FCHAR_T wchar_t
155 # define DCHAR_T wchar_t
156 # define TCHAR_T wchar_t
157 # define DCHAR_IS_TCHAR 1
158 # define DIRECTIVE wchar_t_directive
159 # define DIRECTIVES wchar_t_directives
160 # define PRINTF_PARSE wprintf_parse
161 # define DCHAR_CPY wmemcpy
163 # define VASNPRINTF vasnprintf
164 # define FCHAR_T char
165 # define DCHAR_T char
166 # define TCHAR_T char
167 # define DCHAR_IS_TCHAR 1
168 # define DIRECTIVE char_directive
169 # define DIRECTIVES char_directives
170 # define PRINTF_PARSE printf_parse
171 # define DCHAR_CPY memcpy
174 #if WIDE_CHAR_VERSION
175 /* TCHAR_T is wchar_t. */
176 # define USE_SNPRINTF 1
177 # if HAVE_DECL__SNWPRINTF
178 /* On Windows, the function swprintf() has a different signature than
179 on Unix; we use the _snwprintf() function instead. */
180 # define SNPRINTF _snwprintf
183 # define SNPRINTF swprintf
186 /* TCHAR_T is char. */
187 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
188 But don't use it on BeOS, since BeOS snprintf produces no output if the
189 size argument is >= 0x3000000.
190 Also don't use it on Linux libc5, since there snprintf with size = 1
191 writes any output without bounds, like sprintf. */
192 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
193 # define USE_SNPRINTF 1
195 # define USE_SNPRINTF 0
197 # if HAVE_DECL__SNPRINTF
199 # define SNPRINTF _snprintf
202 # define SNPRINTF snprintf
203 /* Here we need to call the native snprintf, not rpl_snprintf. */
207 /* Here we need to call the native sprintf, not rpl_sprintf. */
210 /* Avoid some warnings from "gcc -Wshadow".
211 This file doesn't use the exp() and remainder() functions. */
215 #define remainder rem
217 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
218 /* Determine the decimal-point character according to the current locale. */
219 # ifndef decimal_point_char_defined
220 # define decimal_point_char_defined 1
222 decimal_point_char ()
225 /* Determine it in a multithread-safe way. We know nl_langinfo is
226 multithread-safe on glibc systems, but is not required to be multithread-
227 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
228 is rarely multithread-safe. */
229 # if HAVE_NL_LANGINFO && __GLIBC__
230 point = nl_langinfo (RADIXCHAR);
233 sprintf (pointbuf, "%#.0f", 1.0);
234 point = &pointbuf[1];
236 point = localeconv () -> decimal_point;
238 /* The decimal point is always a single byte: either '.' or ','. */
239 return (point[0] != '\0' ? point[0] : '.');
244 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
246 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
248 is_infinite_or_zero (double x)
250 return isnand (x) || x + x == x;
255 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
257 /* Equivalent to !isfinite(x), but does not require libm. */
259 is_infinitel (long double x)
261 return isnanl (x) || (x + x == x && x != 0.0L);
266 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
268 /* Converting 'long double' to decimal without rare rounding bugs requires
269 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
270 (and slower) algorithms. */
272 typedef unsigned int mp_limb_t;
273 # define GMP_LIMB_BITS 32
274 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
276 typedef unsigned long long mp_twolimb_t;
277 # define GMP_TWOLIMB_BITS 64
278 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
280 /* Representation of a bignum >= 0. */
284 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
287 /* Compute the product of two bignums >= 0.
288 Return the allocated memory in case of success, NULL in case of memory
289 allocation failure. */
291 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
298 if (src1.nlimbs <= src2.nlimbs)
312 /* Now 0 <= len1 <= len2. */
315 /* src1 or src2 is zero. */
317 dest->limbs = (mp_limb_t *) malloc (1);
321 /* Here 1 <= len1 <= len2. */
327 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
330 for (k = len2; k > 0; )
332 for (i = 0; i < len1; i++)
334 mp_limb_t digit1 = p1[i];
335 mp_twolimb_t carry = 0;
336 for (j = 0; j < len2; j++)
338 mp_limb_t digit2 = p2[j];
339 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
341 dp[i + j] = (mp_limb_t) carry;
342 carry = carry >> GMP_LIMB_BITS;
344 dp[i + len2] = (mp_limb_t) carry;
347 while (dlen > 0 && dp[dlen - 1] == 0)
355 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
356 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
358 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
360 Return the allocated memory in case of success, NULL in case of memory
361 allocation failure. */
363 divide (mpn_t a, mpn_t b, mpn_t *q)
366 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
367 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
368 If m<n, then q:=0 and r:=a.
369 If m>=n=1, perform a single-precision division:
372 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
373 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
374 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
375 Normalise [q[m-1],...,q[0]], yields q.
376 If m>=n>1, perform a multiple-precision division:
377 We have a/b < beta^(m-n+1).
378 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
379 Shift a and b left by s bits, copying them. r:=a.
380 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
381 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
383 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
384 In case of overflow (q* >= beta) set q* := beta-1.
385 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
386 and c3 := b[n-2] * q*.
387 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
388 occurred. Furthermore 0 <= c3 < beta^2.
389 If there was overflow and
390 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
391 the next test can be skipped.}
392 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
393 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
395 Put r := r - b * q* * beta^j. In detail:
396 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
397 hence: u:=0, for i:=0 to n-1 do
399 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
400 u:=u div beta (+ 1, if carry in subtraction)
402 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
404 the carry u does not overflow.}
405 If a negative carry occurs, put q* := q* - 1
406 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
408 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
409 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
411 The room for q[j] can be allocated at the memory location of r[n+j].
412 Finally, round-to-even:
413 Shift r left by 1 bit.
414 If r > b or if r = b and q[0] is odd, q := q+1.
416 const mp_limb_t *a_ptr = a.limbs;
417 size_t a_len = a.nlimbs;
418 const mp_limb_t *b_ptr = b.limbs;
419 size_t b_len = b.nlimbs;
421 mp_limb_t *tmp_roomptr = NULL;
427 /* Allocate room for a_len+2 digits.
428 (Need a_len+1 digits for the real division and 1 more digit for the
429 final rounding of q.) */
430 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
435 while (a_len > 0 && a_ptr[a_len - 1] == 0)
442 /* Division by zero. */
444 if (b_ptr[b_len - 1] == 0)
450 /* Here m = a_len >= 0 and n = b_len > 0. */
454 /* m<n: trivial case. q=0, r := copy of a. */
457 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
458 q_ptr = roomptr + a_len;
463 /* n=1: single precision division.
464 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
468 mp_limb_t den = b_ptr[0];
469 mp_limb_t remainder = 0;
470 const mp_limb_t *sourceptr = a_ptr + a_len;
471 mp_limb_t *destptr = q_ptr + a_len;
473 for (count = a_len; count > 0; count--)
476 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
477 *--destptr = num / den;
478 remainder = num % den;
480 /* Normalise and store r. */
483 r_ptr[0] = remainder;
490 if (q_ptr[q_len - 1] == 0)
496 /* n>1: multiple precision division.
497 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
498 beta^(m-n-1) <= a/b < beta^(m-n+1). */
502 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
530 /* 0 <= s < GMP_LIMB_BITS.
531 Copy b, shifting it left by s bits. */
534 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
535 if (tmp_roomptr == NULL)
541 const mp_limb_t *sourceptr = b_ptr;
542 mp_limb_t *destptr = tmp_roomptr;
543 mp_twolimb_t accu = 0;
545 for (count = b_len; count > 0; count--)
547 accu += (mp_twolimb_t) *sourceptr++ << s;
548 *destptr++ = (mp_limb_t) accu;
549 accu = accu >> GMP_LIMB_BITS;
551 /* accu must be zero, since that was how s was determined. */
557 /* Copy a, shifting it left by s bits, yields r.
559 At the beginning: r = roomptr[0..a_len],
560 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
564 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
569 const mp_limb_t *sourceptr = a_ptr;
570 mp_limb_t *destptr = r_ptr;
571 mp_twolimb_t accu = 0;
573 for (count = a_len; count > 0; count--)
575 accu += (mp_twolimb_t) *sourceptr++ << s;
576 *destptr++ = (mp_limb_t) accu;
577 accu = accu >> GMP_LIMB_BITS;
579 *destptr++ = (mp_limb_t) accu;
581 q_ptr = roomptr + b_len;
582 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
584 size_t j = a_len - b_len; /* m-n */
585 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
586 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
587 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
588 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
589 /* Division loop, traversed m-n+1 times.
590 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
595 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
597 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
599 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
600 | r_ptr[j + b_len - 1];
601 q_star = num / b_msd;
606 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
607 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
608 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
609 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
610 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
612 If yes, jump directly to the subtraction loop.
613 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
614 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
615 if (r_ptr[j + b_len] > b_msd
616 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
617 /* r[j+n] >= b[n-1]+1 or
618 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
623 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
625 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
626 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
627 mp_twolimb_t c3 = /* b[n-2] * q* */
628 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
629 /* While c2 < c3, increase c2 and decrease c3.
630 Consider c3-c2. While it is > 0, decrease it by
631 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
632 this can happen only twice. */
635 q_star = q_star - 1; /* q* := q* - 1 */
636 if (c3 - c2 > b_msdd)
637 q_star = q_star - 1; /* q* := q* - 1 */
643 /* Subtract r := r - b * q* * beta^j. */
646 const mp_limb_t *sourceptr = b_ptr;
647 mp_limb_t *destptr = r_ptr + j;
648 mp_twolimb_t carry = 0;
650 for (count = b_len; count > 0; count--)
652 /* Here 0 <= carry <= q*. */
655 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
656 + (mp_limb_t) ~(*destptr);
657 /* Here 0 <= carry <= beta*q* + beta-1. */
658 *destptr++ = ~(mp_limb_t) carry;
659 carry = carry >> GMP_LIMB_BITS; /* <= q* */
661 cr = (mp_limb_t) carry;
663 /* Subtract cr from r_ptr[j + b_len], then forget about
665 if (cr > r_ptr[j + b_len])
667 /* Subtraction gave a carry. */
668 q_star = q_star - 1; /* q* := q* - 1 */
671 const mp_limb_t *sourceptr = b_ptr;
672 mp_limb_t *destptr = r_ptr + j;
675 for (count = b_len; count > 0; count--)
677 mp_limb_t source1 = *sourceptr++;
678 mp_limb_t source2 = *destptr;
679 *destptr++ = source1 + source2 + carry;
682 ? source1 >= (mp_limb_t) ~source2
683 : source1 > (mp_limb_t) ~source2);
686 /* Forget about the carry and about r[j+n]. */
689 /* q* is determined. Store it as q[j]. */
698 if (q_ptr[q_len - 1] == 0)
700 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
701 b is shifted left by s bits. */
702 /* Shift r right by s bits. */
705 mp_limb_t ptr = r_ptr + r_len;
706 mp_twolimb_t accu = 0;
708 for (count = r_len; count > 0; count--)
710 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
711 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
712 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
717 while (r_len > 0 && r_ptr[r_len - 1] == 0)
720 /* Compare r << 1 with b. */
728 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
729 | (i < r_len ? r_ptr[i] << 1 : 0);
730 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
740 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
745 for (i = 0; i < q_len; i++)
746 if (++(q_ptr[i]) != 0)
751 if (tmp_roomptr != NULL)
758 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
760 Destroys the contents of a.
761 Return the allocated memory - containing the decimal digits in low-to-high
762 order, terminated with a NUL character - in case of success, NULL in case
763 of memory allocation failure. */
765 convert_to_decimal (mpn_t a, size_t extra_zeroes)
767 mp_limb_t *a_ptr = a.limbs;
768 size_t a_len = a.nlimbs;
769 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
770 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
771 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
775 for (; extra_zeroes > 0; extra_zeroes--)
779 /* Divide a by 10^9, in-place. */
780 mp_limb_t remainder = 0;
781 mp_limb_t *ptr = a_ptr + a_len;
783 for (count = a_len; count > 0; count--)
786 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
787 *ptr = num / 1000000000;
788 remainder = num % 1000000000;
790 /* Store the remainder as 9 decimal digits. */
791 for (count = 9; count > 0; count--)
793 *d_ptr++ = '0' + (remainder % 10);
794 remainder = remainder / 10;
797 if (a_ptr[a_len - 1] == 0)
800 /* Remove leading zeroes. */
801 while (d_ptr > c_ptr && d_ptr[-1] == '0')
803 /* But keep at least one zero. */
806 /* Terminate the string. */
812 # if NEED_PRINTF_LONG_DOUBLE
814 /* Assuming x is finite and >= 0:
815 write x as x = 2^e * m, where m is a bignum.
816 Return the allocated memory in case of success, NULL in case of memory
817 allocation failure. */
819 decode_long_double (long double x, int *ep, mpn_t *mp)
826 /* Allocate memory for result. */
827 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
828 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
831 /* Split into exponential part and mantissa. */
832 y = frexpl (x, &exp);
833 if (!(y >= 0.0L && y < 1.0L))
835 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
836 latter is an integer. */
837 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
838 I'm not sure whether it's safe to cast a 'long double' value between
839 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
840 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
842 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
843 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
846 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
849 if (!(y >= 0.0L && y < 1.0L))
851 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
854 if (!(y >= 0.0L && y < 1.0L))
856 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
861 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
864 if (!(y >= 0.0L && y < 1.0L))
866 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
870 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
873 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
876 if (!(y >= 0.0L && y < 1.0L))
878 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
881 if (!(y >= 0.0L && y < 1.0L))
883 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
885 #if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
891 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
894 *ep = exp - LDBL_MANT_BIT;
900 # if NEED_PRINTF_DOUBLE
902 /* Assuming x is finite and >= 0:
903 write x as x = 2^e * m, where m is a bignum.
904 Return the allocated memory in case of success, NULL in case of memory
905 allocation failure. */
907 decode_double (double x, int *ep, mpn_t *mp)
914 /* Allocate memory for result. */
915 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
916 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
919 /* Split into exponential part and mantissa. */
921 if (!(y >= 0.0 && y < 1.0))
923 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
924 latter is an integer. */
925 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
926 I'm not sure whether it's safe to cast a 'double' value between
927 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
928 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
930 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
931 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
934 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
937 if (!(y >= 0.0 && y < 1.0))
939 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
942 if (!(y >= 0.0 && y < 1.0))
944 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
949 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
952 if (!(y >= 0.0 && y < 1.0))
954 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
958 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
961 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
964 if (!(y >= 0.0 && y < 1.0))
966 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
969 if (!(y >= 0.0 && y < 1.0))
971 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
976 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
979 *ep = exp - DBL_MANT_BIT;
985 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
986 Returns the decimal representation of round (x * 10^n).
987 Return the allocated memory - containing the decimal digits in low-to-high
988 order, terminated with a NUL character - in case of success, NULL in case
989 of memory allocation failure. */
991 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
999 unsigned int s_limbs;
1000 unsigned int s_bits;
1008 /* x = 2^e * m, hence
1009 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1010 = round (2^s * 5^n * m). */
1013 /* Factor out a common power of 10 if possible. */
1016 extra_zeroes = (s < n ? s : n);
1020 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1021 Before converting to decimal, we need to compute
1022 z = round (2^s * 5^n * m). */
1023 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1024 sign. 2.322 is slightly larger than log(5)/log(2). */
1025 abs_n = (n >= 0 ? n : -n);
1026 abs_s = (s >= 0 ? s : -s);
1027 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1028 + abs_s / GMP_LIMB_BITS + 1)
1029 * sizeof (mp_limb_t));
1030 if (pow5_ptr == NULL)
1035 /* Initialize with 1. */
1038 /* Multiply with 5^|n|. */
1041 static mp_limb_t const small_pow5[13 + 1] =
1043 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1044 48828125, 244140625, 1220703125
1047 for (n13 = 0; n13 <= abs_n; n13 += 13)
1049 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1051 mp_twolimb_t carry = 0;
1052 for (j = 0; j < pow5_len; j++)
1054 mp_limb_t digit2 = pow5_ptr[j];
1055 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1056 pow5_ptr[j] = (mp_limb_t) carry;
1057 carry = carry >> GMP_LIMB_BITS;
1060 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1063 s_limbs = abs_s / GMP_LIMB_BITS;
1064 s_bits = abs_s % GMP_LIMB_BITS;
1065 if (n >= 0 ? s >= 0 : s <= 0)
1067 /* Multiply with 2^|s|. */
1070 mp_limb_t *ptr = pow5_ptr;
1071 mp_twolimb_t accu = 0;
1073 for (count = pow5_len; count > 0; count--)
1075 accu += (mp_twolimb_t) *ptr << s_bits;
1076 *ptr++ = (mp_limb_t) accu;
1077 accu = accu >> GMP_LIMB_BITS;
1081 *ptr = (mp_limb_t) accu;
1088 for (count = pow5_len; count > 0;)
1091 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1093 for (count = s_limbs; count > 0;)
1096 pow5_ptr[count] = 0;
1098 pow5_len += s_limbs;
1100 pow5.limbs = pow5_ptr;
1101 pow5.nlimbs = pow5_len;
1104 /* Multiply m with pow5. No division needed. */
1105 z_memory = multiply (m, pow5, &z);
1109 /* Divide m by pow5 and round. */
1110 z_memory = divide (m, pow5, &z);
1115 pow5.limbs = pow5_ptr;
1116 pow5.nlimbs = pow5_len;
1120 Multiply m with pow5, then divide by 2^|s|. */
1124 tmp_memory = multiply (m, pow5, &numerator);
1125 if (tmp_memory == NULL)
1131 /* Construct 2^|s|. */
1133 mp_limb_t *ptr = pow5_ptr + pow5_len;
1135 for (i = 0; i < s_limbs; i++)
1137 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1138 denominator.limbs = ptr;
1139 denominator.nlimbs = s_limbs + 1;
1141 z_memory = divide (numerator, denominator, &z);
1147 Multiply m with 2^s, then divide by pow5. */
1150 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1151 * sizeof (mp_limb_t));
1152 if (num_ptr == NULL)
1159 mp_limb_t *destptr = num_ptr;
1162 for (i = 0; i < s_limbs; i++)
1167 const mp_limb_t *sourceptr = m.limbs;
1168 mp_twolimb_t accu = 0;
1170 for (count = m.nlimbs; count > 0; count--)
1172 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1173 *destptr++ = (mp_limb_t) accu;
1174 accu = accu >> GMP_LIMB_BITS;
1177 *destptr++ = (mp_limb_t) accu;
1181 const mp_limb_t *sourceptr = m.limbs;
1183 for (count = m.nlimbs; count > 0; count--)
1184 *destptr++ = *sourceptr++;
1186 numerator.limbs = num_ptr;
1187 numerator.nlimbs = destptr - num_ptr;
1189 z_memory = divide (numerator, pow5, &z);
1196 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1198 if (z_memory == NULL)
1200 digits = convert_to_decimal (z, extra_zeroes);
1205 # if NEED_PRINTF_LONG_DOUBLE
1207 /* Assuming x is finite and >= 0, and n is an integer:
1208 Returns the decimal representation of round (x * 10^n).
1209 Return the allocated memory - containing the decimal digits in low-to-high
1210 order, terminated with a NUL character - in case of success, NULL in case
1211 of memory allocation failure. */
1213 scale10_round_decimal_long_double (long double x, int n)
1217 void *memory = decode_long_double (x, &e, &m);
1218 return scale10_round_decimal_decoded (e, m, memory, n);
1223 # if NEED_PRINTF_DOUBLE
1225 /* Assuming x is finite and >= 0, and n is an integer:
1226 Returns the decimal representation of round (x * 10^n).
1227 Return the allocated memory - containing the decimal digits in low-to-high
1228 order, terminated with a NUL character - in case of success, NULL in case
1229 of memory allocation failure. */
1231 scale10_round_decimal_double (double x, int n)
1235 void *memory = decode_double (x, &e, &m);
1236 return scale10_round_decimal_decoded (e, m, memory, n);
1241 # if NEED_PRINTF_LONG_DOUBLE
1243 /* Assuming x is finite and > 0:
1244 Return an approximation for n with 10^n <= x < 10^(n+1).
1245 The approximation is usually the right n, but may be off by 1 sometimes. */
1247 floorlog10l (long double x)
1254 /* Split into exponential part and mantissa. */
1255 y = frexpl (x, &exp);
1256 if (!(y >= 0.0L && y < 1.0L))
1262 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1264 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1265 exp -= GMP_LIMB_BITS;
1267 if (y < (1.0L / (1 << 16)))
1269 y *= 1.0L * (1 << 16);
1272 if (y < (1.0L / (1 << 8)))
1274 y *= 1.0L * (1 << 8);
1277 if (y < (1.0L / (1 << 4)))
1279 y *= 1.0L * (1 << 4);
1282 if (y < (1.0L / (1 << 2)))
1284 y *= 1.0L * (1 << 2);
1287 if (y < (1.0L / (1 << 1)))
1289 y *= 1.0L * (1 << 1);
1293 if (!(y >= 0.5L && y < 1.0L))
1295 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1298 if (z < 0.70710678118654752444)
1300 z *= 1.4142135623730950488;
1303 if (z < 0.8408964152537145431)
1305 z *= 1.1892071150027210667;
1308 if (z < 0.91700404320467123175)
1310 z *= 1.0905077326652576592;
1313 if (z < 0.9576032806985736469)
1315 z *= 1.0442737824274138403;
1318 /* Now 0.95 <= z <= 1.01. */
1320 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1321 Four terms are enough to get an approximation with error < 10^-7. */
1322 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1323 /* Finally multiply with log(2)/log(10), yields an approximation for
1325 l *= 0.30102999566398119523;
1326 /* Round down to the next integer. */
1327 return (int) l + (l < 0 ? -1 : 0);
1332 # if NEED_PRINTF_DOUBLE
1334 /* Assuming x is finite and > 0:
1335 Return an approximation for n with 10^n <= x < 10^(n+1).
1336 The approximation is usually the right n, but may be off by 1 sometimes. */
1338 floorlog10 (double x)
1345 /* Split into exponential part and mantissa. */
1346 y = frexp (x, &exp);
1347 if (!(y >= 0.0 && y < 1.0))
1353 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1355 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1356 exp -= GMP_LIMB_BITS;
1358 if (y < (1.0 / (1 << 16)))
1360 y *= 1.0 * (1 << 16);
1363 if (y < (1.0 / (1 << 8)))
1365 y *= 1.0 * (1 << 8);
1368 if (y < (1.0 / (1 << 4)))
1370 y *= 1.0 * (1 << 4);
1373 if (y < (1.0 / (1 << 2)))
1375 y *= 1.0 * (1 << 2);
1378 if (y < (1.0 / (1 << 1)))
1380 y *= 1.0 * (1 << 1);
1384 if (!(y >= 0.5 && y < 1.0))
1386 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1389 if (z < 0.70710678118654752444)
1391 z *= 1.4142135623730950488;
1394 if (z < 0.8408964152537145431)
1396 z *= 1.1892071150027210667;
1399 if (z < 0.91700404320467123175)
1401 z *= 1.0905077326652576592;
1404 if (z < 0.9576032806985736469)
1406 z *= 1.0442737824274138403;
1409 /* Now 0.95 <= z <= 1.01. */
1411 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1412 Four terms are enough to get an approximation with error < 10^-7. */
1413 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1414 /* Finally multiply with log(2)/log(10), yields an approximation for
1416 l *= 0.30102999566398119523;
1417 /* Round down to the next integer. */
1418 return (int) l + (l < 0 ? -1 : 0);
1423 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1424 a single '1' digit. */
1426 is_borderline (const char *digits, size_t precision)
1428 for (; precision > 0; precision--, digits++)
1434 return *digits == '\0';
1440 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1441 const FCHAR_T *format, va_list args)
1446 if (PRINTF_PARSE (format, &d, &a) < 0)
1447 /* errno is already set. */
1455 if (PRINTF_FETCHARGS (args, &a) < 0)
1463 size_t buf_neededlength;
1465 TCHAR_T *buf_malloced;
1469 /* Output string accumulator. */
1474 /* Allocate a small buffer that will hold a directive passed to
1475 sprintf or snprintf. */
1477 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1479 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1481 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1482 buf_malloced = NULL;
1487 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1488 if (size_overflow_p (buf_memsize))
1489 goto out_of_memory_1;
1490 buf = (TCHAR_T *) malloc (buf_memsize);
1492 goto out_of_memory_1;
1496 if (resultbuf != NULL)
1499 allocated = *lengthp;
1508 result is either == resultbuf or == NULL or malloc-allocated.
1509 If length > 0, then result != NULL. */
1511 /* Ensures that allocated >= needed. Aborts through a jump to
1512 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1513 #define ENSURE_ALLOCATION(needed) \
1514 if ((needed) > allocated) \
1516 size_t memory_size; \
1519 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1520 if ((needed) > allocated) \
1521 allocated = (needed); \
1522 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1523 if (size_overflow_p (memory_size)) \
1524 goto out_of_memory; \
1525 if (result == resultbuf || result == NULL) \
1526 memory = (DCHAR_T *) malloc (memory_size); \
1528 memory = (DCHAR_T *) realloc (result, memory_size); \
1529 if (memory == NULL) \
1530 goto out_of_memory; \
1531 if (result == resultbuf && length > 0) \
1532 DCHAR_CPY (memory, result, length); \
1536 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1538 if (cp != dp->dir_start)
1540 size_t n = dp->dir_start - cp;
1541 size_t augmented_length = xsum (length, n);
1543 ENSURE_ALLOCATION (augmented_length);
1544 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1545 need that the format string contains only ASCII characters
1546 if FCHAR_T and DCHAR_T are not the same type. */
1547 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1549 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1550 length = augmented_length;
1555 result[length++] = (unsigned char) *cp++;
1562 /* Execute a single directive. */
1563 if (dp->conversion == '%')
1565 size_t augmented_length;
1567 if (!(dp->arg_index == ARG_NONE))
1569 augmented_length = xsum (length, 1);
1570 ENSURE_ALLOCATION (augmented_length);
1571 result[length] = '%';
1572 length = augmented_length;
1576 if (!(dp->arg_index != ARG_NONE))
1579 if (dp->conversion == 'n')
1581 switch (a.arg[dp->arg_index].type)
1583 case TYPE_COUNT_SCHAR_POINTER:
1584 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1586 case TYPE_COUNT_SHORT_POINTER:
1587 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1589 case TYPE_COUNT_INT_POINTER:
1590 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1592 case TYPE_COUNT_LONGINT_POINTER:
1593 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1595 #if HAVE_LONG_LONG_INT
1596 case TYPE_COUNT_LONGLONGINT_POINTER:
1597 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1605 /* The unistdio extensions. */
1606 else if (dp->conversion == 'U')
1608 arg_type type = a.arg[dp->arg_index].type;
1609 int flags = dp->flags;
1617 if (dp->width_start != dp->width_end)
1619 if (dp->width_arg_index != ARG_NONE)
1623 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1625 arg = a.arg[dp->width_arg_index].a.a_int;
1628 /* "A negative field width is taken as a '-' flag
1629 followed by a positive field width." */
1631 width = (unsigned int) (-arg);
1638 const FCHAR_T *digitp = dp->width_start;
1641 width = xsum (xtimes (width, 10), *digitp++ - '0');
1642 while (digitp != dp->width_end);
1649 if (dp->precision_start != dp->precision_end)
1651 if (dp->precision_arg_index != ARG_NONE)
1655 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1657 arg = a.arg[dp->precision_arg_index].a.a_int;
1658 /* "A negative precision is taken as if the precision
1668 const FCHAR_T *digitp = dp->precision_start + 1;
1671 while (digitp != dp->precision_end)
1672 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1679 case TYPE_U8_STRING:
1681 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1682 const uint8_t *arg_end;
1687 /* Use only PRECISION characters, from the left. */
1690 for (; precision > 0; precision--)
1692 int count = u8_strmblen (arg_end);
1697 if (!(result == resultbuf || result == NULL))
1699 if (buf_malloced != NULL)
1700 free (buf_malloced);
1711 /* Use the entire string, and count the number of
1717 int count = u8_strmblen (arg_end);
1722 if (!(result == resultbuf || result == NULL))
1724 if (buf_malloced != NULL)
1725 free (buf_malloced);
1736 /* Use the entire string. */
1737 arg_end = arg + u8_strlen (arg);
1738 /* The number of characters doesn't matter. */
1742 if (has_width && width > characters
1743 && !(dp->flags & FLAG_LEFT))
1745 size_t n = width - characters;
1746 ENSURE_ALLOCATION (xsum (length, n));
1747 DCHAR_SET (result + length, ' ', n);
1751 # if DCHAR_IS_UINT8_T
1753 size_t n = arg_end - arg;
1754 ENSURE_ALLOCATION (xsum (length, n));
1755 DCHAR_CPY (result + length, arg, n);
1760 DCHAR_T *converted = result + length;
1761 size_t converted_len = allocated - length;
1763 /* Convert from UTF-8 to locale encoding. */
1764 if (u8_conv_to_encoding (locale_charset (),
1765 iconveh_question_mark,
1766 arg, arg_end - arg, NULL,
1767 &converted, &converted_len)
1770 /* Convert from UTF-8 to UTF-16/UTF-32. */
1772 U8_TO_DCHAR (arg, arg_end - arg,
1773 converted, &converted_len);
1774 if (converted == NULL)
1777 int saved_errno = errno;
1778 if (!(result == resultbuf || result == NULL))
1780 if (buf_malloced != NULL)
1781 free (buf_malloced);
1783 errno = saved_errno;
1786 if (converted != result + length)
1788 ENSURE_ALLOCATION (xsum (length, converted_len));
1789 DCHAR_CPY (result + length, converted, converted_len);
1792 length += converted_len;
1796 if (has_width && width > characters
1797 && (dp->flags & FLAG_LEFT))
1799 size_t n = width - characters;
1800 ENSURE_ALLOCATION (xsum (length, n));
1801 DCHAR_SET (result + length, ' ', n);
1807 case TYPE_U16_STRING:
1809 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1810 const uint16_t *arg_end;
1815 /* Use only PRECISION characters, from the left. */
1818 for (; precision > 0; precision--)
1820 int count = u16_strmblen (arg_end);
1825 if (!(result == resultbuf || result == NULL))
1827 if (buf_malloced != NULL)
1828 free (buf_malloced);
1839 /* Use the entire string, and count the number of
1845 int count = u16_strmblen (arg_end);
1850 if (!(result == resultbuf || result == NULL))
1852 if (buf_malloced != NULL)
1853 free (buf_malloced);
1864 /* Use the entire string. */
1865 arg_end = arg + u16_strlen (arg);
1866 /* The number of characters doesn't matter. */
1870 if (has_width && width > characters
1871 && !(dp->flags & FLAG_LEFT))
1873 size_t n = width - characters;
1874 ENSURE_ALLOCATION (xsum (length, n));
1875 DCHAR_SET (result + length, ' ', n);
1879 # if DCHAR_IS_UINT16_T
1881 size_t n = arg_end - arg;
1882 ENSURE_ALLOCATION (xsum (length, n));
1883 DCHAR_CPY (result + length, arg, n);
1888 DCHAR_T *converted = result + length;
1889 size_t converted_len = allocated - length;
1891 /* Convert from UTF-16 to locale encoding. */
1892 if (u16_conv_to_encoding (locale_charset (),
1893 iconveh_question_mark,
1894 arg, arg_end - arg, NULL,
1895 &converted, &converted_len)
1898 /* Convert from UTF-16 to UTF-8/UTF-32. */
1900 U16_TO_DCHAR (arg, arg_end - arg,
1901 converted, &converted_len);
1902 if (converted == NULL)
1905 int saved_errno = errno;
1906 if (!(result == resultbuf || result == NULL))
1908 if (buf_malloced != NULL)
1909 free (buf_malloced);
1911 errno = saved_errno;
1914 if (converted != result + length)
1916 ENSURE_ALLOCATION (xsum (length, converted_len));
1917 DCHAR_CPY (result + length, converted, converted_len);
1920 length += converted_len;
1924 if (has_width && width > characters
1925 && (dp->flags & FLAG_LEFT))
1927 size_t n = width - characters;
1928 ENSURE_ALLOCATION (xsum (length, n));
1929 DCHAR_SET (result + length, ' ', n);
1935 case TYPE_U32_STRING:
1937 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1938 const uint32_t *arg_end;
1943 /* Use only PRECISION characters, from the left. */
1946 for (; precision > 0; precision--)
1948 int count = u32_strmblen (arg_end);
1953 if (!(result == resultbuf || result == NULL))
1955 if (buf_malloced != NULL)
1956 free (buf_malloced);
1967 /* Use the entire string, and count the number of
1973 int count = u32_strmblen (arg_end);
1978 if (!(result == resultbuf || result == NULL))
1980 if (buf_malloced != NULL)
1981 free (buf_malloced);
1992 /* Use the entire string. */
1993 arg_end = arg + u32_strlen (arg);
1994 /* The number of characters doesn't matter. */
1998 if (has_width && width > characters
1999 && !(dp->flags & FLAG_LEFT))
2001 size_t n = width - characters;
2002 ENSURE_ALLOCATION (xsum (length, n));
2003 DCHAR_SET (result + length, ' ', n);
2007 # if DCHAR_IS_UINT32_T
2009 size_t n = arg_end - arg;
2010 ENSURE_ALLOCATION (xsum (length, n));
2011 DCHAR_CPY (result + length, arg, n);
2016 DCHAR_T *converted = result + length;
2017 size_t converted_len = allocated - length;
2019 /* Convert from UTF-32 to locale encoding. */
2020 if (u32_conv_to_encoding (locale_charset (),
2021 iconveh_question_mark,
2022 arg, arg_end - arg, NULL,
2023 &converted, &converted_len)
2026 /* Convert from UTF-32 to UTF-8/UTF-16. */
2028 U32_TO_DCHAR (arg, arg_end - arg,
2029 converted, &converted_len);
2030 if (converted == NULL)
2033 int saved_errno = errno;
2034 if (!(result == resultbuf || result == NULL))
2036 if (buf_malloced != NULL)
2037 free (buf_malloced);
2039 errno = saved_errno;
2042 if (converted != result + length)
2044 ENSURE_ALLOCATION (xsum (length, converted_len));
2045 DCHAR_CPY (result + length, converted, converted_len);
2048 length += converted_len;
2052 if (has_width && width > characters
2053 && (dp->flags & FLAG_LEFT))
2055 size_t n = width - characters;
2056 ENSURE_ALLOCATION (xsum (length, n));
2057 DCHAR_SET (result + length, ' ', n);
2068 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2069 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2070 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2072 # if NEED_PRINTF_DOUBLE
2073 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2075 # if NEED_PRINTF_LONG_DOUBLE
2076 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2082 arg_type type = a.arg[dp->arg_index].type;
2083 int flags = dp->flags;
2089 DCHAR_T tmpbuf[700];
2096 if (dp->width_start != dp->width_end)
2098 if (dp->width_arg_index != ARG_NONE)
2102 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2104 arg = a.arg[dp->width_arg_index].a.a_int;
2107 /* "A negative field width is taken as a '-' flag
2108 followed by a positive field width." */
2110 width = (unsigned int) (-arg);
2117 const FCHAR_T *digitp = dp->width_start;
2120 width = xsum (xtimes (width, 10), *digitp++ - '0');
2121 while (digitp != dp->width_end);
2128 if (dp->precision_start != dp->precision_end)
2130 if (dp->precision_arg_index != ARG_NONE)
2134 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2136 arg = a.arg[dp->precision_arg_index].a.a_int;
2137 /* "A negative precision is taken as if the precision
2147 const FCHAR_T *digitp = dp->precision_start + 1;
2150 while (digitp != dp->precision_end)
2151 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2156 /* Allocate a temporary buffer of sufficient size. */
2157 if (type == TYPE_LONGDOUBLE)
2159 (unsigned int) ((LDBL_DIG + 1)
2160 * 0.831 /* decimal -> hexadecimal */
2162 + 1; /* turn floor into ceil */
2165 (unsigned int) ((DBL_DIG + 1)
2166 * 0.831 /* decimal -> hexadecimal */
2168 + 1; /* turn floor into ceil */
2169 if (tmp_length < precision)
2170 tmp_length = precision;
2171 /* Account for sign, decimal point etc. */
2172 tmp_length = xsum (tmp_length, 12);
2174 if (tmp_length < width)
2177 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2179 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2183 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2185 if (size_overflow_p (tmp_memsize))
2186 /* Overflow, would lead to out of memory. */
2188 tmp = (DCHAR_T *) malloc (tmp_memsize);
2190 /* Out of memory. */
2196 if (type == TYPE_LONGDOUBLE)
2198 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2199 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2203 if (dp->conversion == 'A')
2205 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2209 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2215 DECL_LONG_DOUBLE_ROUNDING
2217 BEGIN_LONG_DOUBLE_ROUNDING ();
2219 if (signbit (arg)) /* arg < 0.0L or negative zero */
2227 else if (flags & FLAG_SHOWSIGN)
2229 else if (flags & FLAG_SPACE)
2232 if (arg > 0.0L && arg + arg == arg)
2234 if (dp->conversion == 'A')
2236 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2240 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2246 long double mantissa;
2249 mantissa = printf_frexpl (arg, &exponent);
2257 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2259 /* Round the mantissa. */
2260 long double tail = mantissa;
2263 for (q = precision; ; q--)
2265 int digit = (int) tail;
2269 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2278 for (q = precision; q > 0; q--)
2284 *p++ = dp->conversion - 'A' + 'X';
2289 digit = (int) mantissa;
2292 if ((flags & FLAG_ALT)
2293 || mantissa > 0.0L || precision > 0)
2295 *p++ = decimal_point_char ();
2296 /* This loop terminates because we assume
2297 that FLT_RADIX is a power of 2. */
2298 while (mantissa > 0.0L)
2301 digit = (int) mantissa;
2306 : dp->conversion - 10);
2310 while (precision > 0)
2317 *p++ = dp->conversion - 'A' + 'P';
2318 # if WIDE_CHAR_VERSION
2320 static const wchar_t decimal_format[] =
2321 { '%', '+', 'd', '\0' };
2322 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2327 if (sizeof (DCHAR_T) == 1)
2329 sprintf ((char *) p, "%+d", exponent);
2337 sprintf (expbuf, "%+d", exponent);
2338 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2344 END_LONG_DOUBLE_ROUNDING ();
2352 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2353 double arg = a.arg[dp->arg_index].a.a_double;
2357 if (dp->conversion == 'A')
2359 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2363 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2370 if (signbit (arg)) /* arg < 0.0 or negative zero */
2378 else if (flags & FLAG_SHOWSIGN)
2380 else if (flags & FLAG_SPACE)
2383 if (arg > 0.0 && arg + arg == arg)
2385 if (dp->conversion == 'A')
2387 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2391 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2400 mantissa = printf_frexp (arg, &exponent);
2408 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2410 /* Round the mantissa. */
2411 double tail = mantissa;
2414 for (q = precision; ; q--)
2416 int digit = (int) tail;
2420 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2429 for (q = precision; q > 0; q--)
2435 *p++ = dp->conversion - 'A' + 'X';
2440 digit = (int) mantissa;
2443 if ((flags & FLAG_ALT)
2444 || mantissa > 0.0 || precision > 0)
2446 *p++ = decimal_point_char ();
2447 /* This loop terminates because we assume
2448 that FLT_RADIX is a power of 2. */
2449 while (mantissa > 0.0)
2452 digit = (int) mantissa;
2457 : dp->conversion - 10);
2461 while (precision > 0)
2468 *p++ = dp->conversion - 'A' + 'P';
2469 # if WIDE_CHAR_VERSION
2471 static const wchar_t decimal_format[] =
2472 { '%', '+', 'd', '\0' };
2473 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2478 if (sizeof (DCHAR_T) == 1)
2480 sprintf ((char *) p, "%+d", exponent);
2488 sprintf (expbuf, "%+d", exponent);
2489 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2499 /* The generated string now extends from tmp to p, with the
2500 zero padding insertion point being at pad_ptr. */
2501 if (has_width && p - tmp < width)
2503 size_t pad = width - (p - tmp);
2504 DCHAR_T *end = p + pad;
2506 if (flags & FLAG_LEFT)
2508 /* Pad with spaces on the right. */
2509 for (; pad > 0; pad--)
2512 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2514 /* Pad with zeroes. */
2519 for (; pad > 0; pad--)
2524 /* Pad with spaces on the left. */
2529 for (; pad > 0; pad--)
2537 size_t count = p - tmp;
2539 if (count >= tmp_length)
2540 /* tmp_length was incorrectly calculated - fix the
2544 /* Make room for the result. */
2545 if (count >= allocated - length)
2547 size_t n = xsum (length, count);
2549 ENSURE_ALLOCATION (n);
2552 /* Append the result. */
2553 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2560 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2561 else if ((dp->conversion == 'f' || dp->conversion == 'F'
2562 || dp->conversion == 'e' || dp->conversion == 'E'
2563 || dp->conversion == 'g' || dp->conversion == 'G'
2564 || dp->conversion == 'a' || dp->conversion == 'A')
2566 # if NEED_PRINTF_DOUBLE
2567 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2568 # elif NEED_PRINTF_INFINITE_DOUBLE
2569 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2570 /* The systems (mingw) which produce wrong output
2571 for Inf, -Inf, and NaN also do so for -0.0.
2572 Therefore we treat this case here as well. */
2573 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2575 # if NEED_PRINTF_LONG_DOUBLE
2576 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2577 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2578 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2579 /* Some systems produce wrong output for Inf,
2581 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
2585 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2586 arg_type type = a.arg[dp->arg_index].type;
2588 int flags = dp->flags;
2594 DCHAR_T tmpbuf[700];
2601 if (dp->width_start != dp->width_end)
2603 if (dp->width_arg_index != ARG_NONE)
2607 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2609 arg = a.arg[dp->width_arg_index].a.a_int;
2612 /* "A negative field width is taken as a '-' flag
2613 followed by a positive field width." */
2615 width = (unsigned int) (-arg);
2622 const FCHAR_T *digitp = dp->width_start;
2625 width = xsum (xtimes (width, 10), *digitp++ - '0');
2626 while (digitp != dp->width_end);
2633 if (dp->precision_start != dp->precision_end)
2635 if (dp->precision_arg_index != ARG_NONE)
2639 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2641 arg = a.arg[dp->precision_arg_index].a.a_int;
2642 /* "A negative precision is taken as if the precision
2652 const FCHAR_T *digitp = dp->precision_start + 1;
2655 while (digitp != dp->precision_end)
2656 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2661 /* POSIX specifies the default precision to be 6 for %f, %F,
2662 %e, %E, but not for %g, %G. Implementations appear to use
2663 the same default precision also for %g, %G. */
2667 /* Allocate a temporary buffer of sufficient size. */
2668 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2669 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
2670 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2671 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2672 # elif NEED_PRINTF_LONG_DOUBLE
2673 tmp_length = LDBL_DIG + 1;
2674 # elif NEED_PRINTF_DOUBLE
2675 tmp_length = DBL_DIG + 1;
2679 if (tmp_length < precision)
2680 tmp_length = precision;
2681 # if NEED_PRINTF_LONG_DOUBLE
2682 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2683 if (type == TYPE_LONGDOUBLE)
2685 if (dp->conversion == 'f' || dp->conversion == 'F')
2687 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2688 if (!(isnanl (arg) || arg + arg == arg))
2690 /* arg is finite and nonzero. */
2691 int exponent = floorlog10l (arg < 0 ? -arg : arg);
2692 if (exponent >= 0 && tmp_length < exponent + precision)
2693 tmp_length = exponent + precision;
2697 # if NEED_PRINTF_DOUBLE
2698 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2699 if (type == TYPE_DOUBLE)
2701 if (dp->conversion == 'f' || dp->conversion == 'F')
2703 double arg = a.arg[dp->arg_index].a.a_double;
2704 if (!(isnand (arg) || arg + arg == arg))
2706 /* arg is finite and nonzero. */
2707 int exponent = floorlog10 (arg < 0 ? -arg : arg);
2708 if (exponent >= 0 && tmp_length < exponent + precision)
2709 tmp_length = exponent + precision;
2713 /* Account for sign, decimal point etc. */
2714 tmp_length = xsum (tmp_length, 12);
2716 if (tmp_length < width)
2719 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2721 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2725 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2727 if (size_overflow_p (tmp_memsize))
2728 /* Overflow, would lead to out of memory. */
2730 tmp = (DCHAR_T *) malloc (tmp_memsize);
2732 /* Out of memory. */
2739 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2740 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2741 if (type == TYPE_LONGDOUBLE)
2744 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2748 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2750 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2754 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2760 DECL_LONG_DOUBLE_ROUNDING
2762 BEGIN_LONG_DOUBLE_ROUNDING ();
2764 if (signbit (arg)) /* arg < 0.0L or negative zero */
2772 else if (flags & FLAG_SHOWSIGN)
2774 else if (flags & FLAG_SPACE)
2777 if (arg > 0.0L && arg + arg == arg)
2779 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2781 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2785 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2790 # if NEED_PRINTF_LONG_DOUBLE
2793 if (dp->conversion == 'f' || dp->conversion == 'F')
2799 scale10_round_decimal_long_double (arg, precision);
2802 END_LONG_DOUBLE_ROUNDING ();
2805 ndigits = strlen (digits);
2807 if (ndigits > precision)
2811 *p++ = digits[ndigits];
2813 while (ndigits > precision);
2816 /* Here ndigits <= precision. */
2817 if ((flags & FLAG_ALT) || precision > 0)
2819 *p++ = decimal_point_char ();
2820 for (; precision > ndigits; precision--)
2825 *p++ = digits[ndigits];
2831 else if (dp->conversion == 'e' || dp->conversion == 'E')
2839 if ((flags & FLAG_ALT) || precision > 0)
2841 *p++ = decimal_point_char ();
2842 for (; precision > 0; precision--)
2853 exponent = floorlog10l (arg);
2858 scale10_round_decimal_long_double (arg,
2859 (int)precision - exponent);
2862 END_LONG_DOUBLE_ROUNDING ();
2865 ndigits = strlen (digits);
2867 if (ndigits == precision + 1)
2869 if (ndigits < precision
2870 || ndigits > precision + 2)
2871 /* The exponent was not guessed
2872 precisely enough. */
2875 /* None of two values of exponent is
2876 the right one. Prevent an endless
2880 if (ndigits == precision)
2886 /* Here ndigits = precision+1. */
2887 if (is_borderline (digits, precision))
2889 /* Maybe the exponent guess was too high
2890 and a smaller exponent can be reached
2891 by turning a 10...0 into 9...9x. */
2893 scale10_round_decimal_long_double (arg,
2894 (int)precision - exponent + 1);
2895 if (digits2 == NULL)
2898 END_LONG_DOUBLE_ROUNDING ();
2901 if (strlen (digits2) == precision + 1)
2910 /* Here ndigits = precision+1. */
2912 *p++ = digits[--ndigits];
2913 if ((flags & FLAG_ALT) || precision > 0)
2915 *p++ = decimal_point_char ();
2919 *p++ = digits[ndigits];
2926 *p++ = dp->conversion; /* 'e' or 'E' */
2927 # if WIDE_CHAR_VERSION
2929 static const wchar_t decimal_format[] =
2930 { '%', '+', '.', '2', 'd', '\0' };
2931 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2936 if (sizeof (DCHAR_T) == 1)
2938 sprintf ((char *) p, "%+.2d", exponent);
2946 sprintf (expbuf, "%+.2d", exponent);
2947 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2952 else if (dp->conversion == 'g' || dp->conversion == 'G')
2956 /* precision >= 1. */
2959 /* The exponent is 0, >= -4, < precision.
2960 Use fixed-point notation. */
2962 size_t ndigits = precision;
2963 /* Number of trailing zeroes that have to be
2966 (flags & FLAG_ALT ? 0 : precision - 1);
2970 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2972 *p++ = decimal_point_char ();
2973 while (ndigits > nzeroes)
2989 exponent = floorlog10l (arg);
2994 scale10_round_decimal_long_double (arg,
2995 (int)(precision - 1) - exponent);
2998 END_LONG_DOUBLE_ROUNDING ();
3001 ndigits = strlen (digits);
3003 if (ndigits == precision)
3005 if (ndigits < precision - 1
3006 || ndigits > precision + 1)
3007 /* The exponent was not guessed
3008 precisely enough. */
3011 /* None of two values of exponent is
3012 the right one. Prevent an endless
3016 if (ndigits < precision)
3022 /* Here ndigits = precision. */
3023 if (is_borderline (digits, precision - 1))
3025 /* Maybe the exponent guess was too high
3026 and a smaller exponent can be reached
3027 by turning a 10...0 into 9...9x. */
3029 scale10_round_decimal_long_double (arg,
3030 (int)(precision - 1) - exponent + 1);
3031 if (digits2 == NULL)
3034 END_LONG_DOUBLE_ROUNDING ();
3037 if (strlen (digits2) == precision)
3046 /* Here ndigits = precision. */
3048 /* Determine the number of trailing zeroes
3049 that have to be dropped. */
3051 if ((flags & FLAG_ALT) == 0)
3052 while (nzeroes < ndigits
3053 && digits[nzeroes] == '0')
3056 /* The exponent is now determined. */
3058 && exponent < (long)precision)
3060 /* Fixed-point notation:
3061 max(exponent,0)+1 digits, then the
3062 decimal point, then the remaining
3063 digits without trailing zeroes. */
3066 size_t count = exponent + 1;
3067 /* Note: count <= precision = ndigits. */
3068 for (; count > 0; count--)
3069 *p++ = digits[--ndigits];
3070 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3072 *p++ = decimal_point_char ();
3073 while (ndigits > nzeroes)
3076 *p++ = digits[ndigits];
3082 size_t count = -exponent - 1;
3084 *p++ = decimal_point_char ();
3085 for (; count > 0; count--)
3087 while (ndigits > nzeroes)
3090 *p++ = digits[ndigits];
3096 /* Exponential notation. */
3097 *p++ = digits[--ndigits];
3098 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3100 *p++ = decimal_point_char ();
3101 while (ndigits > nzeroes)
3104 *p++ = digits[ndigits];
3107 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3108 # if WIDE_CHAR_VERSION
3110 static const wchar_t decimal_format[] =
3111 { '%', '+', '.', '2', 'd', '\0' };
3112 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3117 if (sizeof (DCHAR_T) == 1)
3119 sprintf ((char *) p, "%+.2d", exponent);
3127 sprintf (expbuf, "%+.2d", exponent);
3128 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3140 /* arg is finite. */
3145 END_LONG_DOUBLE_ROUNDING ();
3148 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3152 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3154 double arg = a.arg[dp->arg_index].a.a_double;
3158 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3160 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3164 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3171 if (signbit (arg)) /* arg < 0.0 or negative zero */
3179 else if (flags & FLAG_SHOWSIGN)
3181 else if (flags & FLAG_SPACE)
3184 if (arg > 0.0 && arg + arg == arg)
3186 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3188 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3192 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3197 # if NEED_PRINTF_DOUBLE
3200 if (dp->conversion == 'f' || dp->conversion == 'F')
3206 scale10_round_decimal_double (arg, precision);
3209 ndigits = strlen (digits);
3211 if (ndigits > precision)
3215 *p++ = digits[ndigits];
3217 while (ndigits > precision);
3220 /* Here ndigits <= precision. */
3221 if ((flags & FLAG_ALT) || precision > 0)
3223 *p++ = decimal_point_char ();
3224 for (; precision > ndigits; precision--)
3229 *p++ = digits[ndigits];
3235 else if (dp->conversion == 'e' || dp->conversion == 'E')
3243 if ((flags & FLAG_ALT) || precision > 0)
3245 *p++ = decimal_point_char ();
3246 for (; precision > 0; precision--)
3257 exponent = floorlog10 (arg);
3262 scale10_round_decimal_double (arg,
3263 (int)precision - exponent);
3266 ndigits = strlen (digits);
3268 if (ndigits == precision + 1)
3270 if (ndigits < precision
3271 || ndigits > precision + 2)
3272 /* The exponent was not guessed
3273 precisely enough. */
3276 /* None of two values of exponent is
3277 the right one. Prevent an endless
3281 if (ndigits == precision)
3287 /* Here ndigits = precision+1. */
3288 if (is_borderline (digits, precision))
3290 /* Maybe the exponent guess was too high
3291 and a smaller exponent can be reached
3292 by turning a 10...0 into 9...9x. */
3294 scale10_round_decimal_double (arg,
3295 (int)precision - exponent + 1);
3296 if (digits2 == NULL)
3301 if (strlen (digits2) == precision + 1)
3310 /* Here ndigits = precision+1. */
3312 *p++ = digits[--ndigits];
3313 if ((flags & FLAG_ALT) || precision > 0)
3315 *p++ = decimal_point_char ();
3319 *p++ = digits[ndigits];
3326 *p++ = dp->conversion; /* 'e' or 'E' */
3327 # if WIDE_CHAR_VERSION
3329 static const wchar_t decimal_format[] =
3330 /* Produce the same number of exponent digits
3331 as the native printf implementation. */
3332 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3333 { '%', '+', '.', '3', 'd', '\0' };
3335 { '%', '+', '.', '2', 'd', '\0' };
3337 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3343 static const char decimal_format[] =
3344 /* Produce the same number of exponent digits
3345 as the native printf implementation. */
3346 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3351 if (sizeof (DCHAR_T) == 1)
3353 sprintf ((char *) p, decimal_format, exponent);
3361 sprintf (expbuf, decimal_format, exponent);
3362 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3368 else if (dp->conversion == 'g' || dp->conversion == 'G')
3372 /* precision >= 1. */
3375 /* The exponent is 0, >= -4, < precision.
3376 Use fixed-point notation. */
3378 size_t ndigits = precision;
3379 /* Number of trailing zeroes that have to be
3382 (flags & FLAG_ALT ? 0 : precision - 1);
3386 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3388 *p++ = decimal_point_char ();
3389 while (ndigits > nzeroes)
3405 exponent = floorlog10 (arg);
3410 scale10_round_decimal_double (arg,
3411 (int)(precision - 1) - exponent);
3414 ndigits = strlen (digits);
3416 if (ndigits == precision)
3418 if (ndigits < precision - 1
3419 || ndigits > precision + 1)
3420 /* The exponent was not guessed
3421 precisely enough. */
3424 /* None of two values of exponent is
3425 the right one. Prevent an endless
3429 if (ndigits < precision)
3435 /* Here ndigits = precision. */
3436 if (is_borderline (digits, precision - 1))
3438 /* Maybe the exponent guess was too high
3439 and a smaller exponent can be reached
3440 by turning a 10...0 into 9...9x. */
3442 scale10_round_decimal_double (arg,
3443 (int)(precision - 1) - exponent + 1);
3444 if (digits2 == NULL)
3449 if (strlen (digits2) == precision)
3458 /* Here ndigits = precision. */
3460 /* Determine the number of trailing zeroes
3461 that have to be dropped. */
3463 if ((flags & FLAG_ALT) == 0)
3464 while (nzeroes < ndigits
3465 && digits[nzeroes] == '0')
3468 /* The exponent is now determined. */
3470 && exponent < (long)precision)
3472 /* Fixed-point notation:
3473 max(exponent,0)+1 digits, then the
3474 decimal point, then the remaining
3475 digits without trailing zeroes. */
3478 size_t count = exponent + 1;
3479 /* Note: count <= precision = ndigits. */
3480 for (; count > 0; count--)
3481 *p++ = digits[--ndigits];
3482 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3484 *p++ = decimal_point_char ();
3485 while (ndigits > nzeroes)
3488 *p++ = digits[ndigits];
3494 size_t count = -exponent - 1;
3496 *p++ = decimal_point_char ();
3497 for (; count > 0; count--)
3499 while (ndigits > nzeroes)
3502 *p++ = digits[ndigits];
3508 /* Exponential notation. */
3509 *p++ = digits[--ndigits];
3510 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3512 *p++ = decimal_point_char ();
3513 while (ndigits > nzeroes)
3516 *p++ = digits[ndigits];
3519 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3520 # if WIDE_CHAR_VERSION
3522 static const wchar_t decimal_format[] =
3523 /* Produce the same number of exponent digits
3524 as the native printf implementation. */
3525 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3526 { '%', '+', '.', '3', 'd', '\0' };
3528 { '%', '+', '.', '2', 'd', '\0' };
3530 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3536 static const char decimal_format[] =
3537 /* Produce the same number of exponent digits
3538 as the native printf implementation. */
3539 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3544 if (sizeof (DCHAR_T) == 1)
3546 sprintf ((char *) p, decimal_format, exponent);
3554 sprintf (expbuf, decimal_format, exponent);
3555 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3568 /* arg is finite. */
3574 if (dp->conversion == 'f' || dp->conversion == 'F')
3577 if ((flags & FLAG_ALT) || precision > 0)
3579 *p++ = decimal_point_char ();
3580 for (; precision > 0; precision--)
3584 else if (dp->conversion == 'e' || dp->conversion == 'E')
3587 if ((flags & FLAG_ALT) || precision > 0)
3589 *p++ = decimal_point_char ();
3590 for (; precision > 0; precision--)
3593 *p++ = dp->conversion; /* 'e' or 'E' */
3595 /* Produce the same number of exponent digits as
3596 the native printf implementation. */
3597 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3603 else if (dp->conversion == 'g' || dp->conversion == 'G')
3606 if (flags & FLAG_ALT)
3609 (precision > 0 ? precision - 1 : 0);
3610 *p++ = decimal_point_char ();
3611 for (; ndigits > 0; --ndigits)
3623 /* The generated string now extends from tmp to p, with the
3624 zero padding insertion point being at pad_ptr. */
3625 if (has_width && p - tmp < width)
3627 size_t pad = width - (p - tmp);
3628 DCHAR_T *end = p + pad;
3630 if (flags & FLAG_LEFT)
3632 /* Pad with spaces on the right. */
3633 for (; pad > 0; pad--)
3636 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3638 /* Pad with zeroes. */
3643 for (; pad > 0; pad--)
3648 /* Pad with spaces on the left. */
3653 for (; pad > 0; pad--)
3661 size_t count = p - tmp;
3663 if (count >= tmp_length)
3664 /* tmp_length was incorrectly calculated - fix the
3668 /* Make room for the result. */
3669 if (count >= allocated - length)
3671 size_t n = xsum (length, count);
3673 ENSURE_ALLOCATION (n);
3676 /* Append the result. */
3677 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3686 arg_type type = a.arg[dp->arg_index].type;
3687 int flags = dp->flags;
3688 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3692 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3696 #if NEED_PRINTF_UNBOUNDED_PRECISION
3699 # define prec_ourselves 0
3701 #if NEED_PRINTF_FLAG_LEFTADJUST
3702 # define pad_ourselves 1
3703 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3706 # define pad_ourselves 0
3709 unsigned int prefix_count;
3713 TCHAR_T tmpbuf[700];
3717 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3720 if (dp->width_start != dp->width_end)
3722 if (dp->width_arg_index != ARG_NONE)
3726 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3728 arg = a.arg[dp->width_arg_index].a.a_int;
3731 /* "A negative field width is taken as a '-' flag
3732 followed by a positive field width." */
3734 width = (unsigned int) (-arg);
3741 const FCHAR_T *digitp = dp->width_start;
3744 width = xsum (xtimes (width, 10), *digitp++ - '0');
3745 while (digitp != dp->width_end);
3751 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3754 if (dp->precision_start != dp->precision_end)
3756 if (dp->precision_arg_index != ARG_NONE)
3760 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3762 arg = a.arg[dp->precision_arg_index].a.a_int;
3763 /* "A negative precision is taken as if the precision
3773 const FCHAR_T *digitp = dp->precision_start + 1;
3776 while (digitp != dp->precision_end)
3777 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3783 /* Decide whether to handle the precision ourselves. */
3784 #if NEED_PRINTF_UNBOUNDED_PRECISION
3785 switch (dp->conversion)
3787 case 'd': case 'i': case 'u':
3789 case 'x': case 'X': case 'p':
3790 prec_ourselves = has_precision && (precision > 0);
3798 /* Decide whether to perform the padding ourselves. */
3799 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
3800 switch (dp->conversion)
3802 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
3803 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
3804 to perform the padding after this conversion. Functions
3805 with unistdio extensions perform the padding based on
3806 character count rather than element count. */
3809 # if NEED_PRINTF_FLAG_ZERO
3810 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
3816 pad_ourselves = prec_ourselves;
3822 /* Allocate a temporary buffer of sufficient size for calling
3825 switch (dp->conversion)
3828 case 'd': case 'i': case 'u':
3829 # if HAVE_LONG_LONG_INT
3830 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3832 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3833 * 0.30103 /* binary -> decimal */
3835 + 1; /* turn floor into ceil */
3838 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3840 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3841 * 0.30103 /* binary -> decimal */
3843 + 1; /* turn floor into ceil */
3846 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3847 * 0.30103 /* binary -> decimal */
3849 + 1; /* turn floor into ceil */
3850 if (tmp_length < precision)
3851 tmp_length = precision;
3852 /* Multiply by 2, as an estimate for FLAG_GROUP. */
3853 tmp_length = xsum (tmp_length, tmp_length);
3854 /* Add 1, to account for a leading sign. */
3855 tmp_length = xsum (tmp_length, 1);
3859 # if HAVE_LONG_LONG_INT
3860 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3862 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3863 * 0.333334 /* binary -> octal */
3865 + 1; /* turn floor into ceil */
3868 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3870 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3871 * 0.333334 /* binary -> octal */
3873 + 1; /* turn floor into ceil */
3876 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3877 * 0.333334 /* binary -> octal */
3879 + 1; /* turn floor into ceil */
3880 if (tmp_length < precision)
3881 tmp_length = precision;
3882 /* Add 1, to account for a leading sign. */
3883 tmp_length = xsum (tmp_length, 1);
3887 # if HAVE_LONG_LONG_INT
3888 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3890 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3891 * 0.25 /* binary -> hexadecimal */
3893 + 1; /* turn floor into ceil */
3896 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3898 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3899 * 0.25 /* binary -> hexadecimal */
3901 + 1; /* turn floor into ceil */
3904 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3905 * 0.25 /* binary -> hexadecimal */
3907 + 1; /* turn floor into ceil */
3908 if (tmp_length < precision)
3909 tmp_length = precision;
3910 /* Add 2, to account for a leading sign or alternate form. */
3911 tmp_length = xsum (tmp_length, 2);
3915 if (type == TYPE_LONGDOUBLE)
3917 (unsigned int) (LDBL_MAX_EXP
3918 * 0.30103 /* binary -> decimal */
3919 * 2 /* estimate for FLAG_GROUP */
3921 + 1 /* turn floor into ceil */
3922 + 10; /* sign, decimal point etc. */
3925 (unsigned int) (DBL_MAX_EXP
3926 * 0.30103 /* binary -> decimal */
3927 * 2 /* estimate for FLAG_GROUP */
3929 + 1 /* turn floor into ceil */
3930 + 10; /* sign, decimal point etc. */
3931 tmp_length = xsum (tmp_length, precision);
3934 case 'e': case 'E': case 'g': case 'G':
3936 12; /* sign, decimal point, exponent etc. */
3937 tmp_length = xsum (tmp_length, precision);
3941 if (type == TYPE_LONGDOUBLE)
3943 (unsigned int) (LDBL_DIG
3944 * 0.831 /* decimal -> hexadecimal */
3946 + 1; /* turn floor into ceil */
3949 (unsigned int) (DBL_DIG
3950 * 0.831 /* decimal -> hexadecimal */
3952 + 1; /* turn floor into ceil */
3953 if (tmp_length < precision)
3954 tmp_length = precision;
3955 /* Account for sign, decimal point etc. */
3956 tmp_length = xsum (tmp_length, 12);
3960 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
3961 if (type == TYPE_WIDE_CHAR)
3962 tmp_length = MB_CUR_MAX;
3970 if (type == TYPE_WIDE_STRING)
3973 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
3975 # if !WIDE_CHAR_VERSION
3976 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
3981 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
3986 (unsigned int) (sizeof (void *) * CHAR_BIT
3987 * 0.25 /* binary -> hexadecimal */
3989 + 1 /* turn floor into ceil */
3990 + 2; /* account for leading 0x */
3999 # if ENABLE_UNISTDIO
4000 /* Padding considers the number of characters, therefore
4001 the number of elements after padding may be
4002 > max (tmp_length, width)
4004 <= tmp_length + width. */
4005 tmp_length = xsum (tmp_length, width);
4007 /* Padding considers the number of elements,
4009 if (tmp_length < width)
4014 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
4017 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4021 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4023 if (size_overflow_p (tmp_memsize))
4024 /* Overflow, would lead to out of memory. */
4026 tmp = (TCHAR_T *) malloc (tmp_memsize);
4028 /* Out of memory. */
4033 /* Construct the format string for calling snprintf or
4037 #if NEED_PRINTF_FLAG_GROUPING
4038 /* The underlying implementation doesn't support the ' flag.
4039 Produce no grouping characters in this case; this is
4040 acceptable because the grouping is locale dependent. */
4042 if (flags & FLAG_GROUP)
4045 if (flags & FLAG_LEFT)
4047 if (flags & FLAG_SHOWSIGN)
4049 if (flags & FLAG_SPACE)
4051 if (flags & FLAG_ALT)
4055 if (flags & FLAG_ZERO)
4057 if (dp->width_start != dp->width_end)
4059 size_t n = dp->width_end - dp->width_start;
4060 /* The width specification is known to consist only
4061 of standard ASCII characters. */
4062 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4064 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4069 const FCHAR_T *mp = dp->width_start;
4071 *fbp++ = (unsigned char) *mp++;
4076 if (!prec_ourselves)
4078 if (dp->precision_start != dp->precision_end)
4080 size_t n = dp->precision_end - dp->precision_start;
4081 /* The precision specification is known to consist only
4082 of standard ASCII characters. */
4083 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4085 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4090 const FCHAR_T *mp = dp->precision_start;
4092 *fbp++ = (unsigned char) *mp++;
4100 #if HAVE_LONG_LONG_INT
4101 case TYPE_LONGLONGINT:
4102 case TYPE_ULONGLONGINT:
4103 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4116 case TYPE_WIDE_CHAR:
4119 case TYPE_WIDE_STRING:
4123 case TYPE_LONGDOUBLE:
4129 #if NEED_PRINTF_DIRECTIVE_F
4130 if (dp->conversion == 'F')
4134 *fbp = dp->conversion;
4136 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4141 /* On glibc2 systems from glibc >= 2.3 - probably also older
4142 ones - we know that snprintf's returns value conforms to
4143 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4144 Therefore we can avoid using %n in this situation.
4145 On glibc2 systems from 2004-10-18 or newer, the use of %n
4146 in format strings in writable memory may crash the program
4147 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4148 in this situation. */
4149 /* On native Win32 systems (such as mingw), we can avoid using
4151 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4152 snprintf does not write more than the specified number
4153 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4154 '4', '5', '6' into buf, not '4', '5', '\0'.)
4155 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4156 allows us to recognize the case of an insufficient
4157 buffer size: it returns -1 in this case.
4158 On native Win32 systems (such as mingw) where the OS is
4159 Windows Vista, the use of %n in format strings by default
4160 crashes the program. See
4161 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4162 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4163 So we should avoid %n in this situation. */
4170 /* Construct the arguments for calling snprintf or sprintf. */
4172 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4174 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4176 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4178 if (dp->precision_arg_index != ARG_NONE)
4180 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4182 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4186 /* The SNPRINTF result is appended after result[0..length].
4187 The latter is an array of DCHAR_T; SNPRINTF appends an
4188 array of TCHAR_T to it. This is possible because
4189 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4190 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4191 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4192 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4193 where an snprintf() with maxlen==1 acts like sprintf(). */
4194 ENSURE_ALLOCATION (xsum (length,
4195 (2 + TCHARS_PER_DCHAR - 1)
4196 / TCHARS_PER_DCHAR));
4197 /* Prepare checking whether snprintf returns the count
4199 *(TCHAR_T *) (result + length) = '\0';
4208 size_t maxlen = allocated - length;
4209 /* SNPRINTF can fail if its second argument is
4211 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4212 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4213 maxlen = maxlen * TCHARS_PER_DCHAR;
4214 # define SNPRINTF_BUF(arg) \
4215 switch (prefix_count) \
4218 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4223 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4225 prefixes[0], arg, &count); \
4228 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4230 prefixes[0], prefixes[1], arg, \
4237 # define SNPRINTF_BUF(arg) \
4238 switch (prefix_count) \
4241 count = sprintf (tmp, buf, arg); \
4244 count = sprintf (tmp, buf, prefixes[0], arg); \
4247 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4259 int arg = a.arg[dp->arg_index].a.a_schar;
4265 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4271 int arg = a.arg[dp->arg_index].a.a_short;
4277 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4283 int arg = a.arg[dp->arg_index].a.a_int;
4289 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4295 long int arg = a.arg[dp->arg_index].a.a_longint;
4301 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4305 #if HAVE_LONG_LONG_INT
4306 case TYPE_LONGLONGINT:
4308 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4312 case TYPE_ULONGLONGINT:
4314 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4321 double arg = a.arg[dp->arg_index].a.a_double;
4325 case TYPE_LONGDOUBLE:
4327 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4333 int arg = a.arg[dp->arg_index].a.a_char;
4338 case TYPE_WIDE_CHAR:
4340 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
4347 const char *arg = a.arg[dp->arg_index].a.a_string;
4352 case TYPE_WIDE_STRING:
4354 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
4361 void *arg = a.arg[dp->arg_index].a.a_pointer;
4370 /* Portability: Not all implementations of snprintf()
4371 are ISO C 99 compliant. Determine the number of
4372 bytes that snprintf() has produced or would have
4376 /* Verify that snprintf() has NUL-terminated its
4379 && ((TCHAR_T *) (result + length)) [count] != '\0')
4381 /* Portability hack. */
4382 if (retcount > count)
4387 /* snprintf() doesn't understand the '%n'
4391 /* Don't use the '%n' directive; instead, look
4392 at the snprintf() return value. */
4398 /* Look at the snprintf() return value. */
4401 /* HP-UX 10.20 snprintf() is doubly deficient:
4402 It doesn't understand the '%n' directive,
4403 *and* it returns -1 (rather than the length
4404 that would have been required) when the
4405 buffer is too small. */
4406 size_t bigger_need =
4407 xsum (xtimes (allocated, 2), 12);
4408 ENSURE_ALLOCATION (bigger_need);
4417 /* Attempt to handle failure. */
4420 if (!(result == resultbuf || result == NULL))
4422 if (buf_malloced != NULL)
4423 free (buf_malloced);
4430 /* Handle overflow of the allocated buffer.
4431 If such an overflow occurs, a C99 compliant snprintf()
4432 returns a count >= maxlen. However, a non-compliant
4433 snprintf() function returns only count = maxlen - 1. To
4434 cover both cases, test whether count >= maxlen - 1. */
4435 if ((unsigned int) count + 1 >= maxlen)
4437 /* If maxlen already has attained its allowed maximum,
4438 allocating more memory will not increase maxlen.
4439 Instead of looping, bail out. */
4440 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
4444 /* Need at least (count + 1) * sizeof (TCHAR_T)
4445 bytes. (The +1 is for the trailing NUL.)
4446 But ask for (count + 2) * sizeof (TCHAR_T)
4447 bytes, so that in the next round, we likely get
4448 maxlen > (unsigned int) count + 1
4449 and so we don't get here again.
4450 And allocate proportionally, to avoid looping
4451 eternally if snprintf() reports a too small
4455 ((unsigned int) count + 2
4456 + TCHARS_PER_DCHAR - 1)
4457 / TCHARS_PER_DCHAR),
4458 xtimes (allocated, 2));
4460 ENSURE_ALLOCATION (n);
4466 #if NEED_PRINTF_UNBOUNDED_PRECISION
4469 /* Handle the precision. */
4472 (TCHAR_T *) (result + length);
4476 size_t prefix_count;
4480 /* Put the additional zeroes after the sign. */
4482 && (*prec_ptr == '-' || *prec_ptr == '+'
4483 || *prec_ptr == ' '))
4485 /* Put the additional zeroes after the 0x prefix if
4486 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
4488 && prec_ptr[0] == '0'
4489 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
4492 move = count - prefix_count;
4493 if (precision > move)
4495 /* Insert zeroes. */
4496 size_t insert = precision - move;
4502 (count + insert + TCHARS_PER_DCHAR - 1)
4503 / TCHARS_PER_DCHAR);
4504 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4505 ENSURE_ALLOCATION (n);
4506 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4507 prec_ptr = (TCHAR_T *) (result + length);
4510 prec_end = prec_ptr + count;
4511 prec_ptr += prefix_count;
4513 while (prec_end > prec_ptr)
4516 prec_end[insert] = prec_end[0];
4522 while (prec_end > prec_ptr);
4530 if (count >= tmp_length)
4531 /* tmp_length was incorrectly calculated - fix the
4537 /* Convert from TCHAR_T[] to DCHAR_T[]. */
4538 if (dp->conversion == 'c' || dp->conversion == 's')
4540 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
4542 The result string is not certainly ASCII. */
4543 const TCHAR_T *tmpsrc;
4546 /* This code assumes that TCHAR_T is 'char'. */
4547 typedef int TCHAR_T_verify
4548 [2 * (sizeof (TCHAR_T) == 1) - 1];
4550 tmpsrc = (TCHAR_T *) (result + length);
4556 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
4557 iconveh_question_mark,
4560 &tmpdst, &tmpdst_len)
4563 int saved_errno = errno;
4564 if (!(result == resultbuf || result == NULL))
4566 if (buf_malloced != NULL)
4567 free (buf_malloced);
4569 errno = saved_errno;
4572 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
4573 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
4579 /* The result string is ASCII.
4580 Simple 1:1 conversion. */
4582 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
4583 no-op conversion, in-place on the array starting
4584 at (result + length). */
4585 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
4588 const TCHAR_T *tmpsrc;
4593 if (result == resultbuf)
4595 tmpsrc = (TCHAR_T *) (result + length);
4596 /* ENSURE_ALLOCATION will not move tmpsrc
4597 (because it's part of resultbuf). */
4598 ENSURE_ALLOCATION (xsum (length, count));
4602 /* ENSURE_ALLOCATION will move the array
4603 (because it uses realloc(). */
4604 ENSURE_ALLOCATION (xsum (length, count));
4605 tmpsrc = (TCHAR_T *) (result + length);
4609 ENSURE_ALLOCATION (xsum (length, count));
4611 tmpdst = result + length;
4612 /* Copy backwards, because of overlapping. */
4615 for (n = count; n > 0; n--)
4616 *--tmpdst = (unsigned char) *--tmpsrc;
4621 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4622 /* Make room for the result. */
4623 if (count > allocated - length)
4625 /* Need at least count elements. But allocate
4628 xmax (xsum (length, count), xtimes (allocated, 2));
4630 ENSURE_ALLOCATION (n);
4634 /* Here count <= allocated - length. */
4636 /* Perform padding. */
4637 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4638 if (pad_ourselves && has_width)
4641 # if ENABLE_UNISTDIO
4642 /* Outside POSIX, it's preferrable to compare the width
4643 against the number of _characters_ of the converted
4645 w = DCHAR_MBSNLEN (result + length, count);
4647 /* The width is compared against the number of _bytes_
4648 of the converted value, says POSIX. */
4653 size_t pad = width - w;
4655 /* Make room for the result. */
4656 if (xsum (count, pad) > allocated - length)
4658 /* Need at least count + pad elements. But
4659 allocate proportionally. */
4661 xmax (xsum3 (length, count, pad),
4662 xtimes (allocated, 2));
4666 ENSURE_ALLOCATION (n);
4669 ENSURE_ALLOCATION (n);
4672 /* Here count + pad <= allocated - length. */
4675 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
4676 DCHAR_T * const rp = result + length;
4678 DCHAR_T * const rp = tmp;
4680 DCHAR_T *p = rp + count;
4681 DCHAR_T *end = p + pad;
4683 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4684 if (dp->conversion == 'c'
4685 || dp->conversion == 's')
4686 /* No zero-padding for string directives. */
4691 pad_ptr = (*rp == '-' ? rp + 1 : rp);
4692 /* No zero-padding of "inf" and "nan". */
4693 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
4694 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
4697 /* The generated string now extends from rp to p,
4698 with the zero padding insertion point being at
4701 count = count + pad; /* = end - rp */
4703 if (flags & FLAG_LEFT)
4705 /* Pad with spaces on the right. */
4706 for (; pad > 0; pad--)
4709 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4711 /* Pad with zeroes. */
4716 for (; pad > 0; pad--)
4721 /* Pad with spaces on the left. */
4726 for (; pad > 0; pad--)
4734 /* Here still count <= allocated - length. */
4736 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
4737 /* The snprintf() result did fit. */
4739 /* Append the sprintf() result. */
4740 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4747 #if NEED_PRINTF_DIRECTIVE_F
4748 if (dp->conversion == 'F')
4750 /* Convert the %f result to upper case for %F. */
4751 DCHAR_T *rp = result + length;
4753 for (rc = count; rc > 0; rc--, rp++)
4754 if (*rp >= 'a' && *rp <= 'z')
4755 *rp = *rp - 'a' + 'A';
4766 /* Add the final NUL. */
4767 ENSURE_ALLOCATION (xsum (length, 1));
4768 result[length] = '\0';
4770 if (result != resultbuf && length + 1 < allocated)
4772 /* Shrink the allocated memory if possible. */
4775 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
4780 if (buf_malloced != NULL)
4781 free (buf_malloced);
4784 /* Note that we can produce a big string of a length > INT_MAX. POSIX
4785 says that snprintf() fails with errno = EOVERFLOW in this case, but
4786 that's only because snprintf() returns an 'int'. This function does
4787 not have this limitation. */
4792 if (!(result == resultbuf || result == NULL))
4794 if (buf_malloced != NULL)
4795 free (buf_malloced);
4802 if (!(result == resultbuf || result == NULL))
4804 if (buf_malloced != NULL)
4805 free (buf_malloced);
4813 #undef TCHARS_PER_DCHAR
4820 #undef DCHAR_IS_TCHAR