1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* vsprintf with automatic memory allocation.
4 Copyright (C) 1999, 2002-2013 Free Software Foundation, Inc.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, see <http://www.gnu.org/licenses/>. */
19 /* This file can be parametrized with the following macros:
20 VASNPRINTF The name of the function being defined.
21 FCHAR_T The element type of the format string.
22 DCHAR_T The element type of the destination (result) string.
23 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
24 in the format string are ASCII. MUST be set if
25 FCHAR_T and DCHAR_T are not the same type.
26 DIRECTIVE Structure denoting a format directive.
28 DIRECTIVES Structure denoting the set of format directives of a
29 format string. Depends on FCHAR_T.
30 PRINTF_PARSE Function that parses a format string.
32 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
33 DCHAR_SET memset like function for DCHAR_T[] arrays.
34 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
35 SNPRINTF The system's snprintf (or similar) function.
36 This may be either snprintf or swprintf.
37 TCHAR_T The element type of the argument and result string
38 of the said SNPRINTF function. This may be either
39 char or wchar_t. The code exploits that
40 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
41 alignof (TCHAR_T) <= alignof (DCHAR_T).
42 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
43 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
44 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
45 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
46 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
48 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
49 This must come before <config.h> because <config.h> may include
50 <features.h>, and once <features.h> has been included, it's too late. */
52 # define _GNU_SOURCE 1
64 # if WIDE_CHAR_VERSION
65 # include "vasnwprintf.h"
67 # include "vasnprintf.h"
71 #include <locale.h> /* localeconv() */
72 #include <stdio.h> /* snprintf(), sprintf() */
73 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
74 #include <string.h> /* memcpy(), strlen() */
75 #include <errno.h> /* errno */
76 #include <limits.h> /* CHAR_BIT */
77 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
79 # include <langinfo.h>
82 # if WIDE_CHAR_VERSION
83 # include "wprintf-parse.h"
85 # include "printf-parse.h"
89 /* Checked size_t computations. */
94 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
99 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
101 # include "isnand-nolibm.h"
104 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
106 # include "isnanl-nolibm.h"
110 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
112 # include "isnand-nolibm.h"
113 # include "printf-frexp.h"
116 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
118 # include "isnanl-nolibm.h"
119 # include "printf-frexpl.h"
123 /* Default parameters. */
125 # if WIDE_CHAR_VERSION
126 # define VASNPRINTF vasnwprintf
127 # define FCHAR_T wchar_t
128 # define DCHAR_T wchar_t
129 # define TCHAR_T wchar_t
130 # define DCHAR_IS_TCHAR 1
131 # define DIRECTIVE wchar_t_directive
132 # define DIRECTIVES wchar_t_directives
133 # define PRINTF_PARSE wprintf_parse
134 # define DCHAR_CPY wmemcpy
135 # define DCHAR_SET wmemset
137 # define VASNPRINTF vasnprintf
138 # define FCHAR_T char
139 # define DCHAR_T char
140 # define TCHAR_T char
141 # define DCHAR_IS_TCHAR 1
142 # define DIRECTIVE char_directive
143 # define DIRECTIVES char_directives
144 # define PRINTF_PARSE printf_parse
145 # define DCHAR_CPY memcpy
146 # define DCHAR_SET memset
149 #if WIDE_CHAR_VERSION
150 /* TCHAR_T is wchar_t. */
151 # define USE_SNPRINTF 1
152 # if HAVE_DECL__SNWPRINTF
153 /* On Windows, the function swprintf() has a different signature than
154 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
155 instead. The mingw function snwprintf() has fewer bugs than the
156 MSVCRT function _snwprintf(), so prefer that. */
157 # if defined __MINGW32__
158 # define SNPRINTF snwprintf
160 # define SNPRINTF _snwprintf
164 # define SNPRINTF swprintf
167 /* TCHAR_T is char. */
168 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
169 But don't use it on BeOS, since BeOS snprintf produces no output if the
170 size argument is >= 0x3000000.
171 Also don't use it on Linux libc5, since there snprintf with size = 1
172 writes any output without bounds, like sprintf. */
173 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
174 # define USE_SNPRINTF 1
176 # define USE_SNPRINTF 0
178 # if HAVE_DECL__SNPRINTF
179 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
180 function _snprintf(), so prefer that. */
181 # if defined __MINGW32__
182 # define SNPRINTF snprintf
183 /* Here we need to call the native snprintf, not rpl_snprintf. */
186 # define SNPRINTF _snprintf
190 # define SNPRINTF snprintf
191 /* Here we need to call the native snprintf, not rpl_snprintf. */
195 /* Here we need to call the native sprintf, not rpl_sprintf. */
198 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
199 warnings in this file. Use -Dlint to suppress them. */
201 # define IF_LINT(Code) Code
203 # define IF_LINT(Code) /* empty */
206 /* Avoid some warnings from "gcc -Wshadow".
207 This file doesn't use the exp() and remainder() functions. */
211 #define remainder rem
213 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && !WIDE_CHAR_VERSION
214 # if (HAVE_STRNLEN && !defined _AIX)
215 # define local_strnlen strnlen
217 # ifndef local_strnlen_defined
218 # define local_strnlen_defined 1
220 local_strnlen (const char *string, size_t maxlen)
222 const char *end = memchr (string, '\0', maxlen);
223 return end ? (size_t) (end - string) : maxlen;
229 #if (((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && WIDE_CHAR_VERSION) || ((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && !WIDE_CHAR_VERSION && DCHAR_IS_TCHAR)) && HAVE_WCHAR_T
231 # define local_wcslen wcslen
233 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
234 a dependency towards this library, here is a local substitute.
235 Define this substitute only once, even if this file is included
236 twice in the same compilation unit. */
237 # ifndef local_wcslen_defined
238 # define local_wcslen_defined 1
240 local_wcslen (const wchar_t *s)
244 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
252 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
254 # define local_wcsnlen wcsnlen
256 # ifndef local_wcsnlen_defined
257 # define local_wcsnlen_defined 1
259 local_wcsnlen (const wchar_t *s, size_t maxlen)
263 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
271 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
272 /* Determine the decimal-point character according to the current locale. */
273 # ifndef decimal_point_char_defined
274 # define decimal_point_char_defined 1
276 decimal_point_char (void)
279 /* Determine it in a multithread-safe way. We know nl_langinfo is
280 multithread-safe on glibc systems and Mac OS X systems, but is not required
281 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
282 localeconv() is rarely multithread-safe. */
283 # if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
284 point = nl_langinfo (RADIXCHAR);
287 sprintf (pointbuf, "%#.0f", 1.0);
288 point = &pointbuf[1];
290 point = localeconv () -> decimal_point;
292 /* The decimal point is always a single byte: either '.' or ','. */
293 return (point[0] != '\0' ? point[0] : '.');
298 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
300 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
302 is_infinite_or_zero (double x)
304 return isnand (x) || x + x == x;
309 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
311 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
313 is_infinite_or_zerol (long double x)
315 return isnanl (x) || x + x == x;
320 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
322 /* Converting 'long double' to decimal without rare rounding bugs requires
323 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
324 (and slower) algorithms. */
326 typedef unsigned int mp_limb_t;
327 # define GMP_LIMB_BITS 32
328 verify (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS);
330 typedef unsigned long long mp_twolimb_t;
331 # define GMP_TWOLIMB_BITS 64
332 verify (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS);
334 /* Representation of a bignum >= 0. */
338 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
341 /* Compute the product of two bignums >= 0.
342 Return the allocated memory in case of success, NULL in case of memory
343 allocation failure. */
345 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
352 if (src1.nlimbs <= src2.nlimbs)
366 /* Now 0 <= len1 <= len2. */
369 /* src1 or src2 is zero. */
371 dest->limbs = (mp_limb_t *) malloc (1);
375 /* Here 1 <= len1 <= len2. */
381 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
384 for (k = len2; k > 0; )
386 for (i = 0; i < len1; i++)
388 mp_limb_t digit1 = p1[i];
389 mp_twolimb_t carry = 0;
390 for (j = 0; j < len2; j++)
392 mp_limb_t digit2 = p2[j];
393 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
395 dp[i + j] = (mp_limb_t) carry;
396 carry = carry >> GMP_LIMB_BITS;
398 dp[i + len2] = (mp_limb_t) carry;
401 while (dlen > 0 && dp[dlen - 1] == 0)
409 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
410 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
412 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
414 Return the allocated memory in case of success, NULL in case of memory
415 allocation failure. */
417 divide (mpn_t a, mpn_t b, mpn_t *q)
420 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
421 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
422 If m<n, then q:=0 and r:=a.
423 If m>=n=1, perform a single-precision division:
426 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
427 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
428 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
429 Normalise [q[m-1],...,q[0]], yields q.
430 If m>=n>1, perform a multiple-precision division:
431 We have a/b < beta^(m-n+1).
432 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
433 Shift a and b left by s bits, copying them. r:=a.
434 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
435 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
437 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
438 In case of overflow (q* >= beta) set q* := beta-1.
439 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
440 and c3 := b[n-2] * q*.
441 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
442 occurred. Furthermore 0 <= c3 < beta^2.
443 If there was overflow and
444 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
445 the next test can be skipped.}
446 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
447 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
449 Put r := r - b * q* * beta^j. In detail:
450 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
451 hence: u:=0, for i:=0 to n-1 do
453 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
454 u:=u div beta (+ 1, if carry in subtraction)
456 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
458 the carry u does not overflow.}
459 If a negative carry occurs, put q* := q* - 1
460 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
462 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
463 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
465 The room for q[j] can be allocated at the memory location of r[n+j].
466 Finally, round-to-even:
467 Shift r left by 1 bit.
468 If r > b or if r = b and q[0] is odd, q := q+1.
470 const mp_limb_t *a_ptr = a.limbs;
471 size_t a_len = a.nlimbs;
472 const mp_limb_t *b_ptr = b.limbs;
473 size_t b_len = b.nlimbs;
475 mp_limb_t *tmp_roomptr = NULL;
481 /* Allocate room for a_len+2 digits.
482 (Need a_len+1 digits for the real division and 1 more digit for the
483 final rounding of q.) */
484 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
489 while (a_len > 0 && a_ptr[a_len - 1] == 0)
496 /* Division by zero. */
498 if (b_ptr[b_len - 1] == 0)
504 /* Here m = a_len >= 0 and n = b_len > 0. */
508 /* m<n: trivial case. q=0, r := copy of a. */
511 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
512 q_ptr = roomptr + a_len;
517 /* n=1: single precision division.
518 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
522 mp_limb_t den = b_ptr[0];
523 mp_limb_t remainder = 0;
524 const mp_limb_t *sourceptr = a_ptr + a_len;
525 mp_limb_t *destptr = q_ptr + a_len;
527 for (count = a_len; count > 0; count--)
530 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
531 *--destptr = num / den;
532 remainder = num % den;
534 /* Normalise and store r. */
537 r_ptr[0] = remainder;
544 if (q_ptr[q_len - 1] == 0)
550 /* n>1: multiple precision division.
551 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
552 beta^(m-n-1) <= a/b < beta^(m-n+1). */
556 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
557 /* Determine s = GMP_LIMB_BITS - integer_length (msd).
558 Code copied from gnulib's integer_length.c. */
559 # if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
560 s = __builtin_clz (msd);
562 # if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT
563 if (GMP_LIMB_BITS <= DBL_MANT_BIT)
565 /* Use 'double' operations.
566 Assumes an IEEE 754 'double' implementation. */
567 # define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)
568 # define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1)
570 ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
571 union { double value; unsigned int word[NWORDS]; } m;
573 /* Use a single integer to floating-point conversion. */
577 - (((m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK)
613 /* 0 <= s < GMP_LIMB_BITS.
614 Copy b, shifting it left by s bits. */
617 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
618 if (tmp_roomptr == NULL)
624 const mp_limb_t *sourceptr = b_ptr;
625 mp_limb_t *destptr = tmp_roomptr;
626 mp_twolimb_t accu = 0;
628 for (count = b_len; count > 0; count--)
630 accu += (mp_twolimb_t) *sourceptr++ << s;
631 *destptr++ = (mp_limb_t) accu;
632 accu = accu >> GMP_LIMB_BITS;
634 /* accu must be zero, since that was how s was determined. */
640 /* Copy a, shifting it left by s bits, yields r.
642 At the beginning: r = roomptr[0..a_len],
643 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
647 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
652 const mp_limb_t *sourceptr = a_ptr;
653 mp_limb_t *destptr = r_ptr;
654 mp_twolimb_t accu = 0;
656 for (count = a_len; count > 0; count--)
658 accu += (mp_twolimb_t) *sourceptr++ << s;
659 *destptr++ = (mp_limb_t) accu;
660 accu = accu >> GMP_LIMB_BITS;
662 *destptr++ = (mp_limb_t) accu;
664 q_ptr = roomptr + b_len;
665 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
667 size_t j = a_len - b_len; /* m-n */
668 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
669 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
670 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
671 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
672 /* Division loop, traversed m-n+1 times.
673 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
678 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
680 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
682 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
683 | r_ptr[j + b_len - 1];
684 q_star = num / b_msd;
689 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
690 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
691 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
692 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
693 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
695 If yes, jump directly to the subtraction loop.
696 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
697 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
698 if (r_ptr[j + b_len] > b_msd
699 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
700 /* r[j+n] >= b[n-1]+1 or
701 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
706 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
708 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
709 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
710 mp_twolimb_t c3 = /* b[n-2] * q* */
711 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
712 /* While c2 < c3, increase c2 and decrease c3.
713 Consider c3-c2. While it is > 0, decrease it by
714 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
715 this can happen only twice. */
718 q_star = q_star - 1; /* q* := q* - 1 */
719 if (c3 - c2 > b_msdd)
720 q_star = q_star - 1; /* q* := q* - 1 */
726 /* Subtract r := r - b * q* * beta^j. */
729 const mp_limb_t *sourceptr = b_ptr;
730 mp_limb_t *destptr = r_ptr + j;
731 mp_twolimb_t carry = 0;
733 for (count = b_len; count > 0; count--)
735 /* Here 0 <= carry <= q*. */
738 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
739 + (mp_limb_t) ~(*destptr);
740 /* Here 0 <= carry <= beta*q* + beta-1. */
741 *destptr++ = ~(mp_limb_t) carry;
742 carry = carry >> GMP_LIMB_BITS; /* <= q* */
744 cr = (mp_limb_t) carry;
746 /* Subtract cr from r_ptr[j + b_len], then forget about
748 if (cr > r_ptr[j + b_len])
750 /* Subtraction gave a carry. */
751 q_star = q_star - 1; /* q* := q* - 1 */
754 const mp_limb_t *sourceptr = b_ptr;
755 mp_limb_t *destptr = r_ptr + j;
758 for (count = b_len; count > 0; count--)
760 mp_limb_t source1 = *sourceptr++;
761 mp_limb_t source2 = *destptr;
762 *destptr++ = source1 + source2 + carry;
765 ? source1 >= (mp_limb_t) ~source2
766 : source1 > (mp_limb_t) ~source2);
769 /* Forget about the carry and about r[j+n]. */
772 /* q* is determined. Store it as q[j]. */
781 if (q_ptr[q_len - 1] == 0)
783 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
784 b is shifted left by s bits. */
785 /* Shift r right by s bits. */
788 mp_limb_t ptr = r_ptr + r_len;
789 mp_twolimb_t accu = 0;
791 for (count = r_len; count > 0; count--)
793 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
794 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
795 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
800 while (r_len > 0 && r_ptr[r_len - 1] == 0)
803 /* Compare r << 1 with b. */
811 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
812 | (i < r_len ? r_ptr[i] << 1 : 0);
813 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
823 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
828 for (i = 0; i < q_len; i++)
829 if (++(q_ptr[i]) != 0)
834 if (tmp_roomptr != NULL)
841 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
843 Destroys the contents of a.
844 Return the allocated memory - containing the decimal digits in low-to-high
845 order, terminated with a NUL character - in case of success, NULL in case
846 of memory allocation failure. */
848 convert_to_decimal (mpn_t a, size_t extra_zeroes)
850 mp_limb_t *a_ptr = a.limbs;
851 size_t a_len = a.nlimbs;
852 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
853 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
854 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
858 for (; extra_zeroes > 0; extra_zeroes--)
862 /* Divide a by 10^9, in-place. */
863 mp_limb_t remainder = 0;
864 mp_limb_t *ptr = a_ptr + a_len;
866 for (count = a_len; count > 0; count--)
869 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
870 *ptr = num / 1000000000;
871 remainder = num % 1000000000;
873 /* Store the remainder as 9 decimal digits. */
874 for (count = 9; count > 0; count--)
876 *d_ptr++ = '0' + (remainder % 10);
877 remainder = remainder / 10;
880 if (a_ptr[a_len - 1] == 0)
883 /* Remove leading zeroes. */
884 while (d_ptr > c_ptr && d_ptr[-1] == '0')
886 /* But keep at least one zero. */
889 /* Terminate the string. */
895 # if NEED_PRINTF_LONG_DOUBLE
897 /* Assuming x is finite and >= 0:
898 write x as x = 2^e * m, where m is a bignum.
899 Return the allocated memory in case of success, NULL in case of memory
900 allocation failure. */
902 decode_long_double (long double x, int *ep, mpn_t *mp)
909 /* Allocate memory for result. */
910 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
911 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
914 /* Split into exponential part and mantissa. */
915 y = frexpl (x, &exp);
916 if (!(y >= 0.0L && y < 1.0L))
918 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the
919 latter is an integer. */
920 /* Convert the mantissa (y * 2^LDBL_MANT_BIT) to a sequence of limbs.
921 I'm not sure whether it's safe to cast a 'long double' value between
922 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
923 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
925 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
926 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
929 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
932 if (!(y >= 0.0L && y < 1.0L))
934 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
937 if (!(y >= 0.0L && y < 1.0L))
939 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
944 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
947 if (!(y >= 0.0L && y < 1.0L))
949 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
953 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
956 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
959 if (!(y >= 0.0L && y < 1.0L))
961 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
964 if (!(y >= 0.0L && y < 1.0L))
966 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
968 # if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
974 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
977 *ep = exp - LDBL_MANT_BIT;
983 # if NEED_PRINTF_DOUBLE
985 /* Assuming x is finite and >= 0:
986 write x as x = 2^e * m, where m is a bignum.
987 Return the allocated memory in case of success, NULL in case of memory
988 allocation failure. */
990 decode_double (double x, int *ep, mpn_t *mp)
997 /* Allocate memory for result. */
998 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
999 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
1000 if (m.limbs == NULL)
1002 /* Split into exponential part and mantissa. */
1003 y = frexp (x, &exp);
1004 if (!(y >= 0.0 && y < 1.0))
1006 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the
1007 latter is an integer. */
1008 /* Convert the mantissa (y * 2^DBL_MANT_BIT) to a sequence of limbs.
1009 I'm not sure whether it's safe to cast a 'double' value between
1010 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1011 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1013 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
1014 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1017 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
1020 if (!(y >= 0.0 && y < 1.0))
1022 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1025 if (!(y >= 0.0 && y < 1.0))
1027 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1032 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
1035 if (!(y >= 0.0 && y < 1.0))
1037 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
1041 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1044 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1047 if (!(y >= 0.0 && y < 1.0))
1049 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1052 if (!(y >= 0.0 && y < 1.0))
1054 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1059 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1062 *ep = exp - DBL_MANT_BIT;
1068 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1069 Returns the decimal representation of round (x * 10^n).
1070 Return the allocated memory - containing the decimal digits in low-to-high
1071 order, terminated with a NUL character - in case of success, NULL in case
1072 of memory allocation failure. */
1074 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1077 size_t extra_zeroes;
1080 mp_limb_t *pow5_ptr;
1082 unsigned int s_limbs;
1083 unsigned int s_bits;
1091 /* x = 2^e * m, hence
1092 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1093 = round (2^s * 5^n * m). */
1096 /* Factor out a common power of 10 if possible. */
1099 extra_zeroes = (s < n ? s : n);
1103 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1104 Before converting to decimal, we need to compute
1105 z = round (2^s * 5^n * m). */
1106 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1107 sign. 2.322 is slightly larger than log(5)/log(2). */
1108 abs_n = (n >= 0 ? n : -n);
1109 abs_s = (s >= 0 ? s : -s);
1110 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1111 + abs_s / GMP_LIMB_BITS + 1)
1112 * sizeof (mp_limb_t));
1113 if (pow5_ptr == NULL)
1118 /* Initialize with 1. */
1121 /* Multiply with 5^|n|. */
1124 static mp_limb_t const small_pow5[13 + 1] =
1126 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1127 48828125, 244140625, 1220703125
1130 for (n13 = 0; n13 <= abs_n; n13 += 13)
1132 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1134 mp_twolimb_t carry = 0;
1135 for (j = 0; j < pow5_len; j++)
1137 mp_limb_t digit2 = pow5_ptr[j];
1138 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1139 pow5_ptr[j] = (mp_limb_t) carry;
1140 carry = carry >> GMP_LIMB_BITS;
1143 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1146 s_limbs = abs_s / GMP_LIMB_BITS;
1147 s_bits = abs_s % GMP_LIMB_BITS;
1148 if (n >= 0 ? s >= 0 : s <= 0)
1150 /* Multiply with 2^|s|. */
1153 mp_limb_t *ptr = pow5_ptr;
1154 mp_twolimb_t accu = 0;
1156 for (count = pow5_len; count > 0; count--)
1158 accu += (mp_twolimb_t) *ptr << s_bits;
1159 *ptr++ = (mp_limb_t) accu;
1160 accu = accu >> GMP_LIMB_BITS;
1164 *ptr = (mp_limb_t) accu;
1171 for (count = pow5_len; count > 0;)
1174 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1176 for (count = s_limbs; count > 0;)
1179 pow5_ptr[count] = 0;
1181 pow5_len += s_limbs;
1183 pow5.limbs = pow5_ptr;
1184 pow5.nlimbs = pow5_len;
1187 /* Multiply m with pow5. No division needed. */
1188 z_memory = multiply (m, pow5, &z);
1192 /* Divide m by pow5 and round. */
1193 z_memory = divide (m, pow5, &z);
1198 pow5.limbs = pow5_ptr;
1199 pow5.nlimbs = pow5_len;
1203 Multiply m with pow5, then divide by 2^|s|. */
1207 tmp_memory = multiply (m, pow5, &numerator);
1208 if (tmp_memory == NULL)
1214 /* Construct 2^|s|. */
1216 mp_limb_t *ptr = pow5_ptr + pow5_len;
1218 for (i = 0; i < s_limbs; i++)
1220 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1221 denominator.limbs = ptr;
1222 denominator.nlimbs = s_limbs + 1;
1224 z_memory = divide (numerator, denominator, &z);
1230 Multiply m with 2^s, then divide by pow5. */
1233 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1234 * sizeof (mp_limb_t));
1235 if (num_ptr == NULL)
1242 mp_limb_t *destptr = num_ptr;
1245 for (i = 0; i < s_limbs; i++)
1250 const mp_limb_t *sourceptr = m.limbs;
1251 mp_twolimb_t accu = 0;
1253 for (count = m.nlimbs; count > 0; count--)
1255 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1256 *destptr++ = (mp_limb_t) accu;
1257 accu = accu >> GMP_LIMB_BITS;
1260 *destptr++ = (mp_limb_t) accu;
1264 const mp_limb_t *sourceptr = m.limbs;
1266 for (count = m.nlimbs; count > 0; count--)
1267 *destptr++ = *sourceptr++;
1269 numerator.limbs = num_ptr;
1270 numerator.nlimbs = destptr - num_ptr;
1272 z_memory = divide (numerator, pow5, &z);
1279 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1281 if (z_memory == NULL)
1283 digits = convert_to_decimal (z, extra_zeroes);
1288 # if NEED_PRINTF_LONG_DOUBLE
1290 /* Assuming x is finite and >= 0, and n is an integer:
1291 Returns the decimal representation of round (x * 10^n).
1292 Return the allocated memory - containing the decimal digits in low-to-high
1293 order, terminated with a NUL character - in case of success, NULL in case
1294 of memory allocation failure. */
1296 scale10_round_decimal_long_double (long double x, int n)
1300 void *memory = decode_long_double (x, &e, &m);
1301 return scale10_round_decimal_decoded (e, m, memory, n);
1306 # if NEED_PRINTF_DOUBLE
1308 /* Assuming x is finite and >= 0, and n is an integer:
1309 Returns the decimal representation of round (x * 10^n).
1310 Return the allocated memory - containing the decimal digits in low-to-high
1311 order, terminated with a NUL character - in case of success, NULL in case
1312 of memory allocation failure. */
1314 scale10_round_decimal_double (double x, int n)
1318 void *memory = decode_double (x, &e, &m);
1319 return scale10_round_decimal_decoded (e, m, memory, n);
1324 # if NEED_PRINTF_LONG_DOUBLE
1326 /* Assuming x is finite and > 0:
1327 Return an approximation for n with 10^n <= x < 10^(n+1).
1328 The approximation is usually the right n, but may be off by 1 sometimes. */
1330 floorlog10l (long double x)
1337 /* Split into exponential part and mantissa. */
1338 y = frexpl (x, &exp);
1339 if (!(y >= 0.0L && y < 1.0L))
1345 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1347 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1348 exp -= GMP_LIMB_BITS;
1350 if (y < (1.0L / (1 << 16)))
1352 y *= 1.0L * (1 << 16);
1355 if (y < (1.0L / (1 << 8)))
1357 y *= 1.0L * (1 << 8);
1360 if (y < (1.0L / (1 << 4)))
1362 y *= 1.0L * (1 << 4);
1365 if (y < (1.0L / (1 << 2)))
1367 y *= 1.0L * (1 << 2);
1370 if (y < (1.0L / (1 << 1)))
1372 y *= 1.0L * (1 << 1);
1376 if (!(y >= 0.5L && y < 1.0L))
1378 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1381 if (z < 0.70710678118654752444)
1383 z *= 1.4142135623730950488;
1386 if (z < 0.8408964152537145431)
1388 z *= 1.1892071150027210667;
1391 if (z < 0.91700404320467123175)
1393 z *= 1.0905077326652576592;
1396 if (z < 0.9576032806985736469)
1398 z *= 1.0442737824274138403;
1401 /* Now 0.95 <= z <= 1.01. */
1403 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1404 Four terms are enough to get an approximation with error < 10^-7. */
1405 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1406 /* Finally multiply with log(2)/log(10), yields an approximation for
1408 l *= 0.30102999566398119523;
1409 /* Round down to the next integer. */
1410 return (int) l + (l < 0 ? -1 : 0);
1415 # if NEED_PRINTF_DOUBLE
1417 /* Assuming x is finite and > 0:
1418 Return an approximation for n with 10^n <= x < 10^(n+1).
1419 The approximation is usually the right n, but may be off by 1 sometimes. */
1421 floorlog10 (double x)
1428 /* Split into exponential part and mantissa. */
1429 y = frexp (x, &exp);
1430 if (!(y >= 0.0 && y < 1.0))
1436 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1438 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1439 exp -= GMP_LIMB_BITS;
1441 if (y < (1.0 / (1 << 16)))
1443 y *= 1.0 * (1 << 16);
1446 if (y < (1.0 / (1 << 8)))
1448 y *= 1.0 * (1 << 8);
1451 if (y < (1.0 / (1 << 4)))
1453 y *= 1.0 * (1 << 4);
1456 if (y < (1.0 / (1 << 2)))
1458 y *= 1.0 * (1 << 2);
1461 if (y < (1.0 / (1 << 1)))
1463 y *= 1.0 * (1 << 1);
1467 if (!(y >= 0.5 && y < 1.0))
1469 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1472 if (z < 0.70710678118654752444)
1474 z *= 1.4142135623730950488;
1477 if (z < 0.8408964152537145431)
1479 z *= 1.1892071150027210667;
1482 if (z < 0.91700404320467123175)
1484 z *= 1.0905077326652576592;
1487 if (z < 0.9576032806985736469)
1489 z *= 1.0442737824274138403;
1492 /* Now 0.95 <= z <= 1.01. */
1494 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1495 Four terms are enough to get an approximation with error < 10^-7. */
1496 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1497 /* Finally multiply with log(2)/log(10), yields an approximation for
1499 l *= 0.30102999566398119523;
1500 /* Round down to the next integer. */
1501 return (int) l + (l < 0 ? -1 : 0);
1506 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1507 a single '1' digit. */
1509 is_borderline (const char *digits, size_t precision)
1511 for (; precision > 0; precision--, digits++)
1517 return *digits == '\0';
1522 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99
1524 /* Use a different function name, to make it possible that the 'wchar_t'
1525 parametrization and the 'char' parametrization get compiled in the same
1526 translation unit. */
1527 # if WIDE_CHAR_VERSION
1528 # define MAX_ROOM_NEEDED wmax_room_needed
1530 # define MAX_ROOM_NEEDED max_room_needed
1533 /* Returns the number of TCHAR_T units needed as temporary space for the result
1534 of sprintf or SNPRINTF of a single conversion directive. */
1536 MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
1537 arg_type type, int flags, size_t width, int has_precision,
1538 size_t precision, int pad_ourselves)
1544 case 'd': case 'i': case 'u':
1545 # if HAVE_LONG_LONG_INT
1546 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1548 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1549 * 0.30103 /* binary -> decimal */
1551 + 1; /* turn floor into ceil */
1554 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1556 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1557 * 0.30103 /* binary -> decimal */
1559 + 1; /* turn floor into ceil */
1562 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1563 * 0.30103 /* binary -> decimal */
1565 + 1; /* turn floor into ceil */
1566 if (tmp_length < precision)
1567 tmp_length = precision;
1568 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1569 tmp_length = xsum (tmp_length, tmp_length);
1570 /* Add 1, to account for a leading sign. */
1571 tmp_length = xsum (tmp_length, 1);
1575 # if HAVE_LONG_LONG_INT
1576 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1578 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1579 * 0.333334 /* binary -> octal */
1581 + 1; /* turn floor into ceil */
1584 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1586 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1587 * 0.333334 /* binary -> octal */
1589 + 1; /* turn floor into ceil */
1592 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1593 * 0.333334 /* binary -> octal */
1595 + 1; /* turn floor into ceil */
1596 if (tmp_length < precision)
1597 tmp_length = precision;
1598 /* Add 1, to account for a leading sign. */
1599 tmp_length = xsum (tmp_length, 1);
1603 # if HAVE_LONG_LONG_INT
1604 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1606 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1607 * 0.25 /* binary -> hexadecimal */
1609 + 1; /* turn floor into ceil */
1612 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1614 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1615 * 0.25 /* binary -> hexadecimal */
1617 + 1; /* turn floor into ceil */
1620 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1621 * 0.25 /* binary -> hexadecimal */
1623 + 1; /* turn floor into ceil */
1624 if (tmp_length < precision)
1625 tmp_length = precision;
1626 /* Add 2, to account for a leading sign or alternate form. */
1627 tmp_length = xsum (tmp_length, 2);
1631 if (type == TYPE_LONGDOUBLE)
1633 (unsigned int) (LDBL_MAX_EXP
1634 * 0.30103 /* binary -> decimal */
1635 * 2 /* estimate for FLAG_GROUP */
1637 + 1 /* turn floor into ceil */
1638 + 10; /* sign, decimal point etc. */
1641 (unsigned int) (DBL_MAX_EXP
1642 * 0.30103 /* binary -> decimal */
1643 * 2 /* estimate for FLAG_GROUP */
1645 + 1 /* turn floor into ceil */
1646 + 10; /* sign, decimal point etc. */
1647 tmp_length = xsum (tmp_length, precision);
1650 case 'e': case 'E': case 'g': case 'G':
1652 12; /* sign, decimal point, exponent etc. */
1653 tmp_length = xsum (tmp_length, precision);
1657 if (type == TYPE_LONGDOUBLE)
1659 (unsigned int) (LDBL_DIG
1660 * 0.831 /* decimal -> hexadecimal */
1662 + 1; /* turn floor into ceil */
1665 (unsigned int) (DBL_DIG
1666 * 0.831 /* decimal -> hexadecimal */
1668 + 1; /* turn floor into ceil */
1669 if (tmp_length < precision)
1670 tmp_length = precision;
1671 /* Account for sign, decimal point etc. */
1672 tmp_length = xsum (tmp_length, 12);
1676 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
1677 if (type == TYPE_WIDE_CHAR)
1678 tmp_length = MB_CUR_MAX;
1686 if (type == TYPE_WIDE_STRING)
1688 # if WIDE_CHAR_VERSION
1689 /* ISO C says about %ls in fwprintf:
1690 "If the precision is not specified or is greater than the size
1691 of the array, the array shall contain a null wide character."
1692 So if there is a precision, we must not use wcslen. */
1693 const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
1696 tmp_length = local_wcsnlen (arg, precision);
1698 tmp_length = local_wcslen (arg);
1700 /* ISO C says about %ls in fprintf:
1701 "If a precision is specified, no more than that many bytes are
1702 written (including shift sequences, if any), and the array
1703 shall contain a null wide character if, to equal the multibyte
1704 character sequence length given by the precision, the function
1705 would need to access a wide character one past the end of the
1707 So if there is a precision, we must not use wcslen. */
1708 /* This case has already been handled separately in VASNPRINTF. */
1715 # if WIDE_CHAR_VERSION
1716 /* ISO C says about %s in fwprintf:
1717 "If the precision is not specified or is greater than the size
1718 of the converted array, the converted array shall contain a
1719 null wide character."
1720 So if there is a precision, we must not use strlen. */
1721 /* This case has already been handled separately in VASNPRINTF. */
1724 /* ISO C says about %s in fprintf:
1725 "If the precision is not specified or greater than the size of
1726 the array, the array shall contain a null character."
1727 So if there is a precision, we must not use strlen. */
1728 const char *arg = ap->arg[arg_index].a.a_string;
1731 tmp_length = local_strnlen (arg, precision);
1733 tmp_length = strlen (arg);
1740 (unsigned int) (sizeof (void *) * CHAR_BIT
1741 * 0.25 /* binary -> hexadecimal */
1743 + 1 /* turn floor into ceil */
1744 + 2; /* account for leading 0x */
1753 # if ENABLE_UNISTDIO
1754 /* Padding considers the number of characters, therefore the number of
1755 elements after padding may be
1756 > max (tmp_length, width)
1758 <= tmp_length + width. */
1759 tmp_length = xsum (tmp_length, width);
1761 /* Padding considers the number of elements, says POSIX. */
1762 if (tmp_length < width)
1767 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1775 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1776 const FCHAR_T *format, va_list args)
1781 if (PRINTF_PARSE (format, &d, &a) < 0)
1782 /* errno is already set. */
1786 if (d.dir != d.direct_alloc_dir) \
1788 if (a.arg != a.direct_alloc_arg) \
1791 if (PRINTF_FETCHARGS (args, &a) < 0)
1799 size_t buf_neededlength;
1801 TCHAR_T *buf_malloced;
1805 /* Output string accumulator. */
1810 /* Allocate a small buffer that will hold a directive passed to
1811 sprintf or snprintf. */
1813 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1815 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1817 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1818 buf_malloced = NULL;
1823 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1824 if (size_overflow_p (buf_memsize))
1825 goto out_of_memory_1;
1826 buf = (TCHAR_T *) malloc (buf_memsize);
1828 goto out_of_memory_1;
1832 if (resultbuf != NULL)
1835 allocated = *lengthp;
1844 result is either == resultbuf or == NULL or malloc-allocated.
1845 If length > 0, then result != NULL. */
1847 /* Ensures that allocated >= needed. Aborts through a jump to
1848 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1849 #define ENSURE_ALLOCATION(needed) \
1850 if ((needed) > allocated) \
1852 size_t memory_size; \
1855 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1856 if ((needed) > allocated) \
1857 allocated = (needed); \
1858 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1859 if (size_overflow_p (memory_size)) \
1860 goto out_of_memory; \
1861 if (result == resultbuf || result == NULL) \
1862 memory = (DCHAR_T *) malloc (memory_size); \
1864 memory = (DCHAR_T *) realloc (result, memory_size); \
1865 if (memory == NULL) \
1866 goto out_of_memory; \
1867 if (result == resultbuf && length > 0) \
1868 DCHAR_CPY (memory, result, length); \
1872 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1874 if (cp != dp->dir_start)
1876 size_t n = dp->dir_start - cp;
1877 size_t augmented_length = xsum (length, n);
1879 ENSURE_ALLOCATION (augmented_length);
1880 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1881 need that the format string contains only ASCII characters
1882 if FCHAR_T and DCHAR_T are not the same type. */
1883 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1885 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1886 length = augmented_length;
1891 result[length++] = (unsigned char) *cp++;
1898 /* Execute a single directive. */
1899 if (dp->conversion == '%')
1901 size_t augmented_length;
1903 if (!(dp->arg_index == ARG_NONE))
1905 augmented_length = xsum (length, 1);
1906 ENSURE_ALLOCATION (augmented_length);
1907 result[length] = '%';
1908 length = augmented_length;
1912 if (!(dp->arg_index != ARG_NONE))
1915 if (dp->conversion == 'n')
1917 switch (a.arg[dp->arg_index].type)
1919 case TYPE_COUNT_SCHAR_POINTER:
1920 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1922 case TYPE_COUNT_SHORT_POINTER:
1923 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1925 case TYPE_COUNT_INT_POINTER:
1926 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1928 case TYPE_COUNT_LONGINT_POINTER:
1929 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1931 #if HAVE_LONG_LONG_INT
1932 case TYPE_COUNT_LONGLONGINT_POINTER:
1933 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1941 /* The unistdio extensions. */
1942 else if (dp->conversion == 'U')
1944 arg_type type = a.arg[dp->arg_index].type;
1945 int flags = dp->flags;
1953 if (dp->width_start != dp->width_end)
1955 if (dp->width_arg_index != ARG_NONE)
1959 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1961 arg = a.arg[dp->width_arg_index].a.a_int;
1964 /* "A negative field width is taken as a '-' flag
1965 followed by a positive field width." */
1967 width = (unsigned int) (-arg);
1974 const FCHAR_T *digitp = dp->width_start;
1977 width = xsum (xtimes (width, 10), *digitp++ - '0');
1978 while (digitp != dp->width_end);
1985 if (dp->precision_start != dp->precision_end)
1987 if (dp->precision_arg_index != ARG_NONE)
1991 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1993 arg = a.arg[dp->precision_arg_index].a.a_int;
1994 /* "A negative precision is taken as if the precision
2004 const FCHAR_T *digitp = dp->precision_start + 1;
2007 while (digitp != dp->precision_end)
2008 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2015 case TYPE_U8_STRING:
2017 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
2018 const uint8_t *arg_end;
2023 /* Use only PRECISION characters, from the left. */
2026 for (; precision > 0; precision--)
2028 int count = u8_strmblen (arg_end);
2033 if (!(result == resultbuf || result == NULL))
2035 if (buf_malloced != NULL)
2036 free (buf_malloced);
2047 /* Use the entire string, and count the number of
2053 int count = u8_strmblen (arg_end);
2058 if (!(result == resultbuf || result == NULL))
2060 if (buf_malloced != NULL)
2061 free (buf_malloced);
2072 /* Use the entire string. */
2073 arg_end = arg + u8_strlen (arg);
2074 /* The number of characters doesn't matter. */
2078 if (has_width && width > characters
2079 && !(dp->flags & FLAG_LEFT))
2081 size_t n = width - characters;
2082 ENSURE_ALLOCATION (xsum (length, n));
2083 DCHAR_SET (result + length, ' ', n);
2087 # if DCHAR_IS_UINT8_T
2089 size_t n = arg_end - arg;
2090 ENSURE_ALLOCATION (xsum (length, n));
2091 DCHAR_CPY (result + length, arg, n);
2096 DCHAR_T *converted = result + length;
2097 size_t converted_len = allocated - length;
2099 /* Convert from UTF-8 to locale encoding. */
2101 u8_conv_to_encoding (locale_charset (),
2102 iconveh_question_mark,
2103 arg, arg_end - arg, NULL,
2104 converted, &converted_len);
2106 /* Convert from UTF-8 to UTF-16/UTF-32. */
2108 U8_TO_DCHAR (arg, arg_end - arg,
2109 converted, &converted_len);
2111 if (converted == NULL)
2113 int saved_errno = errno;
2114 if (!(result == resultbuf || result == NULL))
2116 if (buf_malloced != NULL)
2117 free (buf_malloced);
2119 errno = saved_errno;
2122 if (converted != result + length)
2124 ENSURE_ALLOCATION (xsum (length, converted_len));
2125 DCHAR_CPY (result + length, converted, converted_len);
2128 length += converted_len;
2132 if (has_width && width > characters
2133 && (dp->flags & FLAG_LEFT))
2135 size_t n = width - characters;
2136 ENSURE_ALLOCATION (xsum (length, n));
2137 DCHAR_SET (result + length, ' ', n);
2143 case TYPE_U16_STRING:
2145 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
2146 const uint16_t *arg_end;
2151 /* Use only PRECISION characters, from the left. */
2154 for (; precision > 0; precision--)
2156 int count = u16_strmblen (arg_end);
2161 if (!(result == resultbuf || result == NULL))
2163 if (buf_malloced != NULL)
2164 free (buf_malloced);
2175 /* Use the entire string, and count the number of
2181 int count = u16_strmblen (arg_end);
2186 if (!(result == resultbuf || result == NULL))
2188 if (buf_malloced != NULL)
2189 free (buf_malloced);
2200 /* Use the entire string. */
2201 arg_end = arg + u16_strlen (arg);
2202 /* The number of characters doesn't matter. */
2206 if (has_width && width > characters
2207 && !(dp->flags & FLAG_LEFT))
2209 size_t n = width - characters;
2210 ENSURE_ALLOCATION (xsum (length, n));
2211 DCHAR_SET (result + length, ' ', n);
2215 # if DCHAR_IS_UINT16_T
2217 size_t n = arg_end - arg;
2218 ENSURE_ALLOCATION (xsum (length, n));
2219 DCHAR_CPY (result + length, arg, n);
2224 DCHAR_T *converted = result + length;
2225 size_t converted_len = allocated - length;
2227 /* Convert from UTF-16 to locale encoding. */
2229 u16_conv_to_encoding (locale_charset (),
2230 iconveh_question_mark,
2231 arg, arg_end - arg, NULL,
2232 converted, &converted_len);
2234 /* Convert from UTF-16 to UTF-8/UTF-32. */
2236 U16_TO_DCHAR (arg, arg_end - arg,
2237 converted, &converted_len);
2239 if (converted == NULL)
2241 int saved_errno = errno;
2242 if (!(result == resultbuf || result == NULL))
2244 if (buf_malloced != NULL)
2245 free (buf_malloced);
2247 errno = saved_errno;
2250 if (converted != result + length)
2252 ENSURE_ALLOCATION (xsum (length, converted_len));
2253 DCHAR_CPY (result + length, converted, converted_len);
2256 length += converted_len;
2260 if (has_width && width > characters
2261 && (dp->flags & FLAG_LEFT))
2263 size_t n = width - characters;
2264 ENSURE_ALLOCATION (xsum (length, n));
2265 DCHAR_SET (result + length, ' ', n);
2271 case TYPE_U32_STRING:
2273 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
2274 const uint32_t *arg_end;
2279 /* Use only PRECISION characters, from the left. */
2282 for (; precision > 0; precision--)
2284 int count = u32_strmblen (arg_end);
2289 if (!(result == resultbuf || result == NULL))
2291 if (buf_malloced != NULL)
2292 free (buf_malloced);
2303 /* Use the entire string, and count the number of
2309 int count = u32_strmblen (arg_end);
2314 if (!(result == resultbuf || result == NULL))
2316 if (buf_malloced != NULL)
2317 free (buf_malloced);
2328 /* Use the entire string. */
2329 arg_end = arg + u32_strlen (arg);
2330 /* The number of characters doesn't matter. */
2334 if (has_width && width > characters
2335 && !(dp->flags & FLAG_LEFT))
2337 size_t n = width - characters;
2338 ENSURE_ALLOCATION (xsum (length, n));
2339 DCHAR_SET (result + length, ' ', n);
2343 # if DCHAR_IS_UINT32_T
2345 size_t n = arg_end - arg;
2346 ENSURE_ALLOCATION (xsum (length, n));
2347 DCHAR_CPY (result + length, arg, n);
2352 DCHAR_T *converted = result + length;
2353 size_t converted_len = allocated - length;
2355 /* Convert from UTF-32 to locale encoding. */
2357 u32_conv_to_encoding (locale_charset (),
2358 iconveh_question_mark,
2359 arg, arg_end - arg, NULL,
2360 converted, &converted_len);
2362 /* Convert from UTF-32 to UTF-8/UTF-16. */
2364 U32_TO_DCHAR (arg, arg_end - arg,
2365 converted, &converted_len);
2367 if (converted == NULL)
2369 int saved_errno = errno;
2370 if (!(result == resultbuf || result == NULL))
2372 if (buf_malloced != NULL)
2373 free (buf_malloced);
2375 errno = saved_errno;
2378 if (converted != result + length)
2380 ENSURE_ALLOCATION (xsum (length, converted_len));
2381 DCHAR_CPY (result + length, converted, converted_len);
2384 length += converted_len;
2388 if (has_width && width > characters
2389 && (dp->flags & FLAG_LEFT))
2391 size_t n = width - characters;
2392 ENSURE_ALLOCATION (xsum (length, n));
2393 DCHAR_SET (result + length, ' ', n);
2404 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T
2405 else if (dp->conversion == 's'
2406 # if WIDE_CHAR_VERSION
2407 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2409 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2413 /* The normal handling of the 's' directive below requires
2414 allocating a temporary buffer. The determination of its
2415 length (tmp_length), in the case when a precision is
2416 specified, below requires a conversion between a char[]
2417 string and a wchar_t[] wide string. It could be done, but
2418 we have no guarantee that the implementation of sprintf will
2419 use the exactly same algorithm. Without this guarantee, it
2420 is possible to have buffer overrun bugs. In order to avoid
2421 such bugs, we implement the entire processing of the 's'
2422 directive ourselves. */
2423 int flags = dp->flags;
2431 if (dp->width_start != dp->width_end)
2433 if (dp->width_arg_index != ARG_NONE)
2437 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2439 arg = a.arg[dp->width_arg_index].a.a_int;
2442 /* "A negative field width is taken as a '-' flag
2443 followed by a positive field width." */
2445 width = (unsigned int) (-arg);
2452 const FCHAR_T *digitp = dp->width_start;
2455 width = xsum (xtimes (width, 10), *digitp++ - '0');
2456 while (digitp != dp->width_end);
2463 if (dp->precision_start != dp->precision_end)
2465 if (dp->precision_arg_index != ARG_NONE)
2469 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2471 arg = a.arg[dp->precision_arg_index].a.a_int;
2472 /* "A negative precision is taken as if the precision
2482 const FCHAR_T *digitp = dp->precision_start + 1;
2485 while (digitp != dp->precision_end)
2486 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2491 # if WIDE_CHAR_VERSION
2492 /* %s in vasnwprintf. See the specification of fwprintf. */
2494 const char *arg = a.arg[dp->arg_index].a.a_string;
2495 const char *arg_end;
2500 /* Use only as many bytes as needed to produce PRECISION
2501 wide characters, from the left. */
2504 memset (&state, '\0', sizeof (mbstate_t));
2508 for (; precision > 0; precision--)
2512 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2514 count = mblen (arg_end, MB_CUR_MAX);
2517 /* Found the terminating NUL. */
2521 /* Invalid or incomplete multibyte character. */
2522 if (!(result == resultbuf || result == NULL))
2524 if (buf_malloced != NULL)
2525 free (buf_malloced);
2536 /* Use the entire string, and count the number of wide
2540 memset (&state, '\0', sizeof (mbstate_t));
2548 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2550 count = mblen (arg_end, MB_CUR_MAX);
2553 /* Found the terminating NUL. */
2557 /* Invalid or incomplete multibyte character. */
2558 if (!(result == resultbuf || result == NULL))
2560 if (buf_malloced != NULL)
2561 free (buf_malloced);
2572 /* Use the entire string. */
2573 arg_end = arg + strlen (arg);
2574 /* The number of characters doesn't matter. */
2578 if (has_width && width > characters
2579 && !(dp->flags & FLAG_LEFT))
2581 size_t n = width - characters;
2582 ENSURE_ALLOCATION (xsum (length, n));
2583 DCHAR_SET (result + length, ' ', n);
2587 if (has_precision || has_width)
2589 /* We know the number of wide characters in advance. */
2593 memset (&state, '\0', sizeof (mbstate_t));
2595 ENSURE_ALLOCATION (xsum (length, characters));
2596 for (remaining = characters; remaining > 0; remaining--)
2601 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2603 count = mbtowc (&wc, arg, arg_end - arg);
2606 /* mbrtowc not consistent with mbrlen, or mbtowc
2607 not consistent with mblen. */
2609 result[length++] = wc;
2612 if (!(arg == arg_end))
2619 memset (&state, '\0', sizeof (mbstate_t));
2621 while (arg < arg_end)
2626 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2628 count = mbtowc (&wc, arg, arg_end - arg);
2631 /* mbrtowc not consistent with mbrlen, or mbtowc
2632 not consistent with mblen. */
2634 ENSURE_ALLOCATION (xsum (length, 1));
2635 result[length++] = wc;
2640 if (has_width && width > characters
2641 && (dp->flags & FLAG_LEFT))
2643 size_t n = width - characters;
2644 ENSURE_ALLOCATION (xsum (length, n));
2645 DCHAR_SET (result + length, ' ', n);
2650 /* %ls in vasnprintf. See the specification of fprintf. */
2652 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2653 const wchar_t *arg_end;
2655 # if !DCHAR_IS_TCHAR
2656 /* This code assumes that TCHAR_T is 'char'. */
2657 verify (sizeof (TCHAR_T) == 1);
2666 /* Use only as many wide characters as needed to produce
2667 at most PRECISION bytes, from the left. */
2668 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2670 memset (&state, '\0', sizeof (mbstate_t));
2674 while (precision > 0)
2676 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2680 /* Found the terminating null wide character. */
2682 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2683 count = wcrtomb (cbuf, *arg_end, &state);
2685 count = wctomb (cbuf, *arg_end);
2689 /* Cannot convert. */
2690 if (!(result == resultbuf || result == NULL))
2692 if (buf_malloced != NULL)
2693 free (buf_malloced);
2698 if (precision < count)
2701 characters += count;
2711 /* Use the entire string, and count the number of
2713 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2715 memset (&state, '\0', sizeof (mbstate_t));
2721 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2725 /* Found the terminating null wide character. */
2727 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2728 count = wcrtomb (cbuf, *arg_end, &state);
2730 count = wctomb (cbuf, *arg_end);
2734 /* Cannot convert. */
2735 if (!(result == resultbuf || result == NULL))
2737 if (buf_malloced != NULL)
2738 free (buf_malloced);
2744 characters += count;
2750 /* Use the entire string. */
2751 arg_end = arg + local_wcslen (arg);
2752 /* The number of bytes doesn't matter. */
2757 # if !DCHAR_IS_TCHAR
2758 /* Convert the string into a piece of temporary memory. */
2759 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2763 TCHAR_T *tmpptr = tmpsrc;
2765 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2767 memset (&state, '\0', sizeof (mbstate_t));
2769 for (remaining = characters; remaining > 0; )
2771 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2776 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2777 count = wcrtomb (cbuf, *arg, &state);
2779 count = wctomb (cbuf, *arg);
2782 /* Inconsistency. */
2784 memcpy (tmpptr, cbuf, count);
2789 if (!(arg == arg_end))
2793 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2795 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2796 iconveh_question_mark,
2802 int saved_errno = errno;
2804 if (!(result == resultbuf || result == NULL))
2806 if (buf_malloced != NULL)
2807 free (buf_malloced);
2809 errno = saved_errno;
2817 # if ENABLE_UNISTDIO
2818 /* Outside POSIX, it's preferable to compare the width
2819 against the number of _characters_ of the converted
2821 w = DCHAR_MBSNLEN (result + length, characters);
2823 /* The width is compared against the number of _bytes_
2824 of the converted value, says POSIX. */
2829 /* w doesn't matter. */
2832 if (has_width && width > w
2833 && !(dp->flags & FLAG_LEFT))
2835 size_t n = width - w;
2836 ENSURE_ALLOCATION (xsum (length, n));
2837 DCHAR_SET (result + length, ' ', n);
2842 if (has_precision || has_width)
2844 /* We know the number of bytes in advance. */
2846 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2848 memset (&state, '\0', sizeof (mbstate_t));
2850 ENSURE_ALLOCATION (xsum (length, characters));
2851 for (remaining = characters; remaining > 0; )
2853 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2858 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2859 count = wcrtomb (cbuf, *arg, &state);
2861 count = wctomb (cbuf, *arg);
2864 /* Inconsistency. */
2866 memcpy (result + length, cbuf, count);
2871 if (!(arg == arg_end))
2876 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2878 memset (&state, '\0', sizeof (mbstate_t));
2880 while (arg < arg_end)
2882 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2887 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2888 count = wcrtomb (cbuf, *arg, &state);
2890 count = wctomb (cbuf, *arg);
2894 /* Cannot convert. */
2895 if (!(result == resultbuf || result == NULL))
2897 if (buf_malloced != NULL)
2898 free (buf_malloced);
2903 ENSURE_ALLOCATION (xsum (length, count));
2904 memcpy (result + length, cbuf, count);
2910 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2911 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2913 length += tmpdst_len;
2916 if (has_width && width > w
2917 && (dp->flags & FLAG_LEFT))
2919 size_t n = width - w;
2920 ENSURE_ALLOCATION (xsum (length, n));
2921 DCHAR_SET (result + length, ' ', n);
2928 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2929 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2930 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2932 # if NEED_PRINTF_DOUBLE
2933 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2935 # if NEED_PRINTF_LONG_DOUBLE
2936 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2942 arg_type type = a.arg[dp->arg_index].type;
2943 int flags = dp->flags;
2949 DCHAR_T tmpbuf[700];
2956 if (dp->width_start != dp->width_end)
2958 if (dp->width_arg_index != ARG_NONE)
2962 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2964 arg = a.arg[dp->width_arg_index].a.a_int;
2967 /* "A negative field width is taken as a '-' flag
2968 followed by a positive field width." */
2970 width = (unsigned int) (-arg);
2977 const FCHAR_T *digitp = dp->width_start;
2980 width = xsum (xtimes (width, 10), *digitp++ - '0');
2981 while (digitp != dp->width_end);
2988 if (dp->precision_start != dp->precision_end)
2990 if (dp->precision_arg_index != ARG_NONE)
2994 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2996 arg = a.arg[dp->precision_arg_index].a.a_int;
2997 /* "A negative precision is taken as if the precision
3007 const FCHAR_T *digitp = dp->precision_start + 1;
3010 while (digitp != dp->precision_end)
3011 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3016 /* Allocate a temporary buffer of sufficient size. */
3017 if (type == TYPE_LONGDOUBLE)
3019 (unsigned int) ((LDBL_DIG + 1)
3020 * 0.831 /* decimal -> hexadecimal */
3022 + 1; /* turn floor into ceil */
3025 (unsigned int) ((DBL_DIG + 1)
3026 * 0.831 /* decimal -> hexadecimal */
3028 + 1; /* turn floor into ceil */
3029 if (tmp_length < precision)
3030 tmp_length = precision;
3031 /* Account for sign, decimal point etc. */
3032 tmp_length = xsum (tmp_length, 12);
3034 if (tmp_length < width)
3037 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3039 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3043 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3045 if (size_overflow_p (tmp_memsize))
3046 /* Overflow, would lead to out of memory. */
3048 tmp = (DCHAR_T *) malloc (tmp_memsize);
3050 /* Out of memory. */
3056 if (type == TYPE_LONGDOUBLE)
3058 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
3059 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3063 if (dp->conversion == 'A')
3065 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3069 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3075 DECL_LONG_DOUBLE_ROUNDING
3077 BEGIN_LONG_DOUBLE_ROUNDING ();
3079 if (signbit (arg)) /* arg < 0.0L or negative zero */
3087 else if (flags & FLAG_SHOWSIGN)
3089 else if (flags & FLAG_SPACE)
3092 if (arg > 0.0L && arg + arg == arg)
3094 if (dp->conversion == 'A')
3096 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3100 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3106 long double mantissa;
3109 mantissa = printf_frexpl (arg, &exponent);
3117 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
3119 /* Round the mantissa. */
3120 long double tail = mantissa;
3123 for (q = precision; ; q--)
3125 int digit = (int) tail;
3129 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
3138 for (q = precision; q > 0; q--)
3144 *p++ = dp->conversion - 'A' + 'X';
3149 digit = (int) mantissa;
3152 if ((flags & FLAG_ALT)
3153 || mantissa > 0.0L || precision > 0)
3155 *p++ = decimal_point_char ();
3156 /* This loop terminates because we assume
3157 that FLT_RADIX is a power of 2. */
3158 while (mantissa > 0.0L)
3161 digit = (int) mantissa;
3166 : dp->conversion - 10);
3170 while (precision > 0)
3177 *p++ = dp->conversion - 'A' + 'P';
3178 # if WIDE_CHAR_VERSION
3180 static const wchar_t decimal_format[] =
3181 { '%', '+', 'd', '\0' };
3182 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3187 if (sizeof (DCHAR_T) == 1)
3189 sprintf ((char *) p, "%+d", exponent);
3197 sprintf (expbuf, "%+d", exponent);
3198 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3204 END_LONG_DOUBLE_ROUNDING ();
3212 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
3213 double arg = a.arg[dp->arg_index].a.a_double;
3217 if (dp->conversion == 'A')
3219 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3223 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3230 if (signbit (arg)) /* arg < 0.0 or negative zero */
3238 else if (flags & FLAG_SHOWSIGN)
3240 else if (flags & FLAG_SPACE)
3243 if (arg > 0.0 && arg + arg == arg)
3245 if (dp->conversion == 'A')
3247 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3251 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3260 mantissa = printf_frexp (arg, &exponent);
3268 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
3270 /* Round the mantissa. */
3271 double tail = mantissa;
3274 for (q = precision; ; q--)
3276 int digit = (int) tail;
3280 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
3289 for (q = precision; q > 0; q--)
3295 *p++ = dp->conversion - 'A' + 'X';
3300 digit = (int) mantissa;
3303 if ((flags & FLAG_ALT)
3304 || mantissa > 0.0 || precision > 0)
3306 *p++ = decimal_point_char ();
3307 /* This loop terminates because we assume
3308 that FLT_RADIX is a power of 2. */
3309 while (mantissa > 0.0)
3312 digit = (int) mantissa;
3317 : dp->conversion - 10);
3321 while (precision > 0)
3328 *p++ = dp->conversion - 'A' + 'P';
3329 # if WIDE_CHAR_VERSION
3331 static const wchar_t decimal_format[] =
3332 { '%', '+', 'd', '\0' };
3333 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3338 if (sizeof (DCHAR_T) == 1)
3340 sprintf ((char *) p, "%+d", exponent);
3348 sprintf (expbuf, "%+d", exponent);
3349 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3359 /* The generated string now extends from tmp to p, with the
3360 zero padding insertion point being at pad_ptr. */
3361 if (has_width && p - tmp < width)
3363 size_t pad = width - (p - tmp);
3364 DCHAR_T *end = p + pad;
3366 if (flags & FLAG_LEFT)
3368 /* Pad with spaces on the right. */
3369 for (; pad > 0; pad--)
3372 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3374 /* Pad with zeroes. */
3379 for (; pad > 0; pad--)
3384 /* Pad with spaces on the left. */
3389 for (; pad > 0; pad--)
3397 size_t count = p - tmp;
3399 if (count >= tmp_length)
3400 /* tmp_length was incorrectly calculated - fix the
3404 /* Make room for the result. */
3405 if (count >= allocated - length)
3407 size_t n = xsum (length, count);
3409 ENSURE_ALLOCATION (n);
3412 /* Append the result. */
3413 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3420 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3421 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3422 || dp->conversion == 'e' || dp->conversion == 'E'
3423 || dp->conversion == 'g' || dp->conversion == 'G'
3424 || dp->conversion == 'a' || dp->conversion == 'A')
3426 # if NEED_PRINTF_DOUBLE
3427 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3428 # elif NEED_PRINTF_INFINITE_DOUBLE
3429 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3430 /* The systems (mingw) which produce wrong output
3431 for Inf, -Inf, and NaN also do so for -0.0.
3432 Therefore we treat this case here as well. */
3433 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3435 # if NEED_PRINTF_LONG_DOUBLE
3436 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3437 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3438 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3439 /* Some systems produce wrong output for Inf,
3440 -Inf, and NaN. Some systems in this category
3441 (IRIX 5.3) also do so for -0.0. Therefore we
3442 treat this case here as well. */
3443 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3447 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3448 arg_type type = a.arg[dp->arg_index].type;
3450 int flags = dp->flags;
3456 DCHAR_T tmpbuf[700];
3463 if (dp->width_start != dp->width_end)
3465 if (dp->width_arg_index != ARG_NONE)
3469 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3471 arg = a.arg[dp->width_arg_index].a.a_int;
3474 /* "A negative field width is taken as a '-' flag
3475 followed by a positive field width." */
3477 width = (unsigned int) (-arg);
3484 const FCHAR_T *digitp = dp->width_start;
3487 width = xsum (xtimes (width, 10), *digitp++ - '0');
3488 while (digitp != dp->width_end);
3495 if (dp->precision_start != dp->precision_end)
3497 if (dp->precision_arg_index != ARG_NONE)
3501 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3503 arg = a.arg[dp->precision_arg_index].a.a_int;
3504 /* "A negative precision is taken as if the precision
3514 const FCHAR_T *digitp = dp->precision_start + 1;
3517 while (digitp != dp->precision_end)
3518 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3523 /* POSIX specifies the default precision to be 6 for %f, %F,
3524 %e, %E, but not for %g, %G. Implementations appear to use
3525 the same default precision also for %g, %G. But for %a, %A,
3526 the default precision is 0. */
3528 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3531 /* Allocate a temporary buffer of sufficient size. */
3532 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3533 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3534 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3535 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3536 # elif NEED_PRINTF_LONG_DOUBLE
3537 tmp_length = LDBL_DIG + 1;
3538 # elif NEED_PRINTF_DOUBLE
3539 tmp_length = DBL_DIG + 1;
3543 if (tmp_length < precision)
3544 tmp_length = precision;
3545 # if NEED_PRINTF_LONG_DOUBLE
3546 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3547 if (type == TYPE_LONGDOUBLE)
3549 if (dp->conversion == 'f' || dp->conversion == 'F')
3551 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3552 if (!(isnanl (arg) || arg + arg == arg))
3554 /* arg is finite and nonzero. */
3555 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3556 if (exponent >= 0 && tmp_length < exponent + precision)
3557 tmp_length = exponent + precision;
3561 # if NEED_PRINTF_DOUBLE
3562 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3563 if (type == TYPE_DOUBLE)
3565 if (dp->conversion == 'f' || dp->conversion == 'F')
3567 double arg = a.arg[dp->arg_index].a.a_double;
3568 if (!(isnand (arg) || arg + arg == arg))
3570 /* arg is finite and nonzero. */
3571 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3572 if (exponent >= 0 && tmp_length < exponent + precision)
3573 tmp_length = exponent + precision;
3577 /* Account for sign, decimal point etc. */
3578 tmp_length = xsum (tmp_length, 12);
3580 if (tmp_length < width)
3583 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3585 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3589 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3591 if (size_overflow_p (tmp_memsize))
3592 /* Overflow, would lead to out of memory. */
3594 tmp = (DCHAR_T *) malloc (tmp_memsize);
3596 /* Out of memory. */
3603 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3604 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3605 if (type == TYPE_LONGDOUBLE)
3608 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3612 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3614 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3618 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3624 DECL_LONG_DOUBLE_ROUNDING
3626 BEGIN_LONG_DOUBLE_ROUNDING ();
3628 if (signbit (arg)) /* arg < 0.0L or negative zero */
3636 else if (flags & FLAG_SHOWSIGN)
3638 else if (flags & FLAG_SPACE)
3641 if (arg > 0.0L && arg + arg == arg)
3643 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3645 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3649 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3654 # if NEED_PRINTF_LONG_DOUBLE
3657 if (dp->conversion == 'f' || dp->conversion == 'F')
3663 scale10_round_decimal_long_double (arg, precision);
3666 END_LONG_DOUBLE_ROUNDING ();
3669 ndigits = strlen (digits);
3671 if (ndigits > precision)
3675 *p++ = digits[ndigits];
3677 while (ndigits > precision);
3680 /* Here ndigits <= precision. */
3681 if ((flags & FLAG_ALT) || precision > 0)
3683 *p++ = decimal_point_char ();
3684 for (; precision > ndigits; precision--)
3689 *p++ = digits[ndigits];
3695 else if (dp->conversion == 'e' || dp->conversion == 'E')
3703 if ((flags & FLAG_ALT) || precision > 0)
3705 *p++ = decimal_point_char ();
3706 for (; precision > 0; precision--)
3717 exponent = floorlog10l (arg);
3722 scale10_round_decimal_long_double (arg,
3723 (int)precision - exponent);
3726 END_LONG_DOUBLE_ROUNDING ();
3729 ndigits = strlen (digits);
3731 if (ndigits == precision + 1)
3733 if (ndigits < precision
3734 || ndigits > precision + 2)
3735 /* The exponent was not guessed
3736 precisely enough. */
3739 /* None of two values of exponent is
3740 the right one. Prevent an endless
3744 if (ndigits == precision)
3750 /* Here ndigits = precision+1. */
3751 if (is_borderline (digits, precision))
3753 /* Maybe the exponent guess was too high
3754 and a smaller exponent can be reached
3755 by turning a 10...0 into 9...9x. */
3757 scale10_round_decimal_long_double (arg,
3758 (int)precision - exponent + 1);
3759 if (digits2 == NULL)
3762 END_LONG_DOUBLE_ROUNDING ();
3765 if (strlen (digits2) == precision + 1)
3774 /* Here ndigits = precision+1. */
3776 *p++ = digits[--ndigits];
3777 if ((flags & FLAG_ALT) || precision > 0)
3779 *p++ = decimal_point_char ();
3783 *p++ = digits[ndigits];
3790 *p++ = dp->conversion; /* 'e' or 'E' */
3791 # if WIDE_CHAR_VERSION
3793 static const wchar_t decimal_format[] =
3794 { '%', '+', '.', '2', 'd', '\0' };
3795 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3800 if (sizeof (DCHAR_T) == 1)
3802 sprintf ((char *) p, "%+.2d", exponent);
3810 sprintf (expbuf, "%+.2d", exponent);
3811 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3816 else if (dp->conversion == 'g' || dp->conversion == 'G')
3820 /* precision >= 1. */
3823 /* The exponent is 0, >= -4, < precision.
3824 Use fixed-point notation. */
3826 size_t ndigits = precision;
3827 /* Number of trailing zeroes that have to be
3830 (flags & FLAG_ALT ? 0 : precision - 1);
3834 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3836 *p++ = decimal_point_char ();
3837 while (ndigits > nzeroes)
3853 exponent = floorlog10l (arg);
3858 scale10_round_decimal_long_double (arg,
3859 (int)(precision - 1) - exponent);
3862 END_LONG_DOUBLE_ROUNDING ();
3865 ndigits = strlen (digits);
3867 if (ndigits == precision)
3869 if (ndigits < precision - 1
3870 || ndigits > precision + 1)
3871 /* The exponent was not guessed
3872 precisely enough. */
3875 /* None of two values of exponent is
3876 the right one. Prevent an endless
3880 if (ndigits < precision)
3886 /* Here ndigits = precision. */
3887 if (is_borderline (digits, precision - 1))
3889 /* Maybe the exponent guess was too high
3890 and a smaller exponent can be reached
3891 by turning a 10...0 into 9...9x. */
3893 scale10_round_decimal_long_double (arg,
3894 (int)(precision - 1) - exponent + 1);
3895 if (digits2 == NULL)
3898 END_LONG_DOUBLE_ROUNDING ();
3901 if (strlen (digits2) == precision)
3910 /* Here ndigits = precision. */
3912 /* Determine the number of trailing zeroes
3913 that have to be dropped. */
3915 if ((flags & FLAG_ALT) == 0)
3916 while (nzeroes < ndigits
3917 && digits[nzeroes] == '0')
3920 /* The exponent is now determined. */
3922 && exponent < (long)precision)
3924 /* Fixed-point notation:
3925 max(exponent,0)+1 digits, then the
3926 decimal point, then the remaining
3927 digits without trailing zeroes. */
3930 size_t count = exponent + 1;
3931 /* Note: count <= precision = ndigits. */
3932 for (; count > 0; count--)
3933 *p++ = digits[--ndigits];
3934 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3936 *p++ = decimal_point_char ();
3937 while (ndigits > nzeroes)
3940 *p++ = digits[ndigits];
3946 size_t count = -exponent - 1;
3948 *p++ = decimal_point_char ();
3949 for (; count > 0; count--)
3951 while (ndigits > nzeroes)
3954 *p++ = digits[ndigits];
3960 /* Exponential notation. */
3961 *p++ = digits[--ndigits];
3962 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3964 *p++ = decimal_point_char ();
3965 while (ndigits > nzeroes)
3968 *p++ = digits[ndigits];
3971 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3972 # if WIDE_CHAR_VERSION
3974 static const wchar_t decimal_format[] =
3975 { '%', '+', '.', '2', 'd', '\0' };
3976 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3981 if (sizeof (DCHAR_T) == 1)
3983 sprintf ((char *) p, "%+.2d", exponent);
3991 sprintf (expbuf, "%+.2d", exponent);
3992 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4004 /* arg is finite. */
4010 if (dp->conversion == 'f' || dp->conversion == 'F')
4013 if ((flags & FLAG_ALT) || precision > 0)
4015 *p++ = decimal_point_char ();
4016 for (; precision > 0; precision--)
4020 else if (dp->conversion == 'e' || dp->conversion == 'E')
4023 if ((flags & FLAG_ALT) || precision > 0)
4025 *p++ = decimal_point_char ();
4026 for (; precision > 0; precision--)
4029 *p++ = dp->conversion; /* 'e' or 'E' */
4034 else if (dp->conversion == 'g' || dp->conversion == 'G')
4037 if (flags & FLAG_ALT)
4040 (precision > 0 ? precision - 1 : 0);
4041 *p++ = decimal_point_char ();
4042 for (; ndigits > 0; --ndigits)
4046 else if (dp->conversion == 'a' || dp->conversion == 'A')
4049 *p++ = dp->conversion - 'A' + 'X';
4052 if ((flags & FLAG_ALT) || precision > 0)
4054 *p++ = decimal_point_char ();
4055 for (; precision > 0; precision--)
4058 *p++ = dp->conversion - 'A' + 'P';
4067 END_LONG_DOUBLE_ROUNDING ();
4070 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4074 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4076 double arg = a.arg[dp->arg_index].a.a_double;
4080 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4082 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4086 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4093 if (signbit (arg)) /* arg < 0.0 or negative zero */
4101 else if (flags & FLAG_SHOWSIGN)
4103 else if (flags & FLAG_SPACE)
4106 if (arg > 0.0 && arg + arg == arg)
4108 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4110 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4114 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4119 # if NEED_PRINTF_DOUBLE
4122 if (dp->conversion == 'f' || dp->conversion == 'F')
4128 scale10_round_decimal_double (arg, precision);
4131 ndigits = strlen (digits);
4133 if (ndigits > precision)
4137 *p++ = digits[ndigits];
4139 while (ndigits > precision);
4142 /* Here ndigits <= precision. */
4143 if ((flags & FLAG_ALT) || precision > 0)
4145 *p++ = decimal_point_char ();
4146 for (; precision > ndigits; precision--)
4151 *p++ = digits[ndigits];
4157 else if (dp->conversion == 'e' || dp->conversion == 'E')
4165 if ((flags & FLAG_ALT) || precision > 0)
4167 *p++ = decimal_point_char ();
4168 for (; precision > 0; precision--)
4179 exponent = floorlog10 (arg);
4184 scale10_round_decimal_double (arg,
4185 (int)precision - exponent);
4188 ndigits = strlen (digits);
4190 if (ndigits == precision + 1)
4192 if (ndigits < precision
4193 || ndigits > precision + 2)
4194 /* The exponent was not guessed
4195 precisely enough. */
4198 /* None of two values of exponent is
4199 the right one. Prevent an endless
4203 if (ndigits == precision)
4209 /* Here ndigits = precision+1. */
4210 if (is_borderline (digits, precision))
4212 /* Maybe the exponent guess was too high
4213 and a smaller exponent can be reached
4214 by turning a 10...0 into 9...9x. */
4216 scale10_round_decimal_double (arg,
4217 (int)precision - exponent + 1);
4218 if (digits2 == NULL)
4223 if (strlen (digits2) == precision + 1)
4232 /* Here ndigits = precision+1. */
4234 *p++ = digits[--ndigits];
4235 if ((flags & FLAG_ALT) || precision > 0)
4237 *p++ = decimal_point_char ();
4241 *p++ = digits[ndigits];
4248 *p++ = dp->conversion; /* 'e' or 'E' */
4249 # if WIDE_CHAR_VERSION
4251 static const wchar_t decimal_format[] =
4252 /* Produce the same number of exponent digits
4253 as the native printf implementation. */
4254 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4255 { '%', '+', '.', '3', 'd', '\0' };
4257 { '%', '+', '.', '2', 'd', '\0' };
4259 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4265 static const char decimal_format[] =
4266 /* Produce the same number of exponent digits
4267 as the native printf implementation. */
4268 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4273 if (sizeof (DCHAR_T) == 1)
4275 sprintf ((char *) p, decimal_format, exponent);
4283 sprintf (expbuf, decimal_format, exponent);
4284 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4290 else if (dp->conversion == 'g' || dp->conversion == 'G')
4294 /* precision >= 1. */
4297 /* The exponent is 0, >= -4, < precision.
4298 Use fixed-point notation. */
4300 size_t ndigits = precision;
4301 /* Number of trailing zeroes that have to be
4304 (flags & FLAG_ALT ? 0 : precision - 1);
4308 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4310 *p++ = decimal_point_char ();
4311 while (ndigits > nzeroes)
4327 exponent = floorlog10 (arg);
4332 scale10_round_decimal_double (arg,
4333 (int)(precision - 1) - exponent);
4336 ndigits = strlen (digits);
4338 if (ndigits == precision)
4340 if (ndigits < precision - 1
4341 || ndigits > precision + 1)
4342 /* The exponent was not guessed
4343 precisely enough. */
4346 /* None of two values of exponent is
4347 the right one. Prevent an endless
4351 if (ndigits < precision)
4357 /* Here ndigits = precision. */
4358 if (is_borderline (digits, precision - 1))
4360 /* Maybe the exponent guess was too high
4361 and a smaller exponent can be reached
4362 by turning a 10...0 into 9...9x. */
4364 scale10_round_decimal_double (arg,
4365 (int)(precision - 1) - exponent + 1);
4366 if (digits2 == NULL)
4371 if (strlen (digits2) == precision)
4380 /* Here ndigits = precision. */
4382 /* Determine the number of trailing zeroes
4383 that have to be dropped. */
4385 if ((flags & FLAG_ALT) == 0)
4386 while (nzeroes < ndigits
4387 && digits[nzeroes] == '0')
4390 /* The exponent is now determined. */
4392 && exponent < (long)precision)
4394 /* Fixed-point notation:
4395 max(exponent,0)+1 digits, then the
4396 decimal point, then the remaining
4397 digits without trailing zeroes. */
4400 size_t count = exponent + 1;
4401 /* Note: count <= precision = ndigits. */
4402 for (; count > 0; count--)
4403 *p++ = digits[--ndigits];
4404 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4406 *p++ = decimal_point_char ();
4407 while (ndigits > nzeroes)
4410 *p++ = digits[ndigits];
4416 size_t count = -exponent - 1;
4418 *p++ = decimal_point_char ();
4419 for (; count > 0; count--)
4421 while (ndigits > nzeroes)
4424 *p++ = digits[ndigits];
4430 /* Exponential notation. */
4431 *p++ = digits[--ndigits];
4432 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4434 *p++ = decimal_point_char ();
4435 while (ndigits > nzeroes)
4438 *p++ = digits[ndigits];
4441 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4442 # if WIDE_CHAR_VERSION
4444 static const wchar_t decimal_format[] =
4445 /* Produce the same number of exponent digits
4446 as the native printf implementation. */
4447 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4448 { '%', '+', '.', '3', 'd', '\0' };
4450 { '%', '+', '.', '2', 'd', '\0' };
4452 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4458 static const char decimal_format[] =
4459 /* Produce the same number of exponent digits
4460 as the native printf implementation. */
4461 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4466 if (sizeof (DCHAR_T) == 1)
4468 sprintf ((char *) p, decimal_format, exponent);
4476 sprintf (expbuf, decimal_format, exponent);
4477 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4490 /* arg is finite. */
4496 if (dp->conversion == 'f' || dp->conversion == 'F')
4499 if ((flags & FLAG_ALT) || precision > 0)
4501 *p++ = decimal_point_char ();
4502 for (; precision > 0; precision--)
4506 else if (dp->conversion == 'e' || dp->conversion == 'E')
4509 if ((flags & FLAG_ALT) || precision > 0)
4511 *p++ = decimal_point_char ();
4512 for (; precision > 0; precision--)
4515 *p++ = dp->conversion; /* 'e' or 'E' */
4517 /* Produce the same number of exponent digits as
4518 the native printf implementation. */
4519 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4525 else if (dp->conversion == 'g' || dp->conversion == 'G')
4528 if (flags & FLAG_ALT)
4531 (precision > 0 ? precision - 1 : 0);
4532 *p++ = decimal_point_char ();
4533 for (; ndigits > 0; --ndigits)
4545 /* The generated string now extends from tmp to p, with the
4546 zero padding insertion point being at pad_ptr. */
4547 if (has_width && p - tmp < width)
4549 size_t pad = width - (p - tmp);
4550 DCHAR_T *end = p + pad;
4552 if (flags & FLAG_LEFT)
4554 /* Pad with spaces on the right. */
4555 for (; pad > 0; pad--)
4558 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4560 /* Pad with zeroes. */
4565 for (; pad > 0; pad--)
4570 /* Pad with spaces on the left. */
4575 for (; pad > 0; pad--)
4583 size_t count = p - tmp;
4585 if (count >= tmp_length)
4586 /* tmp_length was incorrectly calculated - fix the
4590 /* Make room for the result. */
4591 if (count >= allocated - length)
4593 size_t n = xsum (length, count);
4595 ENSURE_ALLOCATION (n);
4598 /* Append the result. */
4599 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4608 arg_type type = a.arg[dp->arg_index].type;
4609 int flags = dp->flags;
4610 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4614 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4618 #if NEED_PRINTF_UNBOUNDED_PRECISION
4621 # define prec_ourselves 0
4623 #if NEED_PRINTF_FLAG_LEFTADJUST
4624 # define pad_ourselves 1
4625 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4628 # define pad_ourselves 0
4631 unsigned int prefix_count;
4632 int prefixes[2] IF_LINT (= { 0 });
4636 TCHAR_T tmpbuf[700];
4640 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4643 if (dp->width_start != dp->width_end)
4645 if (dp->width_arg_index != ARG_NONE)
4649 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4651 arg = a.arg[dp->width_arg_index].a.a_int;
4654 /* "A negative field width is taken as a '-' flag
4655 followed by a positive field width." */
4657 width = (unsigned int) (-arg);
4664 const FCHAR_T *digitp = dp->width_start;
4667 width = xsum (xtimes (width, 10), *digitp++ - '0');
4668 while (digitp != dp->width_end);
4674 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4677 if (dp->precision_start != dp->precision_end)
4679 if (dp->precision_arg_index != ARG_NONE)
4683 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4685 arg = a.arg[dp->precision_arg_index].a.a_int;
4686 /* "A negative precision is taken as if the precision
4696 const FCHAR_T *digitp = dp->precision_start + 1;
4699 while (digitp != dp->precision_end)
4700 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4706 /* Decide whether to handle the precision ourselves. */
4707 #if NEED_PRINTF_UNBOUNDED_PRECISION
4708 switch (dp->conversion)
4710 case 'd': case 'i': case 'u':
4712 case 'x': case 'X': case 'p':
4713 prec_ourselves = has_precision && (precision > 0);
4721 /* Decide whether to perform the padding ourselves. */
4722 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4723 switch (dp->conversion)
4725 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4726 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4727 to perform the padding after this conversion. Functions
4728 with unistdio extensions perform the padding based on
4729 character count rather than element count. */
4732 # if NEED_PRINTF_FLAG_ZERO
4733 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4739 pad_ourselves = prec_ourselves;
4745 /* Allocate a temporary buffer of sufficient size for calling
4748 MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
4749 flags, width, has_precision, precision,
4752 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4756 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4758 if (size_overflow_p (tmp_memsize))
4759 /* Overflow, would lead to out of memory. */
4761 tmp = (TCHAR_T *) malloc (tmp_memsize);
4763 /* Out of memory. */
4768 /* Construct the format string for calling snprintf or
4772 #if NEED_PRINTF_FLAG_GROUPING
4773 /* The underlying implementation doesn't support the ' flag.
4774 Produce no grouping characters in this case; this is
4775 acceptable because the grouping is locale dependent. */
4777 if (flags & FLAG_GROUP)
4780 if (flags & FLAG_LEFT)
4782 if (flags & FLAG_SHOWSIGN)
4784 if (flags & FLAG_SPACE)
4786 if (flags & FLAG_ALT)
4788 #if __GLIBC__ >= 2 && !defined __UCLIBC__
4789 if (flags & FLAG_LOCALIZED)
4794 if (flags & FLAG_ZERO)
4796 if (dp->width_start != dp->width_end)
4798 size_t n = dp->width_end - dp->width_start;
4799 /* The width specification is known to consist only
4800 of standard ASCII characters. */
4801 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4803 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4808 const FCHAR_T *mp = dp->width_start;
4810 *fbp++ = (unsigned char) *mp++;
4815 if (!prec_ourselves)
4817 if (dp->precision_start != dp->precision_end)
4819 size_t n = dp->precision_end - dp->precision_start;
4820 /* The precision specification is known to consist only
4821 of standard ASCII characters. */
4822 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4824 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4829 const FCHAR_T *mp = dp->precision_start;
4831 *fbp++ = (unsigned char) *mp++;
4839 #if HAVE_LONG_LONG_INT
4840 case TYPE_LONGLONGINT:
4841 case TYPE_ULONGLONGINT:
4842 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4855 case TYPE_WIDE_CHAR:
4858 case TYPE_WIDE_STRING:
4862 case TYPE_LONGDOUBLE:
4868 #if NEED_PRINTF_DIRECTIVE_F
4869 if (dp->conversion == 'F')
4873 *fbp = dp->conversion;
4875 # if !(((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) && !defined __UCLIBC__) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4880 /* On glibc2 systems from glibc >= 2.3 - probably also older
4881 ones - we know that snprintf's return value conforms to
4882 ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and
4883 gl_SNPRINTF_TRUNCATION_C99 pass.
4884 Therefore we can avoid using %n in this situation.
4885 On glibc2 systems from 2004-10-18 or newer, the use of %n
4886 in format strings in writable memory may crash the program
4887 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4888 in this situation. */
4889 /* On native Windows systems (such as mingw), we can avoid using
4891 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4892 snprintf does not write more than the specified number
4893 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4894 '4', '5', '6' into buf, not '4', '5', '\0'.)
4895 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4896 allows us to recognize the case of an insufficient
4897 buffer size: it returns -1 in this case.
4898 On native Windows systems (such as mingw) where the OS is
4899 Windows Vista, the use of %n in format strings by default
4900 crashes the program. See
4901 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4902 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4903 So we should avoid %n in this situation. */
4910 /* Construct the arguments for calling snprintf or sprintf. */
4912 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4914 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4916 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4918 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4920 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4922 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4926 /* The SNPRINTF result is appended after result[0..length].
4927 The latter is an array of DCHAR_T; SNPRINTF appends an
4928 array of TCHAR_T to it. This is possible because
4929 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4930 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4931 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4932 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4933 where an snprintf() with maxlen==1 acts like sprintf(). */
4934 ENSURE_ALLOCATION (xsum (length,
4935 (2 + TCHARS_PER_DCHAR - 1)
4936 / TCHARS_PER_DCHAR));
4937 /* Prepare checking whether snprintf returns the count
4939 *(TCHAR_T *) (result + length) = '\0';
4950 size_t maxlen = allocated - length;
4951 /* SNPRINTF can fail if its second argument is
4953 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4954 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4955 maxlen = maxlen * TCHARS_PER_DCHAR;
4956 # define SNPRINTF_BUF(arg) \
4957 switch (prefix_count) \
4960 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4965 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4967 prefixes[0], arg, &count); \
4970 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4972 prefixes[0], prefixes[1], arg, \
4979 # define SNPRINTF_BUF(arg) \
4980 switch (prefix_count) \
4983 count = sprintf (tmp, buf, arg); \
4986 count = sprintf (tmp, buf, prefixes[0], arg); \
4989 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
5002 int arg = a.arg[dp->arg_index].a.a_schar;
5008 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
5014 int arg = a.arg[dp->arg_index].a.a_short;
5020 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
5026 int arg = a.arg[dp->arg_index].a.a_int;
5032 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
5038 long int arg = a.arg[dp->arg_index].a.a_longint;
5044 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
5048 #if HAVE_LONG_LONG_INT
5049 case TYPE_LONGLONGINT:
5051 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
5055 case TYPE_ULONGLONGINT:
5057 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
5064 double arg = a.arg[dp->arg_index].a.a_double;
5068 case TYPE_LONGDOUBLE:
5070 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5076 int arg = a.arg[dp->arg_index].a.a_char;
5081 case TYPE_WIDE_CHAR:
5083 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5090 const char *arg = a.arg[dp->arg_index].a.a_string;
5095 case TYPE_WIDE_STRING:
5097 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5104 void *arg = a.arg[dp->arg_index].a.a_pointer;
5113 /* Portability: Not all implementations of snprintf()
5114 are ISO C 99 compliant. Determine the number of
5115 bytes that snprintf() has produced or would have
5119 /* Verify that snprintf() has NUL-terminated its
5122 && ((TCHAR_T *) (result + length)) [count] != '\0')
5124 /* Portability hack. */
5125 if (retcount > count)
5130 /* snprintf() doesn't understand the '%n'
5134 /* Don't use the '%n' directive; instead, look
5135 at the snprintf() return value. */
5141 /* Look at the snprintf() return value. */
5144 # if !HAVE_SNPRINTF_RETVAL_C99
5145 /* HP-UX 10.20 snprintf() is doubly deficient:
5146 It doesn't understand the '%n' directive,
5147 *and* it returns -1 (rather than the length
5148 that would have been required) when the
5149 buffer is too small.
5150 But a failure at this point can also come
5151 from other reasons than a too small buffer,
5152 such as an invalid wide string argument to
5153 the %ls directive, or possibly an invalid
5154 floating-point argument. */
5156 MAX_ROOM_NEEDED (&a, dp->arg_index,
5157 dp->conversion, type, flags,
5158 has_width ? width : 0,
5160 precision, pad_ourselves);
5162 if (maxlen < tmp_length)
5164 /* Make more room. But try to do through
5165 this reallocation only once. */
5166 size_t bigger_need =
5169 TCHARS_PER_DCHAR - 1)
5170 / TCHARS_PER_DCHAR);
5171 /* And always grow proportionally.
5172 (There may be several arguments, each
5173 needing a little more room than the
5175 size_t bigger_need2 =
5176 xsum (xtimes (allocated, 2), 12);
5177 if (bigger_need < bigger_need2)
5178 bigger_need = bigger_need2;
5179 ENSURE_ALLOCATION (bigger_need);
5190 /* Attempt to handle failure. */
5193 /* SNPRINTF or sprintf failed. Save and use the errno
5194 that it has set, if any. */
5195 int saved_errno = errno;
5197 if (!(result == resultbuf || result == NULL))
5199 if (buf_malloced != NULL)
5200 free (buf_malloced);
5205 : (dp->conversion == 'c' || dp->conversion == 's'
5212 /* Handle overflow of the allocated buffer.
5213 If such an overflow occurs, a C99 compliant snprintf()
5214 returns a count >= maxlen. However, a non-compliant
5215 snprintf() function returns only count = maxlen - 1. To
5216 cover both cases, test whether count >= maxlen - 1. */
5217 if ((unsigned int) count + 1 >= maxlen)
5219 /* If maxlen already has attained its allowed maximum,
5220 allocating more memory will not increase maxlen.
5221 Instead of looping, bail out. */
5222 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5226 /* Need at least (count + 1) * sizeof (TCHAR_T)
5227 bytes. (The +1 is for the trailing NUL.)
5228 But ask for (count + 2) * sizeof (TCHAR_T)
5229 bytes, so that in the next round, we likely get
5230 maxlen > (unsigned int) count + 1
5231 and so we don't get here again.
5232 And allocate proportionally, to avoid looping
5233 eternally if snprintf() reports a too small
5237 ((unsigned int) count + 2
5238 + TCHARS_PER_DCHAR - 1)
5239 / TCHARS_PER_DCHAR),
5240 xtimes (allocated, 2));
5242 ENSURE_ALLOCATION (n);
5248 #if NEED_PRINTF_UNBOUNDED_PRECISION
5251 /* Handle the precision. */
5254 (TCHAR_T *) (result + length);
5258 size_t prefix_count;
5262 /* Put the additional zeroes after the sign. */
5264 && (*prec_ptr == '-' || *prec_ptr == '+'
5265 || *prec_ptr == ' '))
5267 /* Put the additional zeroes after the 0x prefix if
5268 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5270 && prec_ptr[0] == '0'
5271 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5274 move = count - prefix_count;
5275 if (precision > move)
5277 /* Insert zeroes. */
5278 size_t insert = precision - move;
5284 (count + insert + TCHARS_PER_DCHAR - 1)
5285 / TCHARS_PER_DCHAR);
5286 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5287 ENSURE_ALLOCATION (n);
5288 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5289 prec_ptr = (TCHAR_T *) (result + length);
5292 prec_end = prec_ptr + count;
5293 prec_ptr += prefix_count;
5295 while (prec_end > prec_ptr)
5298 prec_end[insert] = prec_end[0];
5304 while (prec_end > prec_ptr);
5312 if (count >= tmp_length)
5313 /* tmp_length was incorrectly calculated - fix the
5319 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5320 if (dp->conversion == 'c' || dp->conversion == 's')
5322 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5324 The result string is not certainly ASCII. */
5325 const TCHAR_T *tmpsrc;
5328 /* This code assumes that TCHAR_T is 'char'. */
5329 verify (sizeof (TCHAR_T) == 1);
5331 tmpsrc = (TCHAR_T *) (result + length);
5336 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5337 iconveh_question_mark,
5343 int saved_errno = errno;
5344 if (!(result == resultbuf || result == NULL))
5346 if (buf_malloced != NULL)
5347 free (buf_malloced);
5349 errno = saved_errno;
5352 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5353 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5359 /* The result string is ASCII.
5360 Simple 1:1 conversion. */
5362 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5363 no-op conversion, in-place on the array starting
5364 at (result + length). */
5365 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5368 const TCHAR_T *tmpsrc;
5373 if (result == resultbuf)
5375 tmpsrc = (TCHAR_T *) (result + length);
5376 /* ENSURE_ALLOCATION will not move tmpsrc
5377 (because it's part of resultbuf). */
5378 ENSURE_ALLOCATION (xsum (length, count));
5382 /* ENSURE_ALLOCATION will move the array
5383 (because it uses realloc(). */
5384 ENSURE_ALLOCATION (xsum (length, count));
5385 tmpsrc = (TCHAR_T *) (result + length);
5389 ENSURE_ALLOCATION (xsum (length, count));
5391 tmpdst = result + length;
5392 /* Copy backwards, because of overlapping. */
5395 for (n = count; n > 0; n--)
5396 *--tmpdst = (unsigned char) *--tmpsrc;
5401 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5402 /* Make room for the result. */
5403 if (count > allocated - length)
5405 /* Need at least count elements. But allocate
5408 xmax (xsum (length, count), xtimes (allocated, 2));
5410 ENSURE_ALLOCATION (n);
5414 /* Here count <= allocated - length. */
5416 /* Perform padding. */
5417 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5418 if (pad_ourselves && has_width)
5421 # if ENABLE_UNISTDIO
5422 /* Outside POSIX, it's preferable to compare the width
5423 against the number of _characters_ of the converted
5425 w = DCHAR_MBSNLEN (result + length, count);
5427 /* The width is compared against the number of _bytes_
5428 of the converted value, says POSIX. */
5433 size_t pad = width - w;
5435 /* Make room for the result. */
5436 if (xsum (count, pad) > allocated - length)
5438 /* Need at least count + pad elements. But
5439 allocate proportionally. */
5441 xmax (xsum3 (length, count, pad),
5442 xtimes (allocated, 2));
5446 ENSURE_ALLOCATION (n);
5449 ENSURE_ALLOCATION (n);
5452 /* Here count + pad <= allocated - length. */
5455 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5456 DCHAR_T * const rp = result + length;
5458 DCHAR_T * const rp = tmp;
5460 DCHAR_T *p = rp + count;
5461 DCHAR_T *end = p + pad;
5463 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5464 if (dp->conversion == 'c'
5465 || dp->conversion == 's')
5466 /* No zero-padding for string directives. */
5471 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5472 /* No zero-padding of "inf" and "nan". */
5473 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5474 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5477 /* The generated string now extends from rp to p,
5478 with the zero padding insertion point being at
5481 count = count + pad; /* = end - rp */
5483 if (flags & FLAG_LEFT)
5485 /* Pad with spaces on the right. */
5486 for (; pad > 0; pad--)
5489 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5491 /* Pad with zeroes. */
5496 for (; pad > 0; pad--)
5501 /* Pad with spaces on the left. */
5506 for (; pad > 0; pad--)
5514 /* Here still count <= allocated - length. */
5516 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5517 /* The snprintf() result did fit. */
5519 /* Append the sprintf() result. */
5520 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5527 #if NEED_PRINTF_DIRECTIVE_F
5528 if (dp->conversion == 'F')
5530 /* Convert the %f result to upper case for %F. */
5531 DCHAR_T *rp = result + length;
5533 for (rc = count; rc > 0; rc--, rp++)
5534 if (*rp >= 'a' && *rp <= 'z')
5535 *rp = *rp - 'a' + 'A';
5543 #undef pad_ourselves
5544 #undef prec_ourselves
5549 /* Add the final NUL. */
5550 ENSURE_ALLOCATION (xsum (length, 1));
5551 result[length] = '\0';
5553 if (result != resultbuf && length + 1 < allocated)
5555 /* Shrink the allocated memory if possible. */
5558 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5563 if (buf_malloced != NULL)
5564 free (buf_malloced);
5567 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5568 says that snprintf() fails with errno = EOVERFLOW in this case, but
5569 that's only because snprintf() returns an 'int'. This function does
5570 not have this limitation. */
5575 if (!(result == resultbuf || result == NULL))
5577 if (buf_malloced != NULL)
5578 free (buf_malloced);
5585 if (!(result == resultbuf || result == NULL))
5587 if (buf_malloced != NULL)
5588 free (buf_malloced);
5596 #undef MAX_ROOM_NEEDED
5597 #undef TCHARS_PER_DCHAR
5605 #undef DCHAR_IS_TCHAR