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
98 # include "isnand-nolibm.h"
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
109 # include "isnand-nolibm.h"
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"
122 # define local_wcslen wcslen
124 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
125 a dependency towards this library, here is a local substitute.
126 Define this substitute only once, even if this file is included
127 twice in the same compilation unit. */
128 # ifndef local_wcslen_defined
129 # define local_wcslen_defined 1
131 local_wcslen (const wchar_t *s)
135 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
143 /* Default parameters. */
145 # if WIDE_CHAR_VERSION
146 # define VASNPRINTF vasnwprintf
147 # define FCHAR_T wchar_t
148 # define DCHAR_T wchar_t
149 # define TCHAR_T wchar_t
150 # define DCHAR_IS_TCHAR 1
151 # define DIRECTIVE wchar_t_directive
152 # define DIRECTIVES wchar_t_directives
153 # define PRINTF_PARSE wprintf_parse
154 # define DCHAR_CPY wmemcpy
156 # define VASNPRINTF vasnprintf
157 # define FCHAR_T char
158 # define DCHAR_T char
159 # define TCHAR_T char
160 # define DCHAR_IS_TCHAR 1
161 # define DIRECTIVE char_directive
162 # define DIRECTIVES char_directives
163 # define PRINTF_PARSE printf_parse
164 # define DCHAR_CPY memcpy
167 #if WIDE_CHAR_VERSION
168 /* TCHAR_T is wchar_t. */
169 # define USE_SNPRINTF 1
170 # if HAVE_DECL__SNWPRINTF
171 /* On Windows, the function swprintf() has a different signature than
172 on Unix; we use the _snwprintf() function instead. */
173 # define SNPRINTF _snwprintf
176 # define SNPRINTF swprintf
179 /* TCHAR_T is char. */
180 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
181 But don't use it on BeOS, since BeOS snprintf produces no output if the
182 size argument is >= 0x3000000.
183 Also don't use it on Linux libc5, since there snprintf with size = 1
184 writes any output without bounds, like sprintf. */
185 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
186 # define USE_SNPRINTF 1
188 # define USE_SNPRINTF 0
190 # if HAVE_DECL__SNPRINTF
192 # define SNPRINTF _snprintf
195 # define SNPRINTF snprintf
196 /* Here we need to call the native snprintf, not rpl_snprintf. */
200 /* Here we need to call the native sprintf, not rpl_sprintf. */
203 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
204 warnings in this file. Use -Dlint to suppress them. */
206 # define IF_LINT(Code) Code
208 # define IF_LINT(Code) /* empty */
211 /* Avoid some warnings from "gcc -Wshadow".
212 This file doesn't use the exp() and remainder() functions. */
216 #define remainder rem
218 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
219 /* Determine the decimal-point character according to the current locale. */
220 # ifndef decimal_point_char_defined
221 # define decimal_point_char_defined 1
223 decimal_point_char ()
226 /* Determine it in a multithread-safe way. We know nl_langinfo is
227 multithread-safe on glibc systems, but is not required to be multithread-
228 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
229 is rarely multithread-safe. */
230 # if HAVE_NL_LANGINFO && __GLIBC__
231 point = nl_langinfo (RADIXCHAR);
234 sprintf (pointbuf, "%#.0f", 1.0);
235 point = &pointbuf[1];
237 point = localeconv () -> decimal_point;
239 /* The decimal point is always a single byte: either '.' or ','. */
240 return (point[0] != '\0' ? point[0] : '.');
245 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
247 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
249 is_infinite_or_zero (double x)
251 return isnand (x) || x + x == x;
256 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
258 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
260 is_infinite_or_zerol (long double x)
262 return isnanl (x) || x + x == x;
267 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
269 /* Converting 'long double' to decimal without rare rounding bugs requires
270 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
271 (and slower) algorithms. */
273 typedef unsigned int mp_limb_t;
274 # define GMP_LIMB_BITS 32
275 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
277 typedef unsigned long long mp_twolimb_t;
278 # define GMP_TWOLIMB_BITS 64
279 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
281 /* Representation of a bignum >= 0. */
285 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
288 /* Compute the product of two bignums >= 0.
289 Return the allocated memory in case of success, NULL in case of memory
290 allocation failure. */
292 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
299 if (src1.nlimbs <= src2.nlimbs)
313 /* Now 0 <= len1 <= len2. */
316 /* src1 or src2 is zero. */
318 dest->limbs = (mp_limb_t *) malloc (1);
322 /* Here 1 <= len1 <= len2. */
328 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
331 for (k = len2; k > 0; )
333 for (i = 0; i < len1; i++)
335 mp_limb_t digit1 = p1[i];
336 mp_twolimb_t carry = 0;
337 for (j = 0; j < len2; j++)
339 mp_limb_t digit2 = p2[j];
340 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
342 dp[i + j] = (mp_limb_t) carry;
343 carry = carry >> GMP_LIMB_BITS;
345 dp[i + len2] = (mp_limb_t) carry;
348 while (dlen > 0 && dp[dlen - 1] == 0)
356 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
357 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
359 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
361 Return the allocated memory in case of success, NULL in case of memory
362 allocation failure. */
364 divide (mpn_t a, mpn_t b, mpn_t *q)
367 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
368 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
369 If m<n, then q:=0 and r:=a.
370 If m>=n=1, perform a single-precision division:
373 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
374 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
375 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
376 Normalise [q[m-1],...,q[0]], yields q.
377 If m>=n>1, perform a multiple-precision division:
378 We have a/b < beta^(m-n+1).
379 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
380 Shift a and b left by s bits, copying them. r:=a.
381 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
382 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
384 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
385 In case of overflow (q* >= beta) set q* := beta-1.
386 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
387 and c3 := b[n-2] * q*.
388 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
389 occurred. Furthermore 0 <= c3 < beta^2.
390 If there was overflow and
391 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
392 the next test can be skipped.}
393 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
394 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
396 Put r := r - b * q* * beta^j. In detail:
397 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
398 hence: u:=0, for i:=0 to n-1 do
400 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
401 u:=u div beta (+ 1, if carry in subtraction)
403 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
405 the carry u does not overflow.}
406 If a negative carry occurs, put q* := q* - 1
407 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
409 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
410 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
412 The room for q[j] can be allocated at the memory location of r[n+j].
413 Finally, round-to-even:
414 Shift r left by 1 bit.
415 If r > b or if r = b and q[0] is odd, q := q+1.
417 const mp_limb_t *a_ptr = a.limbs;
418 size_t a_len = a.nlimbs;
419 const mp_limb_t *b_ptr = b.limbs;
420 size_t b_len = b.nlimbs;
422 mp_limb_t *tmp_roomptr = NULL;
428 /* Allocate room for a_len+2 digits.
429 (Need a_len+1 digits for the real division and 1 more digit for the
430 final rounding of q.) */
431 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
436 while (a_len > 0 && a_ptr[a_len - 1] == 0)
443 /* Division by zero. */
445 if (b_ptr[b_len - 1] == 0)
451 /* Here m = a_len >= 0 and n = b_len > 0. */
455 /* m<n: trivial case. q=0, r := copy of a. */
458 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
459 q_ptr = roomptr + a_len;
464 /* n=1: single precision division.
465 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
469 mp_limb_t den = b_ptr[0];
470 mp_limb_t remainder = 0;
471 const mp_limb_t *sourceptr = a_ptr + a_len;
472 mp_limb_t *destptr = q_ptr + a_len;
474 for (count = a_len; count > 0; count--)
477 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
478 *--destptr = num / den;
479 remainder = num % den;
481 /* Normalise and store r. */
484 r_ptr[0] = remainder;
491 if (q_ptr[q_len - 1] == 0)
497 /* n>1: multiple precision division.
498 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
499 beta^(m-n-1) <= a/b < beta^(m-n+1). */
503 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
531 /* 0 <= s < GMP_LIMB_BITS.
532 Copy b, shifting it left by s bits. */
535 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
536 if (tmp_roomptr == NULL)
542 const mp_limb_t *sourceptr = b_ptr;
543 mp_limb_t *destptr = tmp_roomptr;
544 mp_twolimb_t accu = 0;
546 for (count = b_len; count > 0; count--)
548 accu += (mp_twolimb_t) *sourceptr++ << s;
549 *destptr++ = (mp_limb_t) accu;
550 accu = accu >> GMP_LIMB_BITS;
552 /* accu must be zero, since that was how s was determined. */
558 /* Copy a, shifting it left by s bits, yields r.
560 At the beginning: r = roomptr[0..a_len],
561 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
565 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
570 const mp_limb_t *sourceptr = a_ptr;
571 mp_limb_t *destptr = r_ptr;
572 mp_twolimb_t accu = 0;
574 for (count = a_len; count > 0; count--)
576 accu += (mp_twolimb_t) *sourceptr++ << s;
577 *destptr++ = (mp_limb_t) accu;
578 accu = accu >> GMP_LIMB_BITS;
580 *destptr++ = (mp_limb_t) accu;
582 q_ptr = roomptr + b_len;
583 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
585 size_t j = a_len - b_len; /* m-n */
586 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
587 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
588 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
589 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
590 /* Division loop, traversed m-n+1 times.
591 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
596 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
598 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
600 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
601 | r_ptr[j + b_len - 1];
602 q_star = num / b_msd;
607 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
608 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
609 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
610 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
611 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
613 If yes, jump directly to the subtraction loop.
614 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
615 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
616 if (r_ptr[j + b_len] > b_msd
617 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
618 /* r[j+n] >= b[n-1]+1 or
619 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
624 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
626 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
627 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
628 mp_twolimb_t c3 = /* b[n-2] * q* */
629 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
630 /* While c2 < c3, increase c2 and decrease c3.
631 Consider c3-c2. While it is > 0, decrease it by
632 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
633 this can happen only twice. */
636 q_star = q_star - 1; /* q* := q* - 1 */
637 if (c3 - c2 > b_msdd)
638 q_star = q_star - 1; /* q* := q* - 1 */
644 /* Subtract r := r - b * q* * beta^j. */
647 const mp_limb_t *sourceptr = b_ptr;
648 mp_limb_t *destptr = r_ptr + j;
649 mp_twolimb_t carry = 0;
651 for (count = b_len; count > 0; count--)
653 /* Here 0 <= carry <= q*. */
656 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
657 + (mp_limb_t) ~(*destptr);
658 /* Here 0 <= carry <= beta*q* + beta-1. */
659 *destptr++ = ~(mp_limb_t) carry;
660 carry = carry >> GMP_LIMB_BITS; /* <= q* */
662 cr = (mp_limb_t) carry;
664 /* Subtract cr from r_ptr[j + b_len], then forget about
666 if (cr > r_ptr[j + b_len])
668 /* Subtraction gave a carry. */
669 q_star = q_star - 1; /* q* := q* - 1 */
672 const mp_limb_t *sourceptr = b_ptr;
673 mp_limb_t *destptr = r_ptr + j;
676 for (count = b_len; count > 0; count--)
678 mp_limb_t source1 = *sourceptr++;
679 mp_limb_t source2 = *destptr;
680 *destptr++ = source1 + source2 + carry;
683 ? source1 >= (mp_limb_t) ~source2
684 : source1 > (mp_limb_t) ~source2);
687 /* Forget about the carry and about r[j+n]. */
690 /* q* is determined. Store it as q[j]. */
699 if (q_ptr[q_len - 1] == 0)
701 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
702 b is shifted left by s bits. */
703 /* Shift r right by s bits. */
706 mp_limb_t ptr = r_ptr + r_len;
707 mp_twolimb_t accu = 0;
709 for (count = r_len; count > 0; count--)
711 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
712 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
713 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
718 while (r_len > 0 && r_ptr[r_len - 1] == 0)
721 /* Compare r << 1 with b. */
729 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
730 | (i < r_len ? r_ptr[i] << 1 : 0);
731 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
741 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
746 for (i = 0; i < q_len; i++)
747 if (++(q_ptr[i]) != 0)
752 if (tmp_roomptr != NULL)
759 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
761 Destroys the contents of a.
762 Return the allocated memory - containing the decimal digits in low-to-high
763 order, terminated with a NUL character - in case of success, NULL in case
764 of memory allocation failure. */
766 convert_to_decimal (mpn_t a, size_t extra_zeroes)
768 mp_limb_t *a_ptr = a.limbs;
769 size_t a_len = a.nlimbs;
770 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
771 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
772 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
776 for (; extra_zeroes > 0; extra_zeroes--)
780 /* Divide a by 10^9, in-place. */
781 mp_limb_t remainder = 0;
782 mp_limb_t *ptr = a_ptr + a_len;
784 for (count = a_len; count > 0; count--)
787 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
788 *ptr = num / 1000000000;
789 remainder = num % 1000000000;
791 /* Store the remainder as 9 decimal digits. */
792 for (count = 9; count > 0; count--)
794 *d_ptr++ = '0' + (remainder % 10);
795 remainder = remainder / 10;
798 if (a_ptr[a_len - 1] == 0)
801 /* Remove leading zeroes. */
802 while (d_ptr > c_ptr && d_ptr[-1] == '0')
804 /* But keep at least one zero. */
807 /* Terminate the string. */
813 # if NEED_PRINTF_LONG_DOUBLE
815 /* Assuming x is finite and >= 0:
816 write x as x = 2^e * m, where m is a bignum.
817 Return the allocated memory in case of success, NULL in case of memory
818 allocation failure. */
820 decode_long_double (long double x, int *ep, mpn_t *mp)
827 /* Allocate memory for result. */
828 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
829 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
832 /* Split into exponential part and mantissa. */
833 y = frexpl (x, &exp);
834 if (!(y >= 0.0L && y < 1.0L))
836 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
837 latter is an integer. */
838 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
839 I'm not sure whether it's safe to cast a 'long double' value between
840 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
841 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
843 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
844 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
847 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
850 if (!(y >= 0.0L && y < 1.0L))
852 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
855 if (!(y >= 0.0L && y < 1.0L))
857 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
862 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
865 if (!(y >= 0.0L && y < 1.0L))
867 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
871 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
874 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
877 if (!(y >= 0.0L && y < 1.0L))
879 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
882 if (!(y >= 0.0L && y < 1.0L))
884 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
886 #if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
892 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
895 *ep = exp - LDBL_MANT_BIT;
901 # if NEED_PRINTF_DOUBLE
903 /* Assuming x is finite and >= 0:
904 write x as x = 2^e * m, where m is a bignum.
905 Return the allocated memory in case of success, NULL in case of memory
906 allocation failure. */
908 decode_double (double x, int *ep, mpn_t *mp)
915 /* Allocate memory for result. */
916 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
917 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
920 /* Split into exponential part and mantissa. */
922 if (!(y >= 0.0 && y < 1.0))
924 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
925 latter is an integer. */
926 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
927 I'm not sure whether it's safe to cast a 'double' value between
928 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
929 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
931 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
932 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
935 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
938 if (!(y >= 0.0 && y < 1.0))
940 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
943 if (!(y >= 0.0 && y < 1.0))
945 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
950 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
953 if (!(y >= 0.0 && y < 1.0))
955 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
959 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
962 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
965 if (!(y >= 0.0 && y < 1.0))
967 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
970 if (!(y >= 0.0 && y < 1.0))
972 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
977 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
980 *ep = exp - DBL_MANT_BIT;
986 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
987 Returns the decimal representation of round (x * 10^n).
988 Return the allocated memory - containing the decimal digits in low-to-high
989 order, terminated with a NUL character - in case of success, NULL in case
990 of memory allocation failure. */
992 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1000 unsigned int s_limbs;
1001 unsigned int s_bits;
1009 /* x = 2^e * m, hence
1010 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1011 = round (2^s * 5^n * m). */
1014 /* Factor out a common power of 10 if possible. */
1017 extra_zeroes = (s < n ? s : n);
1021 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1022 Before converting to decimal, we need to compute
1023 z = round (2^s * 5^n * m). */
1024 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1025 sign. 2.322 is slightly larger than log(5)/log(2). */
1026 abs_n = (n >= 0 ? n : -n);
1027 abs_s = (s >= 0 ? s : -s);
1028 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1029 + abs_s / GMP_LIMB_BITS + 1)
1030 * sizeof (mp_limb_t));
1031 if (pow5_ptr == NULL)
1036 /* Initialize with 1. */
1039 /* Multiply with 5^|n|. */
1042 static mp_limb_t const small_pow5[13 + 1] =
1044 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1045 48828125, 244140625, 1220703125
1048 for (n13 = 0; n13 <= abs_n; n13 += 13)
1050 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1052 mp_twolimb_t carry = 0;
1053 for (j = 0; j < pow5_len; j++)
1055 mp_limb_t digit2 = pow5_ptr[j];
1056 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1057 pow5_ptr[j] = (mp_limb_t) carry;
1058 carry = carry >> GMP_LIMB_BITS;
1061 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1064 s_limbs = abs_s / GMP_LIMB_BITS;
1065 s_bits = abs_s % GMP_LIMB_BITS;
1066 if (n >= 0 ? s >= 0 : s <= 0)
1068 /* Multiply with 2^|s|. */
1071 mp_limb_t *ptr = pow5_ptr;
1072 mp_twolimb_t accu = 0;
1074 for (count = pow5_len; count > 0; count--)
1076 accu += (mp_twolimb_t) *ptr << s_bits;
1077 *ptr++ = (mp_limb_t) accu;
1078 accu = accu >> GMP_LIMB_BITS;
1082 *ptr = (mp_limb_t) accu;
1089 for (count = pow5_len; count > 0;)
1092 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1094 for (count = s_limbs; count > 0;)
1097 pow5_ptr[count] = 0;
1099 pow5_len += s_limbs;
1101 pow5.limbs = pow5_ptr;
1102 pow5.nlimbs = pow5_len;
1105 /* Multiply m with pow5. No division needed. */
1106 z_memory = multiply (m, pow5, &z);
1110 /* Divide m by pow5 and round. */
1111 z_memory = divide (m, pow5, &z);
1116 pow5.limbs = pow5_ptr;
1117 pow5.nlimbs = pow5_len;
1121 Multiply m with pow5, then divide by 2^|s|. */
1125 tmp_memory = multiply (m, pow5, &numerator);
1126 if (tmp_memory == NULL)
1132 /* Construct 2^|s|. */
1134 mp_limb_t *ptr = pow5_ptr + pow5_len;
1136 for (i = 0; i < s_limbs; i++)
1138 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1139 denominator.limbs = ptr;
1140 denominator.nlimbs = s_limbs + 1;
1142 z_memory = divide (numerator, denominator, &z);
1148 Multiply m with 2^s, then divide by pow5. */
1151 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1152 * sizeof (mp_limb_t));
1153 if (num_ptr == NULL)
1160 mp_limb_t *destptr = num_ptr;
1163 for (i = 0; i < s_limbs; i++)
1168 const mp_limb_t *sourceptr = m.limbs;
1169 mp_twolimb_t accu = 0;
1171 for (count = m.nlimbs; count > 0; count--)
1173 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1174 *destptr++ = (mp_limb_t) accu;
1175 accu = accu >> GMP_LIMB_BITS;
1178 *destptr++ = (mp_limb_t) accu;
1182 const mp_limb_t *sourceptr = m.limbs;
1184 for (count = m.nlimbs; count > 0; count--)
1185 *destptr++ = *sourceptr++;
1187 numerator.limbs = num_ptr;
1188 numerator.nlimbs = destptr - num_ptr;
1190 z_memory = divide (numerator, pow5, &z);
1197 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1199 if (z_memory == NULL)
1201 digits = convert_to_decimal (z, extra_zeroes);
1206 # if NEED_PRINTF_LONG_DOUBLE
1208 /* Assuming x is finite and >= 0, and n is an integer:
1209 Returns the decimal representation of round (x * 10^n).
1210 Return the allocated memory - containing the decimal digits in low-to-high
1211 order, terminated with a NUL character - in case of success, NULL in case
1212 of memory allocation failure. */
1214 scale10_round_decimal_long_double (long double x, int n)
1218 void *memory = decode_long_double (x, &e, &m);
1219 return scale10_round_decimal_decoded (e, m, memory, n);
1224 # if NEED_PRINTF_DOUBLE
1226 /* Assuming x is finite and >= 0, and n is an integer:
1227 Returns the decimal representation of round (x * 10^n).
1228 Return the allocated memory - containing the decimal digits in low-to-high
1229 order, terminated with a NUL character - in case of success, NULL in case
1230 of memory allocation failure. */
1232 scale10_round_decimal_double (double x, int n)
1236 void *memory = decode_double (x, &e, &m);
1237 return scale10_round_decimal_decoded (e, m, memory, n);
1242 # if NEED_PRINTF_LONG_DOUBLE
1244 /* Assuming x is finite and > 0:
1245 Return an approximation for n with 10^n <= x < 10^(n+1).
1246 The approximation is usually the right n, but may be off by 1 sometimes. */
1248 floorlog10l (long double x)
1255 /* Split into exponential part and mantissa. */
1256 y = frexpl (x, &exp);
1257 if (!(y >= 0.0L && y < 1.0L))
1263 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1265 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1266 exp -= GMP_LIMB_BITS;
1268 if (y < (1.0L / (1 << 16)))
1270 y *= 1.0L * (1 << 16);
1273 if (y < (1.0L / (1 << 8)))
1275 y *= 1.0L * (1 << 8);
1278 if (y < (1.0L / (1 << 4)))
1280 y *= 1.0L * (1 << 4);
1283 if (y < (1.0L / (1 << 2)))
1285 y *= 1.0L * (1 << 2);
1288 if (y < (1.0L / (1 << 1)))
1290 y *= 1.0L * (1 << 1);
1294 if (!(y >= 0.5L && y < 1.0L))
1296 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1299 if (z < 0.70710678118654752444)
1301 z *= 1.4142135623730950488;
1304 if (z < 0.8408964152537145431)
1306 z *= 1.1892071150027210667;
1309 if (z < 0.91700404320467123175)
1311 z *= 1.0905077326652576592;
1314 if (z < 0.9576032806985736469)
1316 z *= 1.0442737824274138403;
1319 /* Now 0.95 <= z <= 1.01. */
1321 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1322 Four terms are enough to get an approximation with error < 10^-7. */
1323 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1324 /* Finally multiply with log(2)/log(10), yields an approximation for
1326 l *= 0.30102999566398119523;
1327 /* Round down to the next integer. */
1328 return (int) l + (l < 0 ? -1 : 0);
1333 # if NEED_PRINTF_DOUBLE
1335 /* Assuming x is finite and > 0:
1336 Return an approximation for n with 10^n <= x < 10^(n+1).
1337 The approximation is usually the right n, but may be off by 1 sometimes. */
1339 floorlog10 (double x)
1346 /* Split into exponential part and mantissa. */
1347 y = frexp (x, &exp);
1348 if (!(y >= 0.0 && y < 1.0))
1354 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1356 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1357 exp -= GMP_LIMB_BITS;
1359 if (y < (1.0 / (1 << 16)))
1361 y *= 1.0 * (1 << 16);
1364 if (y < (1.0 / (1 << 8)))
1366 y *= 1.0 * (1 << 8);
1369 if (y < (1.0 / (1 << 4)))
1371 y *= 1.0 * (1 << 4);
1374 if (y < (1.0 / (1 << 2)))
1376 y *= 1.0 * (1 << 2);
1379 if (y < (1.0 / (1 << 1)))
1381 y *= 1.0 * (1 << 1);
1385 if (!(y >= 0.5 && y < 1.0))
1387 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1390 if (z < 0.70710678118654752444)
1392 z *= 1.4142135623730950488;
1395 if (z < 0.8408964152537145431)
1397 z *= 1.1892071150027210667;
1400 if (z < 0.91700404320467123175)
1402 z *= 1.0905077326652576592;
1405 if (z < 0.9576032806985736469)
1407 z *= 1.0442737824274138403;
1410 /* Now 0.95 <= z <= 1.01. */
1412 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1413 Four terms are enough to get an approximation with error < 10^-7. */
1414 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1415 /* Finally multiply with log(2)/log(10), yields an approximation for
1417 l *= 0.30102999566398119523;
1418 /* Round down to the next integer. */
1419 return (int) l + (l < 0 ? -1 : 0);
1424 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1425 a single '1' digit. */
1427 is_borderline (const char *digits, size_t precision)
1429 for (; precision > 0; precision--, digits++)
1435 return *digits == '\0';
1441 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1442 const FCHAR_T *format, va_list args)
1447 if (PRINTF_PARSE (format, &d, &a) < 0)
1448 /* errno is already set. */
1456 if (PRINTF_FETCHARGS (args, &a) < 0)
1464 size_t buf_neededlength;
1466 TCHAR_T *buf_malloced;
1470 /* Output string accumulator. */
1475 /* Allocate a small buffer that will hold a directive passed to
1476 sprintf or snprintf. */
1478 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1480 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1482 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1483 buf_malloced = NULL;
1488 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1489 if (size_overflow_p (buf_memsize))
1490 goto out_of_memory_1;
1491 buf = (TCHAR_T *) malloc (buf_memsize);
1493 goto out_of_memory_1;
1497 if (resultbuf != NULL)
1500 allocated = *lengthp;
1509 result is either == resultbuf or == NULL or malloc-allocated.
1510 If length > 0, then result != NULL. */
1512 /* Ensures that allocated >= needed. Aborts through a jump to
1513 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1514 #define ENSURE_ALLOCATION(needed) \
1515 if ((needed) > allocated) \
1517 size_t memory_size; \
1520 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1521 if ((needed) > allocated) \
1522 allocated = (needed); \
1523 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1524 if (size_overflow_p (memory_size)) \
1525 goto out_of_memory; \
1526 if (result == resultbuf || result == NULL) \
1527 memory = (DCHAR_T *) malloc (memory_size); \
1529 memory = (DCHAR_T *) realloc (result, memory_size); \
1530 if (memory == NULL) \
1531 goto out_of_memory; \
1532 if (result == resultbuf && length > 0) \
1533 DCHAR_CPY (memory, result, length); \
1537 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1539 if (cp != dp->dir_start)
1541 size_t n = dp->dir_start - cp;
1542 size_t augmented_length = xsum (length, n);
1544 ENSURE_ALLOCATION (augmented_length);
1545 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1546 need that the format string contains only ASCII characters
1547 if FCHAR_T and DCHAR_T are not the same type. */
1548 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1550 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1551 length = augmented_length;
1556 result[length++] = (unsigned char) *cp++;
1563 /* Execute a single directive. */
1564 if (dp->conversion == '%')
1566 size_t augmented_length;
1568 if (!(dp->arg_index == ARG_NONE))
1570 augmented_length = xsum (length, 1);
1571 ENSURE_ALLOCATION (augmented_length);
1572 result[length] = '%';
1573 length = augmented_length;
1577 if (!(dp->arg_index != ARG_NONE))
1580 if (dp->conversion == 'n')
1582 switch (a.arg[dp->arg_index].type)
1584 case TYPE_COUNT_SCHAR_POINTER:
1585 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1587 case TYPE_COUNT_SHORT_POINTER:
1588 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1590 case TYPE_COUNT_INT_POINTER:
1591 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1593 case TYPE_COUNT_LONGINT_POINTER:
1594 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1596 #if HAVE_LONG_LONG_INT
1597 case TYPE_COUNT_LONGLONGINT_POINTER:
1598 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1606 /* The unistdio extensions. */
1607 else if (dp->conversion == 'U')
1609 arg_type type = a.arg[dp->arg_index].type;
1610 int flags = dp->flags;
1618 if (dp->width_start != dp->width_end)
1620 if (dp->width_arg_index != ARG_NONE)
1624 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1626 arg = a.arg[dp->width_arg_index].a.a_int;
1629 /* "A negative field width is taken as a '-' flag
1630 followed by a positive field width." */
1632 width = (unsigned int) (-arg);
1639 const FCHAR_T *digitp = dp->width_start;
1642 width = xsum (xtimes (width, 10), *digitp++ - '0');
1643 while (digitp != dp->width_end);
1650 if (dp->precision_start != dp->precision_end)
1652 if (dp->precision_arg_index != ARG_NONE)
1656 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1658 arg = a.arg[dp->precision_arg_index].a.a_int;
1659 /* "A negative precision is taken as if the precision
1669 const FCHAR_T *digitp = dp->precision_start + 1;
1672 while (digitp != dp->precision_end)
1673 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1680 case TYPE_U8_STRING:
1682 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1683 const uint8_t *arg_end;
1688 /* Use only PRECISION characters, from the left. */
1691 for (; precision > 0; precision--)
1693 int count = u8_strmblen (arg_end);
1698 if (!(result == resultbuf || result == NULL))
1700 if (buf_malloced != NULL)
1701 free (buf_malloced);
1712 /* Use the entire string, and count the number of
1718 int count = u8_strmblen (arg_end);
1723 if (!(result == resultbuf || result == NULL))
1725 if (buf_malloced != NULL)
1726 free (buf_malloced);
1737 /* Use the entire string. */
1738 arg_end = arg + u8_strlen (arg);
1739 /* The number of characters doesn't matter. */
1743 if (has_width && width > characters
1744 && !(dp->flags & FLAG_LEFT))
1746 size_t n = width - characters;
1747 ENSURE_ALLOCATION (xsum (length, n));
1748 DCHAR_SET (result + length, ' ', n);
1752 # if DCHAR_IS_UINT8_T
1754 size_t n = arg_end - arg;
1755 ENSURE_ALLOCATION (xsum (length, n));
1756 DCHAR_CPY (result + length, arg, n);
1761 DCHAR_T *converted = result + length;
1762 size_t converted_len = allocated - length;
1764 /* Convert from UTF-8 to locale encoding. */
1765 if (u8_conv_to_encoding (locale_charset (),
1766 iconveh_question_mark,
1767 arg, arg_end - arg, NULL,
1768 &converted, &converted_len)
1771 /* Convert from UTF-8 to UTF-16/UTF-32. */
1773 U8_TO_DCHAR (arg, arg_end - arg,
1774 converted, &converted_len);
1775 if (converted == NULL)
1778 int saved_errno = errno;
1779 if (!(result == resultbuf || result == NULL))
1781 if (buf_malloced != NULL)
1782 free (buf_malloced);
1784 errno = saved_errno;
1787 if (converted != result + length)
1789 ENSURE_ALLOCATION (xsum (length, converted_len));
1790 DCHAR_CPY (result + length, converted, converted_len);
1793 length += converted_len;
1797 if (has_width && width > characters
1798 && (dp->flags & FLAG_LEFT))
1800 size_t n = width - characters;
1801 ENSURE_ALLOCATION (xsum (length, n));
1802 DCHAR_SET (result + length, ' ', n);
1808 case TYPE_U16_STRING:
1810 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1811 const uint16_t *arg_end;
1816 /* Use only PRECISION characters, from the left. */
1819 for (; precision > 0; precision--)
1821 int count = u16_strmblen (arg_end);
1826 if (!(result == resultbuf || result == NULL))
1828 if (buf_malloced != NULL)
1829 free (buf_malloced);
1840 /* Use the entire string, and count the number of
1846 int count = u16_strmblen (arg_end);
1851 if (!(result == resultbuf || result == NULL))
1853 if (buf_malloced != NULL)
1854 free (buf_malloced);
1865 /* Use the entire string. */
1866 arg_end = arg + u16_strlen (arg);
1867 /* The number of characters doesn't matter. */
1871 if (has_width && width > characters
1872 && !(dp->flags & FLAG_LEFT))
1874 size_t n = width - characters;
1875 ENSURE_ALLOCATION (xsum (length, n));
1876 DCHAR_SET (result + length, ' ', n);
1880 # if DCHAR_IS_UINT16_T
1882 size_t n = arg_end - arg;
1883 ENSURE_ALLOCATION (xsum (length, n));
1884 DCHAR_CPY (result + length, arg, n);
1889 DCHAR_T *converted = result + length;
1890 size_t converted_len = allocated - length;
1892 /* Convert from UTF-16 to locale encoding. */
1893 if (u16_conv_to_encoding (locale_charset (),
1894 iconveh_question_mark,
1895 arg, arg_end - arg, NULL,
1896 &converted, &converted_len)
1899 /* Convert from UTF-16 to UTF-8/UTF-32. */
1901 U16_TO_DCHAR (arg, arg_end - arg,
1902 converted, &converted_len);
1903 if (converted == NULL)
1906 int saved_errno = errno;
1907 if (!(result == resultbuf || result == NULL))
1909 if (buf_malloced != NULL)
1910 free (buf_malloced);
1912 errno = saved_errno;
1915 if (converted != result + length)
1917 ENSURE_ALLOCATION (xsum (length, converted_len));
1918 DCHAR_CPY (result + length, converted, converted_len);
1921 length += converted_len;
1925 if (has_width && width > characters
1926 && (dp->flags & FLAG_LEFT))
1928 size_t n = width - characters;
1929 ENSURE_ALLOCATION (xsum (length, n));
1930 DCHAR_SET (result + length, ' ', n);
1936 case TYPE_U32_STRING:
1938 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1939 const uint32_t *arg_end;
1944 /* Use only PRECISION characters, from the left. */
1947 for (; precision > 0; precision--)
1949 int count = u32_strmblen (arg_end);
1954 if (!(result == resultbuf || result == NULL))
1956 if (buf_malloced != NULL)
1957 free (buf_malloced);
1968 /* Use the entire string, and count the number of
1974 int count = u32_strmblen (arg_end);
1979 if (!(result == resultbuf || result == NULL))
1981 if (buf_malloced != NULL)
1982 free (buf_malloced);
1993 /* Use the entire string. */
1994 arg_end = arg + u32_strlen (arg);
1995 /* The number of characters doesn't matter. */
1999 if (has_width && width > characters
2000 && !(dp->flags & FLAG_LEFT))
2002 size_t n = width - characters;
2003 ENSURE_ALLOCATION (xsum (length, n));
2004 DCHAR_SET (result + length, ' ', n);
2008 # if DCHAR_IS_UINT32_T
2010 size_t n = arg_end - arg;
2011 ENSURE_ALLOCATION (xsum (length, n));
2012 DCHAR_CPY (result + length, arg, n);
2017 DCHAR_T *converted = result + length;
2018 size_t converted_len = allocated - length;
2020 /* Convert from UTF-32 to locale encoding. */
2021 if (u32_conv_to_encoding (locale_charset (),
2022 iconveh_question_mark,
2023 arg, arg_end - arg, NULL,
2024 &converted, &converted_len)
2027 /* Convert from UTF-32 to UTF-8/UTF-16. */
2029 U32_TO_DCHAR (arg, arg_end - arg,
2030 converted, &converted_len);
2031 if (converted == NULL)
2034 int saved_errno = errno;
2035 if (!(result == resultbuf || result == NULL))
2037 if (buf_malloced != NULL)
2038 free (buf_malloced);
2040 errno = saved_errno;
2043 if (converted != result + length)
2045 ENSURE_ALLOCATION (xsum (length, converted_len));
2046 DCHAR_CPY (result + length, converted, converted_len);
2049 length += converted_len;
2053 if (has_width && width > characters
2054 && (dp->flags & FLAG_LEFT))
2056 size_t n = width - characters;
2057 ENSURE_ALLOCATION (xsum (length, n));
2058 DCHAR_SET (result + length, ' ', n);
2069 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2070 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2071 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2073 # if NEED_PRINTF_DOUBLE
2074 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2076 # if NEED_PRINTF_LONG_DOUBLE
2077 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2083 arg_type type = a.arg[dp->arg_index].type;
2084 int flags = dp->flags;
2090 DCHAR_T tmpbuf[700];
2097 if (dp->width_start != dp->width_end)
2099 if (dp->width_arg_index != ARG_NONE)
2103 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2105 arg = a.arg[dp->width_arg_index].a.a_int;
2108 /* "A negative field width is taken as a '-' flag
2109 followed by a positive field width." */
2111 width = (unsigned int) (-arg);
2118 const FCHAR_T *digitp = dp->width_start;
2121 width = xsum (xtimes (width, 10), *digitp++ - '0');
2122 while (digitp != dp->width_end);
2129 if (dp->precision_start != dp->precision_end)
2131 if (dp->precision_arg_index != ARG_NONE)
2135 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2137 arg = a.arg[dp->precision_arg_index].a.a_int;
2138 /* "A negative precision is taken as if the precision
2148 const FCHAR_T *digitp = dp->precision_start + 1;
2151 while (digitp != dp->precision_end)
2152 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2157 /* Allocate a temporary buffer of sufficient size. */
2158 if (type == TYPE_LONGDOUBLE)
2160 (unsigned int) ((LDBL_DIG + 1)
2161 * 0.831 /* decimal -> hexadecimal */
2163 + 1; /* turn floor into ceil */
2166 (unsigned int) ((DBL_DIG + 1)
2167 * 0.831 /* decimal -> hexadecimal */
2169 + 1; /* turn floor into ceil */
2170 if (tmp_length < precision)
2171 tmp_length = precision;
2172 /* Account for sign, decimal point etc. */
2173 tmp_length = xsum (tmp_length, 12);
2175 if (tmp_length < width)
2178 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2180 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2184 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2186 if (size_overflow_p (tmp_memsize))
2187 /* Overflow, would lead to out of memory. */
2189 tmp = (DCHAR_T *) malloc (tmp_memsize);
2191 /* Out of memory. */
2197 if (type == TYPE_LONGDOUBLE)
2199 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2200 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2204 if (dp->conversion == 'A')
2206 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2210 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2216 DECL_LONG_DOUBLE_ROUNDING
2218 BEGIN_LONG_DOUBLE_ROUNDING ();
2220 if (signbit (arg)) /* arg < 0.0L or negative zero */
2228 else if (flags & FLAG_SHOWSIGN)
2230 else if (flags & FLAG_SPACE)
2233 if (arg > 0.0L && arg + arg == arg)
2235 if (dp->conversion == 'A')
2237 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2241 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2247 long double mantissa;
2250 mantissa = printf_frexpl (arg, &exponent);
2258 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2260 /* Round the mantissa. */
2261 long double tail = mantissa;
2264 for (q = precision; ; q--)
2266 int digit = (int) tail;
2270 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2279 for (q = precision; q > 0; q--)
2285 *p++ = dp->conversion - 'A' + 'X';
2290 digit = (int) mantissa;
2293 if ((flags & FLAG_ALT)
2294 || mantissa > 0.0L || precision > 0)
2296 *p++ = decimal_point_char ();
2297 /* This loop terminates because we assume
2298 that FLT_RADIX is a power of 2. */
2299 while (mantissa > 0.0L)
2302 digit = (int) mantissa;
2307 : dp->conversion - 10);
2311 while (precision > 0)
2318 *p++ = dp->conversion - 'A' + 'P';
2319 # if WIDE_CHAR_VERSION
2321 static const wchar_t decimal_format[] =
2322 { '%', '+', 'd', '\0' };
2323 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2328 if (sizeof (DCHAR_T) == 1)
2330 sprintf ((char *) p, "%+d", exponent);
2338 sprintf (expbuf, "%+d", exponent);
2339 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2345 END_LONG_DOUBLE_ROUNDING ();
2353 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2354 double arg = a.arg[dp->arg_index].a.a_double;
2358 if (dp->conversion == 'A')
2360 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2364 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2371 if (signbit (arg)) /* arg < 0.0 or negative zero */
2379 else if (flags & FLAG_SHOWSIGN)
2381 else if (flags & FLAG_SPACE)
2384 if (arg > 0.0 && arg + arg == arg)
2386 if (dp->conversion == 'A')
2388 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2392 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2401 mantissa = printf_frexp (arg, &exponent);
2409 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2411 /* Round the mantissa. */
2412 double tail = mantissa;
2415 for (q = precision; ; q--)
2417 int digit = (int) tail;
2421 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2430 for (q = precision; q > 0; q--)
2436 *p++ = dp->conversion - 'A' + 'X';
2441 digit = (int) mantissa;
2444 if ((flags & FLAG_ALT)
2445 || mantissa > 0.0 || precision > 0)
2447 *p++ = decimal_point_char ();
2448 /* This loop terminates because we assume
2449 that FLT_RADIX is a power of 2. */
2450 while (mantissa > 0.0)
2453 digit = (int) mantissa;
2458 : dp->conversion - 10);
2462 while (precision > 0)
2469 *p++ = dp->conversion - 'A' + 'P';
2470 # if WIDE_CHAR_VERSION
2472 static const wchar_t decimal_format[] =
2473 { '%', '+', 'd', '\0' };
2474 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2479 if (sizeof (DCHAR_T) == 1)
2481 sprintf ((char *) p, "%+d", exponent);
2489 sprintf (expbuf, "%+d", exponent);
2490 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2500 /* The generated string now extends from tmp to p, with the
2501 zero padding insertion point being at pad_ptr. */
2502 if (has_width && p - tmp < width)
2504 size_t pad = width - (p - tmp);
2505 DCHAR_T *end = p + pad;
2507 if (flags & FLAG_LEFT)
2509 /* Pad with spaces on the right. */
2510 for (; pad > 0; pad--)
2513 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2515 /* Pad with zeroes. */
2520 for (; pad > 0; pad--)
2525 /* Pad with spaces on the left. */
2530 for (; pad > 0; pad--)
2538 size_t count = p - tmp;
2540 if (count >= tmp_length)
2541 /* tmp_length was incorrectly calculated - fix the
2545 /* Make room for the result. */
2546 if (count >= allocated - length)
2548 size_t n = xsum (length, count);
2550 ENSURE_ALLOCATION (n);
2553 /* Append the result. */
2554 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2561 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2562 else if ((dp->conversion == 'f' || dp->conversion == 'F'
2563 || dp->conversion == 'e' || dp->conversion == 'E'
2564 || dp->conversion == 'g' || dp->conversion == 'G'
2565 || dp->conversion == 'a' || dp->conversion == 'A')
2567 # if NEED_PRINTF_DOUBLE
2568 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2569 # elif NEED_PRINTF_INFINITE_DOUBLE
2570 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2571 /* The systems (mingw) which produce wrong output
2572 for Inf, -Inf, and NaN also do so for -0.0.
2573 Therefore we treat this case here as well. */
2574 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2576 # if NEED_PRINTF_LONG_DOUBLE
2577 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2578 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2579 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2580 /* Some systems produce wrong output for Inf,
2581 -Inf, and NaN. Some systems in this category
2582 (IRIX 5.3) also do so for -0.0. Therefore we
2583 treat this case here as well. */
2584 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
2588 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2589 arg_type type = a.arg[dp->arg_index].type;
2591 int flags = dp->flags;
2597 DCHAR_T tmpbuf[700];
2604 if (dp->width_start != dp->width_end)
2606 if (dp->width_arg_index != ARG_NONE)
2610 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2612 arg = a.arg[dp->width_arg_index].a.a_int;
2615 /* "A negative field width is taken as a '-' flag
2616 followed by a positive field width." */
2618 width = (unsigned int) (-arg);
2625 const FCHAR_T *digitp = dp->width_start;
2628 width = xsum (xtimes (width, 10), *digitp++ - '0');
2629 while (digitp != dp->width_end);
2636 if (dp->precision_start != dp->precision_end)
2638 if (dp->precision_arg_index != ARG_NONE)
2642 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2644 arg = a.arg[dp->precision_arg_index].a.a_int;
2645 /* "A negative precision is taken as if the precision
2655 const FCHAR_T *digitp = dp->precision_start + 1;
2658 while (digitp != dp->precision_end)
2659 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2664 /* POSIX specifies the default precision to be 6 for %f, %F,
2665 %e, %E, but not for %g, %G. Implementations appear to use
2666 the same default precision also for %g, %G. But for %a, %A,
2667 the default precision is 0. */
2669 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
2672 /* Allocate a temporary buffer of sufficient size. */
2673 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2674 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
2675 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2676 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2677 # elif NEED_PRINTF_LONG_DOUBLE
2678 tmp_length = LDBL_DIG + 1;
2679 # elif NEED_PRINTF_DOUBLE
2680 tmp_length = DBL_DIG + 1;
2684 if (tmp_length < precision)
2685 tmp_length = precision;
2686 # if NEED_PRINTF_LONG_DOUBLE
2687 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2688 if (type == TYPE_LONGDOUBLE)
2690 if (dp->conversion == 'f' || dp->conversion == 'F')
2692 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2693 if (!(isnanl (arg) || arg + arg == arg))
2695 /* arg is finite and nonzero. */
2696 int exponent = floorlog10l (arg < 0 ? -arg : arg);
2697 if (exponent >= 0 && tmp_length < exponent + precision)
2698 tmp_length = exponent + precision;
2702 # if NEED_PRINTF_DOUBLE
2703 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2704 if (type == TYPE_DOUBLE)
2706 if (dp->conversion == 'f' || dp->conversion == 'F')
2708 double arg = a.arg[dp->arg_index].a.a_double;
2709 if (!(isnand (arg) || arg + arg == arg))
2711 /* arg is finite and nonzero. */
2712 int exponent = floorlog10 (arg < 0 ? -arg : arg);
2713 if (exponent >= 0 && tmp_length < exponent + precision)
2714 tmp_length = exponent + precision;
2718 /* Account for sign, decimal point etc. */
2719 tmp_length = xsum (tmp_length, 12);
2721 if (tmp_length < width)
2724 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2726 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2730 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2732 if (size_overflow_p (tmp_memsize))
2733 /* Overflow, would lead to out of memory. */
2735 tmp = (DCHAR_T *) malloc (tmp_memsize);
2737 /* Out of memory. */
2744 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2745 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2746 if (type == TYPE_LONGDOUBLE)
2749 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2753 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2755 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2759 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2765 DECL_LONG_DOUBLE_ROUNDING
2767 BEGIN_LONG_DOUBLE_ROUNDING ();
2769 if (signbit (arg)) /* arg < 0.0L or negative zero */
2777 else if (flags & FLAG_SHOWSIGN)
2779 else if (flags & FLAG_SPACE)
2782 if (arg > 0.0L && arg + arg == arg)
2784 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2786 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2790 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2795 # if NEED_PRINTF_LONG_DOUBLE
2798 if (dp->conversion == 'f' || dp->conversion == 'F')
2804 scale10_round_decimal_long_double (arg, precision);
2807 END_LONG_DOUBLE_ROUNDING ();
2810 ndigits = strlen (digits);
2812 if (ndigits > precision)
2816 *p++ = digits[ndigits];
2818 while (ndigits > precision);
2821 /* Here ndigits <= precision. */
2822 if ((flags & FLAG_ALT) || precision > 0)
2824 *p++ = decimal_point_char ();
2825 for (; precision > ndigits; precision--)
2830 *p++ = digits[ndigits];
2836 else if (dp->conversion == 'e' || dp->conversion == 'E')
2844 if ((flags & FLAG_ALT) || precision > 0)
2846 *p++ = decimal_point_char ();
2847 for (; precision > 0; precision--)
2858 exponent = floorlog10l (arg);
2863 scale10_round_decimal_long_double (arg,
2864 (int)precision - exponent);
2867 END_LONG_DOUBLE_ROUNDING ();
2870 ndigits = strlen (digits);
2872 if (ndigits == precision + 1)
2874 if (ndigits < precision
2875 || ndigits > precision + 2)
2876 /* The exponent was not guessed
2877 precisely enough. */
2880 /* None of two values of exponent is
2881 the right one. Prevent an endless
2885 if (ndigits == precision)
2891 /* Here ndigits = precision+1. */
2892 if (is_borderline (digits, precision))
2894 /* Maybe the exponent guess was too high
2895 and a smaller exponent can be reached
2896 by turning a 10...0 into 9...9x. */
2898 scale10_round_decimal_long_double (arg,
2899 (int)precision - exponent + 1);
2900 if (digits2 == NULL)
2903 END_LONG_DOUBLE_ROUNDING ();
2906 if (strlen (digits2) == precision + 1)
2915 /* Here ndigits = precision+1. */
2917 *p++ = digits[--ndigits];
2918 if ((flags & FLAG_ALT) || precision > 0)
2920 *p++ = decimal_point_char ();
2924 *p++ = digits[ndigits];
2931 *p++ = dp->conversion; /* 'e' or 'E' */
2932 # if WIDE_CHAR_VERSION
2934 static const wchar_t decimal_format[] =
2935 { '%', '+', '.', '2', 'd', '\0' };
2936 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2941 if (sizeof (DCHAR_T) == 1)
2943 sprintf ((char *) p, "%+.2d", exponent);
2951 sprintf (expbuf, "%+.2d", exponent);
2952 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2957 else if (dp->conversion == 'g' || dp->conversion == 'G')
2961 /* precision >= 1. */
2964 /* The exponent is 0, >= -4, < precision.
2965 Use fixed-point notation. */
2967 size_t ndigits = precision;
2968 /* Number of trailing zeroes that have to be
2971 (flags & FLAG_ALT ? 0 : precision - 1);
2975 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2977 *p++ = decimal_point_char ();
2978 while (ndigits > nzeroes)
2994 exponent = floorlog10l (arg);
2999 scale10_round_decimal_long_double (arg,
3000 (int)(precision - 1) - exponent);
3003 END_LONG_DOUBLE_ROUNDING ();
3006 ndigits = strlen (digits);
3008 if (ndigits == precision)
3010 if (ndigits < precision - 1
3011 || ndigits > precision + 1)
3012 /* The exponent was not guessed
3013 precisely enough. */
3016 /* None of two values of exponent is
3017 the right one. Prevent an endless
3021 if (ndigits < precision)
3027 /* Here ndigits = precision. */
3028 if (is_borderline (digits, precision - 1))
3030 /* Maybe the exponent guess was too high
3031 and a smaller exponent can be reached
3032 by turning a 10...0 into 9...9x. */
3034 scale10_round_decimal_long_double (arg,
3035 (int)(precision - 1) - exponent + 1);
3036 if (digits2 == NULL)
3039 END_LONG_DOUBLE_ROUNDING ();
3042 if (strlen (digits2) == precision)
3051 /* Here ndigits = precision. */
3053 /* Determine the number of trailing zeroes
3054 that have to be dropped. */
3056 if ((flags & FLAG_ALT) == 0)
3057 while (nzeroes < ndigits
3058 && digits[nzeroes] == '0')
3061 /* The exponent is now determined. */
3063 && exponent < (long)precision)
3065 /* Fixed-point notation:
3066 max(exponent,0)+1 digits, then the
3067 decimal point, then the remaining
3068 digits without trailing zeroes. */
3071 size_t count = exponent + 1;
3072 /* Note: count <= precision = ndigits. */
3073 for (; count > 0; count--)
3074 *p++ = digits[--ndigits];
3075 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3077 *p++ = decimal_point_char ();
3078 while (ndigits > nzeroes)
3081 *p++ = digits[ndigits];
3087 size_t count = -exponent - 1;
3089 *p++ = decimal_point_char ();
3090 for (; count > 0; count--)
3092 while (ndigits > nzeroes)
3095 *p++ = digits[ndigits];
3101 /* Exponential notation. */
3102 *p++ = digits[--ndigits];
3103 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3105 *p++ = decimal_point_char ();
3106 while (ndigits > nzeroes)
3109 *p++ = digits[ndigits];
3112 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3113 # if WIDE_CHAR_VERSION
3115 static const wchar_t decimal_format[] =
3116 { '%', '+', '.', '2', 'd', '\0' };
3117 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3122 if (sizeof (DCHAR_T) == 1)
3124 sprintf ((char *) p, "%+.2d", exponent);
3132 sprintf (expbuf, "%+.2d", exponent);
3133 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3145 /* arg is finite. */
3151 if (dp->conversion == 'f' || dp->conversion == 'F')
3154 if ((flags & FLAG_ALT) || precision > 0)
3156 *p++ = decimal_point_char ();
3157 for (; precision > 0; precision--)
3161 else if (dp->conversion == 'e' || dp->conversion == 'E')
3164 if ((flags & FLAG_ALT) || precision > 0)
3166 *p++ = decimal_point_char ();
3167 for (; precision > 0; precision--)
3170 *p++ = dp->conversion; /* 'e' or 'E' */
3175 else if (dp->conversion == 'g' || dp->conversion == 'G')
3178 if (flags & FLAG_ALT)
3181 (precision > 0 ? precision - 1 : 0);
3182 *p++ = decimal_point_char ();
3183 for (; ndigits > 0; --ndigits)
3187 else if (dp->conversion == 'a' || dp->conversion == 'A')
3190 *p++ = dp->conversion - 'A' + 'X';
3193 if ((flags & FLAG_ALT) || precision > 0)
3195 *p++ = decimal_point_char ();
3196 for (; precision > 0; precision--)
3199 *p++ = dp->conversion - 'A' + 'P';
3208 END_LONG_DOUBLE_ROUNDING ();
3211 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3215 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3217 double arg = a.arg[dp->arg_index].a.a_double;
3221 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3223 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3227 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3234 if (signbit (arg)) /* arg < 0.0 or negative zero */
3242 else if (flags & FLAG_SHOWSIGN)
3244 else if (flags & FLAG_SPACE)
3247 if (arg > 0.0 && arg + arg == arg)
3249 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3251 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3255 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3260 # if NEED_PRINTF_DOUBLE
3263 if (dp->conversion == 'f' || dp->conversion == 'F')
3269 scale10_round_decimal_double (arg, precision);
3272 ndigits = strlen (digits);
3274 if (ndigits > precision)
3278 *p++ = digits[ndigits];
3280 while (ndigits > precision);
3283 /* Here ndigits <= precision. */
3284 if ((flags & FLAG_ALT) || precision > 0)
3286 *p++ = decimal_point_char ();
3287 for (; precision > ndigits; precision--)
3292 *p++ = digits[ndigits];
3298 else if (dp->conversion == 'e' || dp->conversion == 'E')
3306 if ((flags & FLAG_ALT) || precision > 0)
3308 *p++ = decimal_point_char ();
3309 for (; precision > 0; precision--)
3320 exponent = floorlog10 (arg);
3325 scale10_round_decimal_double (arg,
3326 (int)precision - exponent);
3329 ndigits = strlen (digits);
3331 if (ndigits == precision + 1)
3333 if (ndigits < precision
3334 || ndigits > precision + 2)
3335 /* The exponent was not guessed
3336 precisely enough. */
3339 /* None of two values of exponent is
3340 the right one. Prevent an endless
3344 if (ndigits == precision)
3350 /* Here ndigits = precision+1. */
3351 if (is_borderline (digits, precision))
3353 /* Maybe the exponent guess was too high
3354 and a smaller exponent can be reached
3355 by turning a 10...0 into 9...9x. */
3357 scale10_round_decimal_double (arg,
3358 (int)precision - exponent + 1);
3359 if (digits2 == NULL)
3364 if (strlen (digits2) == precision + 1)
3373 /* Here ndigits = precision+1. */
3375 *p++ = digits[--ndigits];
3376 if ((flags & FLAG_ALT) || precision > 0)
3378 *p++ = decimal_point_char ();
3382 *p++ = digits[ndigits];
3389 *p++ = dp->conversion; /* 'e' or 'E' */
3390 # if WIDE_CHAR_VERSION
3392 static const wchar_t decimal_format[] =
3393 /* Produce the same number of exponent digits
3394 as the native printf implementation. */
3395 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3396 { '%', '+', '.', '3', 'd', '\0' };
3398 { '%', '+', '.', '2', 'd', '\0' };
3400 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3406 static const char decimal_format[] =
3407 /* Produce the same number of exponent digits
3408 as the native printf implementation. */
3409 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3414 if (sizeof (DCHAR_T) == 1)
3416 sprintf ((char *) p, decimal_format, exponent);
3424 sprintf (expbuf, decimal_format, exponent);
3425 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3431 else if (dp->conversion == 'g' || dp->conversion == 'G')
3435 /* precision >= 1. */
3438 /* The exponent is 0, >= -4, < precision.
3439 Use fixed-point notation. */
3441 size_t ndigits = precision;
3442 /* Number of trailing zeroes that have to be
3445 (flags & FLAG_ALT ? 0 : precision - 1);
3449 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3451 *p++ = decimal_point_char ();
3452 while (ndigits > nzeroes)
3468 exponent = floorlog10 (arg);
3473 scale10_round_decimal_double (arg,
3474 (int)(precision - 1) - exponent);
3477 ndigits = strlen (digits);
3479 if (ndigits == precision)
3481 if (ndigits < precision - 1
3482 || ndigits > precision + 1)
3483 /* The exponent was not guessed
3484 precisely enough. */
3487 /* None of two values of exponent is
3488 the right one. Prevent an endless
3492 if (ndigits < precision)
3498 /* Here ndigits = precision. */
3499 if (is_borderline (digits, precision - 1))
3501 /* Maybe the exponent guess was too high
3502 and a smaller exponent can be reached
3503 by turning a 10...0 into 9...9x. */
3505 scale10_round_decimal_double (arg,
3506 (int)(precision - 1) - exponent + 1);
3507 if (digits2 == NULL)
3512 if (strlen (digits2) == precision)
3521 /* Here ndigits = precision. */
3523 /* Determine the number of trailing zeroes
3524 that have to be dropped. */
3526 if ((flags & FLAG_ALT) == 0)
3527 while (nzeroes < ndigits
3528 && digits[nzeroes] == '0')
3531 /* The exponent is now determined. */
3533 && exponent < (long)precision)
3535 /* Fixed-point notation:
3536 max(exponent,0)+1 digits, then the
3537 decimal point, then the remaining
3538 digits without trailing zeroes. */
3541 size_t count = exponent + 1;
3542 /* Note: count <= precision = ndigits. */
3543 for (; count > 0; count--)
3544 *p++ = digits[--ndigits];
3545 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3547 *p++ = decimal_point_char ();
3548 while (ndigits > nzeroes)
3551 *p++ = digits[ndigits];
3557 size_t count = -exponent - 1;
3559 *p++ = decimal_point_char ();
3560 for (; count > 0; count--)
3562 while (ndigits > nzeroes)
3565 *p++ = digits[ndigits];
3571 /* Exponential notation. */
3572 *p++ = digits[--ndigits];
3573 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3575 *p++ = decimal_point_char ();
3576 while (ndigits > nzeroes)
3579 *p++ = digits[ndigits];
3582 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3583 # if WIDE_CHAR_VERSION
3585 static const wchar_t decimal_format[] =
3586 /* Produce the same number of exponent digits
3587 as the native printf implementation. */
3588 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3589 { '%', '+', '.', '3', 'd', '\0' };
3591 { '%', '+', '.', '2', 'd', '\0' };
3593 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3599 static const char decimal_format[] =
3600 /* Produce the same number of exponent digits
3601 as the native printf implementation. */
3602 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3607 if (sizeof (DCHAR_T) == 1)
3609 sprintf ((char *) p, decimal_format, exponent);
3617 sprintf (expbuf, decimal_format, exponent);
3618 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3631 /* arg is finite. */
3637 if (dp->conversion == 'f' || dp->conversion == 'F')
3640 if ((flags & FLAG_ALT) || precision > 0)
3642 *p++ = decimal_point_char ();
3643 for (; precision > 0; precision--)
3647 else if (dp->conversion == 'e' || dp->conversion == 'E')
3650 if ((flags & FLAG_ALT) || precision > 0)
3652 *p++ = decimal_point_char ();
3653 for (; precision > 0; precision--)
3656 *p++ = dp->conversion; /* 'e' or 'E' */
3658 /* Produce the same number of exponent digits as
3659 the native printf implementation. */
3660 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3666 else if (dp->conversion == 'g' || dp->conversion == 'G')
3669 if (flags & FLAG_ALT)
3672 (precision > 0 ? precision - 1 : 0);
3673 *p++ = decimal_point_char ();
3674 for (; ndigits > 0; --ndigits)
3686 /* The generated string now extends from tmp to p, with the
3687 zero padding insertion point being at pad_ptr. */
3688 if (has_width && p - tmp < width)
3690 size_t pad = width - (p - tmp);
3691 DCHAR_T *end = p + pad;
3693 if (flags & FLAG_LEFT)
3695 /* Pad with spaces on the right. */
3696 for (; pad > 0; pad--)
3699 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3701 /* Pad with zeroes. */
3706 for (; pad > 0; pad--)
3711 /* Pad with spaces on the left. */
3716 for (; pad > 0; pad--)
3724 size_t count = p - tmp;
3726 if (count >= tmp_length)
3727 /* tmp_length was incorrectly calculated - fix the
3731 /* Make room for the result. */
3732 if (count >= allocated - length)
3734 size_t n = xsum (length, count);
3736 ENSURE_ALLOCATION (n);
3739 /* Append the result. */
3740 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3749 arg_type type = a.arg[dp->arg_index].type;
3750 int flags = dp->flags;
3751 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3755 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3759 #if NEED_PRINTF_UNBOUNDED_PRECISION
3762 # define prec_ourselves 0
3764 #if NEED_PRINTF_FLAG_LEFTADJUST
3765 # define pad_ourselves 1
3766 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3769 # define pad_ourselves 0
3772 unsigned int prefix_count;
3773 int prefixes[2] IF_LINT (= { 0 });
3776 TCHAR_T tmpbuf[700];
3780 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3783 if (dp->width_start != dp->width_end)
3785 if (dp->width_arg_index != ARG_NONE)
3789 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3791 arg = a.arg[dp->width_arg_index].a.a_int;
3794 /* "A negative field width is taken as a '-' flag
3795 followed by a positive field width." */
3797 width = (unsigned int) (-arg);
3804 const FCHAR_T *digitp = dp->width_start;
3807 width = xsum (xtimes (width, 10), *digitp++ - '0');
3808 while (digitp != dp->width_end);
3814 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3817 if (dp->precision_start != dp->precision_end)
3819 if (dp->precision_arg_index != ARG_NONE)
3823 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3825 arg = a.arg[dp->precision_arg_index].a.a_int;
3826 /* "A negative precision is taken as if the precision
3836 const FCHAR_T *digitp = dp->precision_start + 1;
3839 while (digitp != dp->precision_end)
3840 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3846 /* Decide whether to handle the precision ourselves. */
3847 #if NEED_PRINTF_UNBOUNDED_PRECISION
3848 switch (dp->conversion)
3850 case 'd': case 'i': case 'u':
3852 case 'x': case 'X': case 'p':
3853 prec_ourselves = has_precision && (precision > 0);
3861 /* Decide whether to perform the padding ourselves. */
3862 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
3863 switch (dp->conversion)
3865 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
3866 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
3867 to perform the padding after this conversion. Functions
3868 with unistdio extensions perform the padding based on
3869 character count rather than element count. */
3872 # if NEED_PRINTF_FLAG_ZERO
3873 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
3879 pad_ourselves = prec_ourselves;
3885 /* Allocate a temporary buffer of sufficient size for calling
3888 switch (dp->conversion)
3891 case 'd': case 'i': case 'u':
3892 # if HAVE_LONG_LONG_INT
3893 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3895 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3896 * 0.30103 /* binary -> decimal */
3898 + 1; /* turn floor into ceil */
3901 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3903 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3904 * 0.30103 /* binary -> decimal */
3906 + 1; /* turn floor into ceil */
3909 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3910 * 0.30103 /* binary -> decimal */
3912 + 1; /* turn floor into ceil */
3913 if (tmp_length < precision)
3914 tmp_length = precision;
3915 /* Multiply by 2, as an estimate for FLAG_GROUP. */
3916 tmp_length = xsum (tmp_length, tmp_length);
3917 /* Add 1, to account for a leading sign. */
3918 tmp_length = xsum (tmp_length, 1);
3922 # if HAVE_LONG_LONG_INT
3923 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3925 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3926 * 0.333334 /* binary -> octal */
3928 + 1; /* turn floor into ceil */
3931 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3933 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3934 * 0.333334 /* binary -> octal */
3936 + 1; /* turn floor into ceil */
3939 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3940 * 0.333334 /* binary -> octal */
3942 + 1; /* turn floor into ceil */
3943 if (tmp_length < precision)
3944 tmp_length = precision;
3945 /* Add 1, to account for a leading sign. */
3946 tmp_length = xsum (tmp_length, 1);
3950 # if HAVE_LONG_LONG_INT
3951 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3953 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3954 * 0.25 /* binary -> hexadecimal */
3956 + 1; /* turn floor into ceil */
3959 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3961 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3962 * 0.25 /* binary -> hexadecimal */
3964 + 1; /* turn floor into ceil */
3967 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3968 * 0.25 /* binary -> hexadecimal */
3970 + 1; /* turn floor into ceil */
3971 if (tmp_length < precision)
3972 tmp_length = precision;
3973 /* Add 2, to account for a leading sign or alternate form. */
3974 tmp_length = xsum (tmp_length, 2);
3978 if (type == TYPE_LONGDOUBLE)
3980 (unsigned int) (LDBL_MAX_EXP
3981 * 0.30103 /* binary -> decimal */
3982 * 2 /* estimate for FLAG_GROUP */
3984 + 1 /* turn floor into ceil */
3985 + 10; /* sign, decimal point etc. */
3988 (unsigned int) (DBL_MAX_EXP
3989 * 0.30103 /* binary -> decimal */
3990 * 2 /* estimate for FLAG_GROUP */
3992 + 1 /* turn floor into ceil */
3993 + 10; /* sign, decimal point etc. */
3994 tmp_length = xsum (tmp_length, precision);
3997 case 'e': case 'E': case 'g': case 'G':
3999 12; /* sign, decimal point, exponent etc. */
4000 tmp_length = xsum (tmp_length, precision);
4004 if (type == TYPE_LONGDOUBLE)
4006 (unsigned int) (LDBL_DIG
4007 * 0.831 /* decimal -> hexadecimal */
4009 + 1; /* turn floor into ceil */
4012 (unsigned int) (DBL_DIG
4013 * 0.831 /* decimal -> hexadecimal */
4015 + 1; /* turn floor into ceil */
4016 if (tmp_length < precision)
4017 tmp_length = precision;
4018 /* Account for sign, decimal point etc. */
4019 tmp_length = xsum (tmp_length, 12);
4023 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
4024 if (type == TYPE_WIDE_CHAR)
4025 tmp_length = MB_CUR_MAX;
4033 if (type == TYPE_WIDE_STRING)
4036 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
4038 # if !WIDE_CHAR_VERSION
4039 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
4044 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
4049 (unsigned int) (sizeof (void *) * CHAR_BIT
4050 * 0.25 /* binary -> hexadecimal */
4052 + 1 /* turn floor into ceil */
4053 + 2; /* account for leading 0x */
4062 # if ENABLE_UNISTDIO
4063 /* Padding considers the number of characters, therefore
4064 the number of elements after padding may be
4065 > max (tmp_length, width)
4067 <= tmp_length + width. */
4068 tmp_length = xsum (tmp_length, width);
4070 /* Padding considers the number of elements,
4072 if (tmp_length < width)
4077 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
4080 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4084 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4086 if (size_overflow_p (tmp_memsize))
4087 /* Overflow, would lead to out of memory. */
4089 tmp = (TCHAR_T *) malloc (tmp_memsize);
4091 /* Out of memory. */
4096 /* Construct the format string for calling snprintf or
4100 #if NEED_PRINTF_FLAG_GROUPING
4101 /* The underlying implementation doesn't support the ' flag.
4102 Produce no grouping characters in this case; this is
4103 acceptable because the grouping is locale dependent. */
4105 if (flags & FLAG_GROUP)
4108 if (flags & FLAG_LEFT)
4110 if (flags & FLAG_SHOWSIGN)
4112 if (flags & FLAG_SPACE)
4114 if (flags & FLAG_ALT)
4118 if (flags & FLAG_ZERO)
4120 if (dp->width_start != dp->width_end)
4122 size_t n = dp->width_end - dp->width_start;
4123 /* The width specification is known to consist only
4124 of standard ASCII characters. */
4125 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4127 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4132 const FCHAR_T *mp = dp->width_start;
4134 *fbp++ = (unsigned char) *mp++;
4139 if (!prec_ourselves)
4141 if (dp->precision_start != dp->precision_end)
4143 size_t n = dp->precision_end - dp->precision_start;
4144 /* The precision specification is known to consist only
4145 of standard ASCII characters. */
4146 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4148 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4153 const FCHAR_T *mp = dp->precision_start;
4155 *fbp++ = (unsigned char) *mp++;
4163 #if HAVE_LONG_LONG_INT
4164 case TYPE_LONGLONGINT:
4165 case TYPE_ULONGLONGINT:
4166 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4179 case TYPE_WIDE_CHAR:
4182 case TYPE_WIDE_STRING:
4186 case TYPE_LONGDOUBLE:
4192 #if NEED_PRINTF_DIRECTIVE_F
4193 if (dp->conversion == 'F')
4197 *fbp = dp->conversion;
4199 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4204 /* On glibc2 systems from glibc >= 2.3 - probably also older
4205 ones - we know that snprintf's returns value conforms to
4206 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4207 Therefore we can avoid using %n in this situation.
4208 On glibc2 systems from 2004-10-18 or newer, the use of %n
4209 in format strings in writable memory may crash the program
4210 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4211 in this situation. */
4212 /* On native Win32 systems (such as mingw), we can avoid using
4214 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4215 snprintf does not write more than the specified number
4216 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4217 '4', '5', '6' into buf, not '4', '5', '\0'.)
4218 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4219 allows us to recognize the case of an insufficient
4220 buffer size: it returns -1 in this case.
4221 On native Win32 systems (such as mingw) where the OS is
4222 Windows Vista, the use of %n in format strings by default
4223 crashes the program. See
4224 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4225 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4226 So we should avoid %n in this situation. */
4233 /* Construct the arguments for calling snprintf or sprintf. */
4235 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4237 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4239 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4241 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4243 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4245 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4249 /* The SNPRINTF result is appended after result[0..length].
4250 The latter is an array of DCHAR_T; SNPRINTF appends an
4251 array of TCHAR_T to it. This is possible because
4252 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4253 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4254 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4255 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4256 where an snprintf() with maxlen==1 acts like sprintf(). */
4257 ENSURE_ALLOCATION (xsum (length,
4258 (2 + TCHARS_PER_DCHAR - 1)
4259 / TCHARS_PER_DCHAR));
4260 /* Prepare checking whether snprintf returns the count
4262 *(TCHAR_T *) (result + length) = '\0';
4271 size_t maxlen = allocated - length;
4272 /* SNPRINTF can fail if its second argument is
4274 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4275 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4276 maxlen = maxlen * TCHARS_PER_DCHAR;
4277 # define SNPRINTF_BUF(arg) \
4278 switch (prefix_count) \
4281 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4286 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4288 prefixes[0], arg, &count); \
4291 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4293 prefixes[0], prefixes[1], arg, \
4300 # define SNPRINTF_BUF(arg) \
4301 switch (prefix_count) \
4304 count = sprintf (tmp, buf, arg); \
4307 count = sprintf (tmp, buf, prefixes[0], arg); \
4310 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4322 int arg = a.arg[dp->arg_index].a.a_schar;
4328 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4334 int arg = a.arg[dp->arg_index].a.a_short;
4340 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4346 int arg = a.arg[dp->arg_index].a.a_int;
4352 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4358 long int arg = a.arg[dp->arg_index].a.a_longint;
4364 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4368 #if HAVE_LONG_LONG_INT
4369 case TYPE_LONGLONGINT:
4371 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4375 case TYPE_ULONGLONGINT:
4377 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4384 double arg = a.arg[dp->arg_index].a.a_double;
4388 case TYPE_LONGDOUBLE:
4390 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4396 int arg = a.arg[dp->arg_index].a.a_char;
4401 case TYPE_WIDE_CHAR:
4403 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
4410 const char *arg = a.arg[dp->arg_index].a.a_string;
4415 case TYPE_WIDE_STRING:
4417 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
4424 void *arg = a.arg[dp->arg_index].a.a_pointer;
4433 /* Portability: Not all implementations of snprintf()
4434 are ISO C 99 compliant. Determine the number of
4435 bytes that snprintf() has produced or would have
4439 /* Verify that snprintf() has NUL-terminated its
4442 && ((TCHAR_T *) (result + length)) [count] != '\0')
4444 /* Portability hack. */
4445 if (retcount > count)
4450 /* snprintf() doesn't understand the '%n'
4454 /* Don't use the '%n' directive; instead, look
4455 at the snprintf() return value. */
4461 /* Look at the snprintf() return value. */
4464 /* HP-UX 10.20 snprintf() is doubly deficient:
4465 It doesn't understand the '%n' directive,
4466 *and* it returns -1 (rather than the length
4467 that would have been required) when the
4468 buffer is too small. */
4469 size_t bigger_need =
4470 xsum (xtimes (allocated, 2), 12);
4471 ENSURE_ALLOCATION (bigger_need);
4480 /* Attempt to handle failure. */
4483 if (!(result == resultbuf || result == NULL))
4485 if (buf_malloced != NULL)
4486 free (buf_malloced);
4493 /* Handle overflow of the allocated buffer.
4494 If such an overflow occurs, a C99 compliant snprintf()
4495 returns a count >= maxlen. However, a non-compliant
4496 snprintf() function returns only count = maxlen - 1. To
4497 cover both cases, test whether count >= maxlen - 1. */
4498 if ((unsigned int) count + 1 >= maxlen)
4500 /* If maxlen already has attained its allowed maximum,
4501 allocating more memory will not increase maxlen.
4502 Instead of looping, bail out. */
4503 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
4507 /* Need at least (count + 1) * sizeof (TCHAR_T)
4508 bytes. (The +1 is for the trailing NUL.)
4509 But ask for (count + 2) * sizeof (TCHAR_T)
4510 bytes, so that in the next round, we likely get
4511 maxlen > (unsigned int) count + 1
4512 and so we don't get here again.
4513 And allocate proportionally, to avoid looping
4514 eternally if snprintf() reports a too small
4518 ((unsigned int) count + 2
4519 + TCHARS_PER_DCHAR - 1)
4520 / TCHARS_PER_DCHAR),
4521 xtimes (allocated, 2));
4523 ENSURE_ALLOCATION (n);
4529 #if NEED_PRINTF_UNBOUNDED_PRECISION
4532 /* Handle the precision. */
4535 (TCHAR_T *) (result + length);
4539 size_t prefix_count;
4543 /* Put the additional zeroes after the sign. */
4545 && (*prec_ptr == '-' || *prec_ptr == '+'
4546 || *prec_ptr == ' '))
4548 /* Put the additional zeroes after the 0x prefix if
4549 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
4551 && prec_ptr[0] == '0'
4552 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
4555 move = count - prefix_count;
4556 if (precision > move)
4558 /* Insert zeroes. */
4559 size_t insert = precision - move;
4565 (count + insert + TCHARS_PER_DCHAR - 1)
4566 / TCHARS_PER_DCHAR);
4567 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4568 ENSURE_ALLOCATION (n);
4569 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4570 prec_ptr = (TCHAR_T *) (result + length);
4573 prec_end = prec_ptr + count;
4574 prec_ptr += prefix_count;
4576 while (prec_end > prec_ptr)
4579 prec_end[insert] = prec_end[0];
4585 while (prec_end > prec_ptr);
4593 if (count >= tmp_length)
4594 /* tmp_length was incorrectly calculated - fix the
4600 /* Convert from TCHAR_T[] to DCHAR_T[]. */
4601 if (dp->conversion == 'c' || dp->conversion == 's')
4603 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
4605 The result string is not certainly ASCII. */
4606 const TCHAR_T *tmpsrc;
4609 /* This code assumes that TCHAR_T is 'char'. */
4610 typedef int TCHAR_T_verify
4611 [2 * (sizeof (TCHAR_T) == 1) - 1];
4613 tmpsrc = (TCHAR_T *) (result + length);
4619 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
4620 iconveh_question_mark,
4623 &tmpdst, &tmpdst_len)
4626 int saved_errno = errno;
4627 if (!(result == resultbuf || result == NULL))
4629 if (buf_malloced != NULL)
4630 free (buf_malloced);
4632 errno = saved_errno;
4635 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
4636 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
4642 /* The result string is ASCII.
4643 Simple 1:1 conversion. */
4645 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
4646 no-op conversion, in-place on the array starting
4647 at (result + length). */
4648 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
4651 const TCHAR_T *tmpsrc;
4656 if (result == resultbuf)
4658 tmpsrc = (TCHAR_T *) (result + length);
4659 /* ENSURE_ALLOCATION will not move tmpsrc
4660 (because it's part of resultbuf). */
4661 ENSURE_ALLOCATION (xsum (length, count));
4665 /* ENSURE_ALLOCATION will move the array
4666 (because it uses realloc(). */
4667 ENSURE_ALLOCATION (xsum (length, count));
4668 tmpsrc = (TCHAR_T *) (result + length);
4672 ENSURE_ALLOCATION (xsum (length, count));
4674 tmpdst = result + length;
4675 /* Copy backwards, because of overlapping. */
4678 for (n = count; n > 0; n--)
4679 *--tmpdst = (unsigned char) *--tmpsrc;
4684 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4685 /* Make room for the result. */
4686 if (count > allocated - length)
4688 /* Need at least count elements. But allocate
4691 xmax (xsum (length, count), xtimes (allocated, 2));
4693 ENSURE_ALLOCATION (n);
4697 /* Here count <= allocated - length. */
4699 /* Perform padding. */
4700 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4701 if (pad_ourselves && has_width)
4704 # if ENABLE_UNISTDIO
4705 /* Outside POSIX, it's preferrable to compare the width
4706 against the number of _characters_ of the converted
4708 w = DCHAR_MBSNLEN (result + length, count);
4710 /* The width is compared against the number of _bytes_
4711 of the converted value, says POSIX. */
4716 size_t pad = width - w;
4718 /* Make room for the result. */
4719 if (xsum (count, pad) > allocated - length)
4721 /* Need at least count + pad elements. But
4722 allocate proportionally. */
4724 xmax (xsum3 (length, count, pad),
4725 xtimes (allocated, 2));
4729 ENSURE_ALLOCATION (n);
4732 ENSURE_ALLOCATION (n);
4735 /* Here count + pad <= allocated - length. */
4738 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
4739 DCHAR_T * const rp = result + length;
4741 DCHAR_T * const rp = tmp;
4743 DCHAR_T *p = rp + count;
4744 DCHAR_T *end = p + pad;
4746 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4747 if (dp->conversion == 'c'
4748 || dp->conversion == 's')
4749 /* No zero-padding for string directives. */
4754 pad_ptr = (*rp == '-' ? rp + 1 : rp);
4755 /* No zero-padding of "inf" and "nan". */
4756 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
4757 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
4760 /* The generated string now extends from rp to p,
4761 with the zero padding insertion point being at
4764 count = count + pad; /* = end - rp */
4766 if (flags & FLAG_LEFT)
4768 /* Pad with spaces on the right. */
4769 for (; pad > 0; pad--)
4772 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4774 /* Pad with zeroes. */
4779 for (; pad > 0; pad--)
4784 /* Pad with spaces on the left. */
4789 for (; pad > 0; pad--)
4797 /* Here still count <= allocated - length. */
4799 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
4800 /* The snprintf() result did fit. */
4802 /* Append the sprintf() result. */
4803 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4810 #if NEED_PRINTF_DIRECTIVE_F
4811 if (dp->conversion == 'F')
4813 /* Convert the %f result to upper case for %F. */
4814 DCHAR_T *rp = result + length;
4816 for (rc = count; rc > 0; rc--, rp++)
4817 if (*rp >= 'a' && *rp <= 'z')
4818 *rp = *rp - 'a' + 'A';
4829 /* Add the final NUL. */
4830 ENSURE_ALLOCATION (xsum (length, 1));
4831 result[length] = '\0';
4833 if (result != resultbuf && length + 1 < allocated)
4835 /* Shrink the allocated memory if possible. */
4838 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
4843 if (buf_malloced != NULL)
4844 free (buf_malloced);
4847 /* Note that we can produce a big string of a length > INT_MAX. POSIX
4848 says that snprintf() fails with errno = EOVERFLOW in this case, but
4849 that's only because snprintf() returns an 'int'. This function does
4850 not have this limitation. */
4855 if (!(result == resultbuf || result == NULL))
4857 if (buf_malloced != NULL)
4858 free (buf_malloced);
4865 if (!(result == resultbuf || result == NULL))
4867 if (buf_malloced != NULL)
4868 free (buf_malloced);
4876 #undef TCHARS_PER_DCHAR
4883 #undef DCHAR_IS_TCHAR