1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2015 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, see <http://www.gnu.org/licenses/>. */
17 /* This file can be parametrized with the following macros:
18 VASNPRINTF The name of the function being defined.
19 FCHAR_T The element type of the format string.
20 DCHAR_T The element type of the destination (result) string.
21 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
22 in the format string are ASCII. MUST be set if
23 FCHAR_T and DCHAR_T are not the same type.
24 DIRECTIVE Structure denoting a format directive.
26 DIRECTIVES Structure denoting the set of format directives of a
27 format string. Depends on FCHAR_T.
28 PRINTF_PARSE Function that parses a format string.
30 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
31 DCHAR_SET memset like function for DCHAR_T[] arrays.
32 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
33 SNPRINTF The system's snprintf (or similar) function.
34 This may be either snprintf or swprintf.
35 TCHAR_T The element type of the argument and result string
36 of the said SNPRINTF function. This may be either
37 char or wchar_t. The code exploits that
38 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
39 alignof (TCHAR_T) <= alignof (DCHAR_T).
40 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
41 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
42 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
43 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
44 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
46 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
47 This must come before <config.h> because <config.h> may include
48 <features.h>, and once <features.h> has been included, it's too late. */
50 # define _GNU_SOURCE 1
62 # if WIDE_CHAR_VERSION
63 # include "vasnwprintf.h"
65 # include "vasnprintf.h"
69 #include <locale.h> /* localeconv() */
70 #include <stdio.h> /* snprintf(), sprintf() */
71 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
72 #include <string.h> /* memcpy(), strlen() */
73 #include <errno.h> /* errno */
74 #include <limits.h> /* CHAR_BIT */
75 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
77 # include <langinfo.h>
80 # if WIDE_CHAR_VERSION
81 # include "wprintf-parse.h"
83 # include "printf-parse.h"
87 /* Checked size_t computations. */
92 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
97 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
99 # include "isnand-nolibm.h"
102 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
104 # include "isnanl-nolibm.h"
108 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
110 # include "isnand-nolibm.h"
111 # include "printf-frexp.h"
114 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
116 # include "isnanl-nolibm.h"
117 # include "printf-frexpl.h"
121 /* Default parameters. */
123 # if WIDE_CHAR_VERSION
124 # define VASNPRINTF vasnwprintf
125 # define FCHAR_T wchar_t
126 # define DCHAR_T wchar_t
127 # define TCHAR_T wchar_t
128 # define DCHAR_IS_TCHAR 1
129 # define DIRECTIVE wchar_t_directive
130 # define DIRECTIVES wchar_t_directives
131 # define PRINTF_PARSE wprintf_parse
132 # define DCHAR_CPY wmemcpy
133 # define DCHAR_SET wmemset
135 # define VASNPRINTF vasnprintf
136 # define FCHAR_T char
137 # define DCHAR_T char
138 # define TCHAR_T char
139 # define DCHAR_IS_TCHAR 1
140 # define DIRECTIVE char_directive
141 # define DIRECTIVES char_directives
142 # define PRINTF_PARSE printf_parse
143 # define DCHAR_CPY memcpy
144 # define DCHAR_SET memset
147 #if WIDE_CHAR_VERSION
148 /* TCHAR_T is wchar_t. */
149 # define USE_SNPRINTF 1
150 # if HAVE_DECL__SNWPRINTF
151 /* On Windows, the function swprintf() has a different signature than
152 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
153 instead. The mingw function snwprintf() has fewer bugs than the
154 MSVCRT function _snwprintf(), so prefer that. */
155 # if defined __MINGW32__
156 # define SNPRINTF snwprintf
158 # define SNPRINTF _snwprintf
162 # define SNPRINTF swprintf
165 /* TCHAR_T is char. */
166 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
167 But don't use it on BeOS, since BeOS snprintf produces no output if the
168 size argument is >= 0x3000000.
169 Also don't use it on Linux libc5, since there snprintf with size = 1
170 writes any output without bounds, like sprintf. */
171 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
172 # define USE_SNPRINTF 1
174 # define USE_SNPRINTF 0
176 # if HAVE_DECL__SNPRINTF
177 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
178 function _snprintf(), so prefer that. */
179 # if defined __MINGW32__
180 # define SNPRINTF snprintf
181 /* Here we need to call the native snprintf, not rpl_snprintf. */
184 # define SNPRINTF _snprintf
188 # define SNPRINTF snprintf
189 /* Here we need to call the native snprintf, not rpl_snprintf. */
193 /* Here we need to call the native sprintf, not rpl_sprintf. */
196 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
197 warnings in this file. Use -Dlint to suppress them. */
199 # define IF_LINT(Code) Code
201 # define IF_LINT(Code) /* empty */
204 /* Avoid some warnings from "gcc -Wshadow".
205 This file doesn't use the exp() and remainder() functions. */
209 #define remainder rem
211 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && !WIDE_CHAR_VERSION
212 # if (HAVE_STRNLEN && !defined _AIX)
213 # define local_strnlen strnlen
215 # ifndef local_strnlen_defined
216 # define local_strnlen_defined 1
218 local_strnlen (const char *string, size_t maxlen)
220 const char *end = memchr (string, '\0', maxlen);
221 return end ? (size_t) (end - string) : maxlen;
227 #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
229 # define local_wcslen wcslen
231 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
232 a dependency towards this library, here is a local substitute.
233 Define this substitute only once, even if this file is included
234 twice in the same compilation unit. */
235 # ifndef local_wcslen_defined
236 # define local_wcslen_defined 1
238 local_wcslen (const wchar_t *s)
242 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
250 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
252 # define local_wcsnlen wcsnlen
254 # ifndef local_wcsnlen_defined
255 # define local_wcsnlen_defined 1
257 local_wcsnlen (const wchar_t *s, size_t maxlen)
261 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
269 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
270 /* Determine the decimal-point character according to the current locale. */
271 # ifndef decimal_point_char_defined
272 # define decimal_point_char_defined 1
274 decimal_point_char (void)
277 /* Determine it in a multithread-safe way. We know nl_langinfo is
278 multithread-safe on glibc systems and Mac OS X systems, but is not required
279 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
280 localeconv() is rarely multithread-safe. */
281 # if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
282 point = nl_langinfo (RADIXCHAR);
285 sprintf (pointbuf, "%#.0f", 1.0);
286 point = &pointbuf[1];
288 point = localeconv () -> decimal_point;
290 /* The decimal point is always a single byte: either '.' or ','. */
291 return (point[0] != '\0' ? point[0] : '.');
296 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
298 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
300 is_infinite_or_zero (double x)
302 return isnand (x) || x + x == x;
307 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
309 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
311 is_infinite_or_zerol (long double x)
313 return isnanl (x) || x + x == x;
318 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
320 /* Converting 'long double' to decimal without rare rounding bugs requires
321 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
322 (and slower) algorithms. */
324 typedef unsigned int mp_limb_t;
325 # define GMP_LIMB_BITS 32
326 verify (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS);
328 typedef unsigned long long mp_twolimb_t;
329 # define GMP_TWOLIMB_BITS 64
330 verify (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS);
332 /* Representation of a bignum >= 0. */
336 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
339 /* Compute the product of two bignums >= 0.
340 Return the allocated memory in case of success, NULL in case of memory
341 allocation failure. */
343 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
350 if (src1.nlimbs <= src2.nlimbs)
364 /* Now 0 <= len1 <= len2. */
367 /* src1 or src2 is zero. */
369 dest->limbs = (mp_limb_t *) malloc (1);
373 /* Here 1 <= len1 <= len2. */
379 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
382 for (k = len2; k > 0; )
384 for (i = 0; i < len1; i++)
386 mp_limb_t digit1 = p1[i];
387 mp_twolimb_t carry = 0;
388 for (j = 0; j < len2; j++)
390 mp_limb_t digit2 = p2[j];
391 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
393 dp[i + j] = (mp_limb_t) carry;
394 carry = carry >> GMP_LIMB_BITS;
396 dp[i + len2] = (mp_limb_t) carry;
399 while (dlen > 0 && dp[dlen - 1] == 0)
407 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
408 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
410 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
412 Return the allocated memory in case of success, NULL in case of memory
413 allocation failure. */
415 divide (mpn_t a, mpn_t b, mpn_t *q)
418 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
419 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
420 If m<n, then q:=0 and r:=a.
421 If m>=n=1, perform a single-precision division:
424 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
425 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
426 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
427 Normalise [q[m-1],...,q[0]], yields q.
428 If m>=n>1, perform a multiple-precision division:
429 We have a/b < beta^(m-n+1).
430 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
431 Shift a and b left by s bits, copying them. r:=a.
432 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
433 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
435 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
436 In case of overflow (q* >= beta) set q* := beta-1.
437 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
438 and c3 := b[n-2] * q*.
439 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
440 occurred. Furthermore 0 <= c3 < beta^2.
441 If there was overflow and
442 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
443 the next test can be skipped.}
444 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
445 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
447 Put r := r - b * q* * beta^j. In detail:
448 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
449 hence: u:=0, for i:=0 to n-1 do
451 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
452 u:=u div beta (+ 1, if carry in subtraction)
454 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
456 the carry u does not overflow.}
457 If a negative carry occurs, put q* := q* - 1
458 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
460 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
461 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
463 The room for q[j] can be allocated at the memory location of r[n+j].
464 Finally, round-to-even:
465 Shift r left by 1 bit.
466 If r > b or if r = b and q[0] is odd, q := q+1.
468 const mp_limb_t *a_ptr = a.limbs;
469 size_t a_len = a.nlimbs;
470 const mp_limb_t *b_ptr = b.limbs;
471 size_t b_len = b.nlimbs;
473 mp_limb_t *tmp_roomptr = NULL;
479 /* Allocate room for a_len+2 digits.
480 (Need a_len+1 digits for the real division and 1 more digit for the
481 final rounding of q.) */
482 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
487 while (a_len > 0 && a_ptr[a_len - 1] == 0)
494 /* Division by zero. */
496 if (b_ptr[b_len - 1] == 0)
502 /* Here m = a_len >= 0 and n = b_len > 0. */
506 /* m<n: trivial case. q=0, r := copy of a. */
509 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
510 q_ptr = roomptr + a_len;
515 /* n=1: single precision division.
516 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
520 mp_limb_t den = b_ptr[0];
521 mp_limb_t remainder = 0;
522 const mp_limb_t *sourceptr = a_ptr + a_len;
523 mp_limb_t *destptr = q_ptr + a_len;
525 for (count = a_len; count > 0; count--)
528 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
529 *--destptr = num / den;
530 remainder = num % den;
532 /* Normalise and store r. */
535 r_ptr[0] = remainder;
542 if (q_ptr[q_len - 1] == 0)
548 /* n>1: multiple precision division.
549 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
550 beta^(m-n-1) <= a/b < beta^(m-n+1). */
554 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
555 /* Determine s = GMP_LIMB_BITS - integer_length (msd).
556 Code copied from gnulib's integer_length.c. */
557 # if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
558 s = __builtin_clz (msd);
560 # if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT
561 if (GMP_LIMB_BITS <= DBL_MANT_BIT)
563 /* Use 'double' operations.
564 Assumes an IEEE 754 'double' implementation. */
565 # define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)
566 # define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1)
568 ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
569 union { double value; unsigned int word[NWORDS]; } m;
571 /* Use a single integer to floating-point conversion. */
575 - (((m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK)
611 /* 0 <= s < GMP_LIMB_BITS.
612 Copy b, shifting it left by s bits. */
615 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
616 if (tmp_roomptr == NULL)
622 const mp_limb_t *sourceptr = b_ptr;
623 mp_limb_t *destptr = tmp_roomptr;
624 mp_twolimb_t accu = 0;
626 for (count = b_len; count > 0; count--)
628 accu += (mp_twolimb_t) *sourceptr++ << s;
629 *destptr++ = (mp_limb_t) accu;
630 accu = accu >> GMP_LIMB_BITS;
632 /* accu must be zero, since that was how s was determined. */
638 /* Copy a, shifting it left by s bits, yields r.
640 At the beginning: r = roomptr[0..a_len],
641 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
645 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
650 const mp_limb_t *sourceptr = a_ptr;
651 mp_limb_t *destptr = r_ptr;
652 mp_twolimb_t accu = 0;
654 for (count = a_len; count > 0; count--)
656 accu += (mp_twolimb_t) *sourceptr++ << s;
657 *destptr++ = (mp_limb_t) accu;
658 accu = accu >> GMP_LIMB_BITS;
660 *destptr++ = (mp_limb_t) accu;
662 q_ptr = roomptr + b_len;
663 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
665 size_t j = a_len - b_len; /* m-n */
666 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
667 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
668 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
669 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
670 /* Division loop, traversed m-n+1 times.
671 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
676 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
678 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
680 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
681 | r_ptr[j + b_len - 1];
682 q_star = num / b_msd;
687 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
688 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
689 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
690 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
691 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
693 If yes, jump directly to the subtraction loop.
694 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
695 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
696 if (r_ptr[j + b_len] > b_msd
697 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
698 /* r[j+n] >= b[n-1]+1 or
699 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
704 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
706 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
707 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
708 mp_twolimb_t c3 = /* b[n-2] * q* */
709 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
710 /* While c2 < c3, increase c2 and decrease c3.
711 Consider c3-c2. While it is > 0, decrease it by
712 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
713 this can happen only twice. */
716 q_star = q_star - 1; /* q* := q* - 1 */
717 if (c3 - c2 > b_msdd)
718 q_star = q_star - 1; /* q* := q* - 1 */
724 /* Subtract r := r - b * q* * beta^j. */
727 const mp_limb_t *sourceptr = b_ptr;
728 mp_limb_t *destptr = r_ptr + j;
729 mp_twolimb_t carry = 0;
731 for (count = b_len; count > 0; count--)
733 /* Here 0 <= carry <= q*. */
736 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
737 + (mp_limb_t) ~(*destptr);
738 /* Here 0 <= carry <= beta*q* + beta-1. */
739 *destptr++ = ~(mp_limb_t) carry;
740 carry = carry >> GMP_LIMB_BITS; /* <= q* */
742 cr = (mp_limb_t) carry;
744 /* Subtract cr from r_ptr[j + b_len], then forget about
746 if (cr > r_ptr[j + b_len])
748 /* Subtraction gave a carry. */
749 q_star = q_star - 1; /* q* := q* - 1 */
752 const mp_limb_t *sourceptr = b_ptr;
753 mp_limb_t *destptr = r_ptr + j;
756 for (count = b_len; count > 0; count--)
758 mp_limb_t source1 = *sourceptr++;
759 mp_limb_t source2 = *destptr;
760 *destptr++ = source1 + source2 + carry;
763 ? source1 >= (mp_limb_t) ~source2
764 : source1 > (mp_limb_t) ~source2);
767 /* Forget about the carry and about r[j+n]. */
770 /* q* is determined. Store it as q[j]. */
779 if (q_ptr[q_len - 1] == 0)
781 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
782 b is shifted left by s bits. */
783 /* Shift r right by s bits. */
786 mp_limb_t ptr = r_ptr + r_len;
787 mp_twolimb_t accu = 0;
789 for (count = r_len; count > 0; count--)
791 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
792 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
793 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
798 while (r_len > 0 && r_ptr[r_len - 1] == 0)
801 /* Compare r << 1 with b. */
809 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
810 | (i < r_len ? r_ptr[i] << 1 : 0);
811 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
821 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
826 for (i = 0; i < q_len; i++)
827 if (++(q_ptr[i]) != 0)
832 if (tmp_roomptr != NULL)
839 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
841 Destroys the contents of a.
842 Return the allocated memory - containing the decimal digits in low-to-high
843 order, terminated with a NUL character - in case of success, NULL in case
844 of memory allocation failure. */
846 convert_to_decimal (mpn_t a, size_t extra_zeroes)
848 mp_limb_t *a_ptr = a.limbs;
849 size_t a_len = a.nlimbs;
850 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
851 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
852 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
856 for (; extra_zeroes > 0; extra_zeroes--)
860 /* Divide a by 10^9, in-place. */
861 mp_limb_t remainder = 0;
862 mp_limb_t *ptr = a_ptr + a_len;
864 for (count = a_len; count > 0; count--)
867 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
868 *ptr = num / 1000000000;
869 remainder = num % 1000000000;
871 /* Store the remainder as 9 decimal digits. */
872 for (count = 9; count > 0; count--)
874 *d_ptr++ = '0' + (remainder % 10);
875 remainder = remainder / 10;
878 if (a_ptr[a_len - 1] == 0)
881 /* Remove leading zeroes. */
882 while (d_ptr > c_ptr && d_ptr[-1] == '0')
884 /* But keep at least one zero. */
887 /* Terminate the string. */
893 # if NEED_PRINTF_LONG_DOUBLE
895 /* Assuming x is finite and >= 0:
896 write x as x = 2^e * m, where m is a bignum.
897 Return the allocated memory in case of success, NULL in case of memory
898 allocation failure. */
900 decode_long_double (long double x, int *ep, mpn_t *mp)
907 /* Allocate memory for result. */
908 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
909 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
912 /* Split into exponential part and mantissa. */
913 y = frexpl (x, &exp);
914 if (!(y >= 0.0L && y < 1.0L))
916 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the
917 latter is an integer. */
918 /* Convert the mantissa (y * 2^LDBL_MANT_BIT) to a sequence of limbs.
919 I'm not sure whether it's safe to cast a 'long double' value between
920 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
921 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
923 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
924 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
927 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
930 if (!(y >= 0.0L && y < 1.0L))
932 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
935 if (!(y >= 0.0L && y < 1.0L))
937 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
942 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
945 if (!(y >= 0.0L && y < 1.0L))
947 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
951 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
954 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
957 if (!(y >= 0.0L && y < 1.0L))
959 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
962 if (!(y >= 0.0L && y < 1.0L))
964 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
966 # if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
972 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
975 *ep = exp - LDBL_MANT_BIT;
981 # if NEED_PRINTF_DOUBLE
983 /* Assuming x is finite and >= 0:
984 write x as x = 2^e * m, where m is a bignum.
985 Return the allocated memory in case of success, NULL in case of memory
986 allocation failure. */
988 decode_double (double x, int *ep, mpn_t *mp)
995 /* Allocate memory for result. */
996 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
997 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
1000 /* Split into exponential part and mantissa. */
1001 y = frexp (x, &exp);
1002 if (!(y >= 0.0 && y < 1.0))
1004 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the
1005 latter is an integer. */
1006 /* Convert the mantissa (y * 2^DBL_MANT_BIT) to a sequence of limbs.
1007 I'm not sure whether it's safe to cast a 'double' value between
1008 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1009 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1011 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
1012 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1015 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
1018 if (!(y >= 0.0 && y < 1.0))
1020 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1023 if (!(y >= 0.0 && y < 1.0))
1025 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1030 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
1033 if (!(y >= 0.0 && y < 1.0))
1035 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
1039 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1042 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1045 if (!(y >= 0.0 && y < 1.0))
1047 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1050 if (!(y >= 0.0 && y < 1.0))
1052 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1057 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1060 *ep = exp - DBL_MANT_BIT;
1066 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1067 Returns the decimal representation of round (x * 10^n).
1068 Return the allocated memory - containing the decimal digits in low-to-high
1069 order, terminated with a NUL character - in case of success, NULL in case
1070 of memory allocation failure. */
1072 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1075 size_t extra_zeroes;
1078 mp_limb_t *pow5_ptr;
1080 unsigned int s_limbs;
1081 unsigned int s_bits;
1089 /* x = 2^e * m, hence
1090 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1091 = round (2^s * 5^n * m). */
1094 /* Factor out a common power of 10 if possible. */
1097 extra_zeroes = (s < n ? s : n);
1101 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1102 Before converting to decimal, we need to compute
1103 z = round (2^s * 5^n * m). */
1104 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1105 sign. 2.322 is slightly larger than log(5)/log(2). */
1106 abs_n = (n >= 0 ? n : -n);
1107 abs_s = (s >= 0 ? s : -s);
1108 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1109 + abs_s / GMP_LIMB_BITS + 1)
1110 * sizeof (mp_limb_t));
1111 if (pow5_ptr == NULL)
1116 /* Initialize with 1. */
1119 /* Multiply with 5^|n|. */
1122 static mp_limb_t const small_pow5[13 + 1] =
1124 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1125 48828125, 244140625, 1220703125
1128 for (n13 = 0; n13 <= abs_n; n13 += 13)
1130 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1132 mp_twolimb_t carry = 0;
1133 for (j = 0; j < pow5_len; j++)
1135 mp_limb_t digit2 = pow5_ptr[j];
1136 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1137 pow5_ptr[j] = (mp_limb_t) carry;
1138 carry = carry >> GMP_LIMB_BITS;
1141 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1144 s_limbs = abs_s / GMP_LIMB_BITS;
1145 s_bits = abs_s % GMP_LIMB_BITS;
1146 if (n >= 0 ? s >= 0 : s <= 0)
1148 /* Multiply with 2^|s|. */
1151 mp_limb_t *ptr = pow5_ptr;
1152 mp_twolimb_t accu = 0;
1154 for (count = pow5_len; count > 0; count--)
1156 accu += (mp_twolimb_t) *ptr << s_bits;
1157 *ptr++ = (mp_limb_t) accu;
1158 accu = accu >> GMP_LIMB_BITS;
1162 *ptr = (mp_limb_t) accu;
1169 for (count = pow5_len; count > 0;)
1172 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1174 for (count = s_limbs; count > 0;)
1177 pow5_ptr[count] = 0;
1179 pow5_len += s_limbs;
1181 pow5.limbs = pow5_ptr;
1182 pow5.nlimbs = pow5_len;
1185 /* Multiply m with pow5. No division needed. */
1186 z_memory = multiply (m, pow5, &z);
1190 /* Divide m by pow5 and round. */
1191 z_memory = divide (m, pow5, &z);
1196 pow5.limbs = pow5_ptr;
1197 pow5.nlimbs = pow5_len;
1201 Multiply m with pow5, then divide by 2^|s|. */
1205 tmp_memory = multiply (m, pow5, &numerator);
1206 if (tmp_memory == NULL)
1212 /* Construct 2^|s|. */
1214 mp_limb_t *ptr = pow5_ptr + pow5_len;
1216 for (i = 0; i < s_limbs; i++)
1218 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1219 denominator.limbs = ptr;
1220 denominator.nlimbs = s_limbs + 1;
1222 z_memory = divide (numerator, denominator, &z);
1228 Multiply m with 2^s, then divide by pow5. */
1231 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1232 * sizeof (mp_limb_t));
1233 if (num_ptr == NULL)
1240 mp_limb_t *destptr = num_ptr;
1243 for (i = 0; i < s_limbs; i++)
1248 const mp_limb_t *sourceptr = m.limbs;
1249 mp_twolimb_t accu = 0;
1251 for (count = m.nlimbs; count > 0; count--)
1253 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1254 *destptr++ = (mp_limb_t) accu;
1255 accu = accu >> GMP_LIMB_BITS;
1258 *destptr++ = (mp_limb_t) accu;
1262 const mp_limb_t *sourceptr = m.limbs;
1264 for (count = m.nlimbs; count > 0; count--)
1265 *destptr++ = *sourceptr++;
1267 numerator.limbs = num_ptr;
1268 numerator.nlimbs = destptr - num_ptr;
1270 z_memory = divide (numerator, pow5, &z);
1277 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1279 if (z_memory == NULL)
1281 digits = convert_to_decimal (z, extra_zeroes);
1286 # if NEED_PRINTF_LONG_DOUBLE
1288 /* Assuming x is finite and >= 0, and n is an integer:
1289 Returns the decimal representation of round (x * 10^n).
1290 Return the allocated memory - containing the decimal digits in low-to-high
1291 order, terminated with a NUL character - in case of success, NULL in case
1292 of memory allocation failure. */
1294 scale10_round_decimal_long_double (long double x, int n)
1298 void *memory = decode_long_double (x, &e, &m);
1299 return scale10_round_decimal_decoded (e, m, memory, n);
1304 # if NEED_PRINTF_DOUBLE
1306 /* Assuming x is finite and >= 0, and n is an integer:
1307 Returns the decimal representation of round (x * 10^n).
1308 Return the allocated memory - containing the decimal digits in low-to-high
1309 order, terminated with a NUL character - in case of success, NULL in case
1310 of memory allocation failure. */
1312 scale10_round_decimal_double (double x, int n)
1316 void *memory = decode_double (x, &e, &m);
1317 return scale10_round_decimal_decoded (e, m, memory, n);
1322 # if NEED_PRINTF_LONG_DOUBLE
1324 /* Assuming x is finite and > 0:
1325 Return an approximation for n with 10^n <= x < 10^(n+1).
1326 The approximation is usually the right n, but may be off by 1 sometimes. */
1328 floorlog10l (long double x)
1335 /* Split into exponential part and mantissa. */
1336 y = frexpl (x, &exp);
1337 if (!(y >= 0.0L && y < 1.0L))
1343 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1345 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1346 exp -= GMP_LIMB_BITS;
1348 if (y < (1.0L / (1 << 16)))
1350 y *= 1.0L * (1 << 16);
1353 if (y < (1.0L / (1 << 8)))
1355 y *= 1.0L * (1 << 8);
1358 if (y < (1.0L / (1 << 4)))
1360 y *= 1.0L * (1 << 4);
1363 if (y < (1.0L / (1 << 2)))
1365 y *= 1.0L * (1 << 2);
1368 if (y < (1.0L / (1 << 1)))
1370 y *= 1.0L * (1 << 1);
1374 if (!(y >= 0.5L && y < 1.0L))
1376 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1379 if (z < 0.70710678118654752444)
1381 z *= 1.4142135623730950488;
1384 if (z < 0.8408964152537145431)
1386 z *= 1.1892071150027210667;
1389 if (z < 0.91700404320467123175)
1391 z *= 1.0905077326652576592;
1394 if (z < 0.9576032806985736469)
1396 z *= 1.0442737824274138403;
1399 /* Now 0.95 <= z <= 1.01. */
1401 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1402 Four terms are enough to get an approximation with error < 10^-7. */
1403 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1404 /* Finally multiply with log(2)/log(10), yields an approximation for
1406 l *= 0.30102999566398119523;
1407 /* Round down to the next integer. */
1408 return (int) l + (l < 0 ? -1 : 0);
1413 # if NEED_PRINTF_DOUBLE
1415 /* Assuming x is finite and > 0:
1416 Return an approximation for n with 10^n <= x < 10^(n+1).
1417 The approximation is usually the right n, but may be off by 1 sometimes. */
1419 floorlog10 (double x)
1426 /* Split into exponential part and mantissa. */
1427 y = frexp (x, &exp);
1428 if (!(y >= 0.0 && y < 1.0))
1434 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1436 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1437 exp -= GMP_LIMB_BITS;
1439 if (y < (1.0 / (1 << 16)))
1441 y *= 1.0 * (1 << 16);
1444 if (y < (1.0 / (1 << 8)))
1446 y *= 1.0 * (1 << 8);
1449 if (y < (1.0 / (1 << 4)))
1451 y *= 1.0 * (1 << 4);
1454 if (y < (1.0 / (1 << 2)))
1456 y *= 1.0 * (1 << 2);
1459 if (y < (1.0 / (1 << 1)))
1461 y *= 1.0 * (1 << 1);
1465 if (!(y >= 0.5 && y < 1.0))
1467 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1470 if (z < 0.70710678118654752444)
1472 z *= 1.4142135623730950488;
1475 if (z < 0.8408964152537145431)
1477 z *= 1.1892071150027210667;
1480 if (z < 0.91700404320467123175)
1482 z *= 1.0905077326652576592;
1485 if (z < 0.9576032806985736469)
1487 z *= 1.0442737824274138403;
1490 /* Now 0.95 <= z <= 1.01. */
1492 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1493 Four terms are enough to get an approximation with error < 10^-7. */
1494 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1495 /* Finally multiply with log(2)/log(10), yields an approximation for
1497 l *= 0.30102999566398119523;
1498 /* Round down to the next integer. */
1499 return (int) l + (l < 0 ? -1 : 0);
1504 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1505 a single '1' digit. */
1507 is_borderline (const char *digits, size_t precision)
1509 for (; precision > 0; precision--, digits++)
1515 return *digits == '\0';
1520 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99
1522 /* Use a different function name, to make it possible that the 'wchar_t'
1523 parametrization and the 'char' parametrization get compiled in the same
1524 translation unit. */
1525 # if WIDE_CHAR_VERSION
1526 # define MAX_ROOM_NEEDED wmax_room_needed
1528 # define MAX_ROOM_NEEDED max_room_needed
1531 /* Returns the number of TCHAR_T units needed as temporary space for the result
1532 of sprintf or SNPRINTF of a single conversion directive. */
1534 MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
1535 arg_type type, int flags, size_t width, int has_precision,
1536 size_t precision, int pad_ourselves)
1542 case 'd': case 'i': case 'u':
1543 # if HAVE_LONG_LONG_INT
1544 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1546 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1547 * 0.30103 /* binary -> decimal */
1549 + 1; /* turn floor into ceil */
1552 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1554 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1555 * 0.30103 /* binary -> decimal */
1557 + 1; /* turn floor into ceil */
1560 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1561 * 0.30103 /* binary -> decimal */
1563 + 1; /* turn floor into ceil */
1564 if (tmp_length < precision)
1565 tmp_length = precision;
1566 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1567 tmp_length = xsum (tmp_length, tmp_length);
1568 /* Add 1, to account for a leading sign. */
1569 tmp_length = xsum (tmp_length, 1);
1573 # if HAVE_LONG_LONG_INT
1574 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1576 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1577 * 0.333334 /* binary -> octal */
1579 + 1; /* turn floor into ceil */
1582 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1584 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1585 * 0.333334 /* binary -> octal */
1587 + 1; /* turn floor into ceil */
1590 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1591 * 0.333334 /* binary -> octal */
1593 + 1; /* turn floor into ceil */
1594 if (tmp_length < precision)
1595 tmp_length = precision;
1596 /* Add 1, to account for a leading sign. */
1597 tmp_length = xsum (tmp_length, 1);
1601 # if HAVE_LONG_LONG_INT
1602 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1604 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1605 * 0.25 /* binary -> hexadecimal */
1607 + 1; /* turn floor into ceil */
1610 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1612 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1613 * 0.25 /* binary -> hexadecimal */
1615 + 1; /* turn floor into ceil */
1618 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1619 * 0.25 /* binary -> hexadecimal */
1621 + 1; /* turn floor into ceil */
1622 if (tmp_length < precision)
1623 tmp_length = precision;
1624 /* Add 2, to account for a leading sign or alternate form. */
1625 tmp_length = xsum (tmp_length, 2);
1629 if (type == TYPE_LONGDOUBLE)
1631 (unsigned int) (LDBL_MAX_EXP
1632 * 0.30103 /* binary -> decimal */
1633 * 2 /* estimate for FLAG_GROUP */
1635 + 1 /* turn floor into ceil */
1636 + 10; /* sign, decimal point etc. */
1639 (unsigned int) (DBL_MAX_EXP
1640 * 0.30103 /* binary -> decimal */
1641 * 2 /* estimate for FLAG_GROUP */
1643 + 1 /* turn floor into ceil */
1644 + 10; /* sign, decimal point etc. */
1645 tmp_length = xsum (tmp_length, precision);
1648 case 'e': case 'E': case 'g': case 'G':
1650 12; /* sign, decimal point, exponent etc. */
1651 tmp_length = xsum (tmp_length, precision);
1655 if (type == TYPE_LONGDOUBLE)
1657 (unsigned int) (LDBL_DIG
1658 * 0.831 /* decimal -> hexadecimal */
1660 + 1; /* turn floor into ceil */
1663 (unsigned int) (DBL_DIG
1664 * 0.831 /* decimal -> hexadecimal */
1666 + 1; /* turn floor into ceil */
1667 if (tmp_length < precision)
1668 tmp_length = precision;
1669 /* Account for sign, decimal point etc. */
1670 tmp_length = xsum (tmp_length, 12);
1674 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
1675 if (type == TYPE_WIDE_CHAR)
1676 tmp_length = MB_CUR_MAX;
1684 if (type == TYPE_WIDE_STRING)
1686 # if WIDE_CHAR_VERSION
1687 /* ISO C says about %ls in fwprintf:
1688 "If the precision is not specified or is greater than the size
1689 of the array, the array shall contain a null wide character."
1690 So if there is a precision, we must not use wcslen. */
1691 const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
1694 tmp_length = local_wcsnlen (arg, precision);
1696 tmp_length = local_wcslen (arg);
1698 /* ISO C says about %ls in fprintf:
1699 "If a precision is specified, no more than that many bytes are
1700 written (including shift sequences, if any), and the array
1701 shall contain a null wide character if, to equal the multibyte
1702 character sequence length given by the precision, the function
1703 would need to access a wide character one past the end of the
1705 So if there is a precision, we must not use wcslen. */
1706 /* This case has already been handled separately in VASNPRINTF. */
1713 # if WIDE_CHAR_VERSION
1714 /* ISO C says about %s in fwprintf:
1715 "If the precision is not specified or is greater than the size
1716 of the converted array, the converted array shall contain a
1717 null wide character."
1718 So if there is a precision, we must not use strlen. */
1719 /* This case has already been handled separately in VASNPRINTF. */
1722 /* ISO C says about %s in fprintf:
1723 "If the precision is not specified or greater than the size of
1724 the array, the array shall contain a null character."
1725 So if there is a precision, we must not use strlen. */
1726 const char *arg = ap->arg[arg_index].a.a_string;
1729 tmp_length = local_strnlen (arg, precision);
1731 tmp_length = strlen (arg);
1738 (unsigned int) (sizeof (void *) * CHAR_BIT
1739 * 0.25 /* binary -> hexadecimal */
1741 + 1 /* turn floor into ceil */
1742 + 2; /* account for leading 0x */
1751 # if ENABLE_UNISTDIO
1752 /* Padding considers the number of characters, therefore the number of
1753 elements after padding may be
1754 > max (tmp_length, width)
1756 <= tmp_length + width. */
1757 tmp_length = xsum (tmp_length, width);
1759 /* Padding considers the number of elements, says POSIX. */
1760 if (tmp_length < width)
1765 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1773 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1774 const FCHAR_T *format, va_list args)
1779 if (PRINTF_PARSE (format, &d, &a) < 0)
1780 /* errno is already set. */
1784 if (d.dir != d.direct_alloc_dir) \
1786 if (a.arg != a.direct_alloc_arg) \
1789 if (PRINTF_FETCHARGS (args, &a) < 0)
1797 size_t buf_neededlength;
1799 TCHAR_T *buf_malloced;
1803 /* Output string accumulator. */
1808 /* Allocate a small buffer that will hold a directive passed to
1809 sprintf or snprintf. */
1811 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1813 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1815 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1816 buf_malloced = NULL;
1821 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1822 if (size_overflow_p (buf_memsize))
1823 goto out_of_memory_1;
1824 buf = (TCHAR_T *) malloc (buf_memsize);
1826 goto out_of_memory_1;
1830 if (resultbuf != NULL)
1833 allocated = *lengthp;
1842 result is either == resultbuf or == NULL or malloc-allocated.
1843 If length > 0, then result != NULL. */
1845 /* Ensures that allocated >= needed. Aborts through a jump to
1846 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1847 #define ENSURE_ALLOCATION(needed) \
1848 if ((needed) > allocated) \
1850 size_t memory_size; \
1853 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1854 if ((needed) > allocated) \
1855 allocated = (needed); \
1856 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1857 if (size_overflow_p (memory_size)) \
1858 goto out_of_memory; \
1859 if (result == resultbuf || result == NULL) \
1860 memory = (DCHAR_T *) malloc (memory_size); \
1862 memory = (DCHAR_T *) realloc (result, memory_size); \
1863 if (memory == NULL) \
1864 goto out_of_memory; \
1865 if (result == resultbuf && length > 0) \
1866 DCHAR_CPY (memory, result, length); \
1870 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1872 if (cp != dp->dir_start)
1874 size_t n = dp->dir_start - cp;
1875 size_t augmented_length = xsum (length, n);
1877 ENSURE_ALLOCATION (augmented_length);
1878 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1879 need that the format string contains only ASCII characters
1880 if FCHAR_T and DCHAR_T are not the same type. */
1881 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1883 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1884 length = augmented_length;
1889 result[length++] = *cp++;
1896 /* Execute a single directive. */
1897 if (dp->conversion == '%')
1899 size_t augmented_length;
1901 if (!(dp->arg_index == ARG_NONE))
1903 augmented_length = xsum (length, 1);
1904 ENSURE_ALLOCATION (augmented_length);
1905 result[length] = '%';
1906 length = augmented_length;
1910 if (!(dp->arg_index != ARG_NONE))
1913 if (dp->conversion == 'n')
1915 switch (a.arg[dp->arg_index].type)
1917 case TYPE_COUNT_SCHAR_POINTER:
1918 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1920 case TYPE_COUNT_SHORT_POINTER:
1921 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1923 case TYPE_COUNT_INT_POINTER:
1924 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1926 case TYPE_COUNT_LONGINT_POINTER:
1927 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1929 #if HAVE_LONG_LONG_INT
1930 case TYPE_COUNT_LONGLONGINT_POINTER:
1931 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1939 /* The unistdio extensions. */
1940 else if (dp->conversion == 'U')
1942 arg_type type = a.arg[dp->arg_index].type;
1943 int flags = dp->flags;
1951 if (dp->width_start != dp->width_end)
1953 if (dp->width_arg_index != ARG_NONE)
1957 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1959 arg = a.arg[dp->width_arg_index].a.a_int;
1963 /* "A negative field width is taken as a '-' flag
1964 followed by a positive field width." */
1971 const FCHAR_T *digitp = dp->width_start;
1974 width = xsum (xtimes (width, 10), *digitp++ - '0');
1975 while (digitp != dp->width_end);
1982 if (dp->precision_start != dp->precision_end)
1984 if (dp->precision_arg_index != ARG_NONE)
1988 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1990 arg = a.arg[dp->precision_arg_index].a.a_int;
1991 /* "A negative precision is taken as if the precision
2001 const FCHAR_T *digitp = dp->precision_start + 1;
2004 while (digitp != dp->precision_end)
2005 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2012 case TYPE_U8_STRING:
2014 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
2015 const uint8_t *arg_end;
2020 /* Use only PRECISION characters, from the left. */
2023 for (; precision > 0; precision--)
2025 int count = u8_strmblen (arg_end);
2030 if (!(result == resultbuf || result == NULL))
2032 if (buf_malloced != NULL)
2033 free (buf_malloced);
2044 /* Use the entire string, and count the number of
2050 int count = u8_strmblen (arg_end);
2055 if (!(result == resultbuf || result == NULL))
2057 if (buf_malloced != NULL)
2058 free (buf_malloced);
2069 /* Use the entire string. */
2070 arg_end = arg + u8_strlen (arg);
2071 /* The number of characters doesn't matter. */
2075 if (characters < width && !(dp->flags & FLAG_LEFT))
2077 size_t n = width - characters;
2078 ENSURE_ALLOCATION (xsum (length, n));
2079 DCHAR_SET (result + length, ' ', n);
2083 # if DCHAR_IS_UINT8_T
2085 size_t n = arg_end - arg;
2086 ENSURE_ALLOCATION (xsum (length, n));
2087 DCHAR_CPY (result + length, arg, n);
2092 DCHAR_T *converted = result + length;
2093 size_t converted_len = allocated - length;
2095 /* Convert from UTF-8 to locale encoding. */
2097 u8_conv_to_encoding (locale_charset (),
2098 iconveh_question_mark,
2099 arg, arg_end - arg, NULL,
2100 converted, &converted_len);
2102 /* Convert from UTF-8 to UTF-16/UTF-32. */
2104 U8_TO_DCHAR (arg, arg_end - arg,
2105 converted, &converted_len);
2107 if (converted == NULL)
2109 int saved_errno = errno;
2110 if (!(result == resultbuf || result == NULL))
2112 if (buf_malloced != NULL)
2113 free (buf_malloced);
2115 errno = saved_errno;
2118 if (converted != result + length)
2120 ENSURE_ALLOCATION (xsum (length, converted_len));
2121 DCHAR_CPY (result + length, converted, converted_len);
2124 length += converted_len;
2128 if (characters < width && (dp->flags & FLAG_LEFT))
2130 size_t n = width - characters;
2131 ENSURE_ALLOCATION (xsum (length, n));
2132 DCHAR_SET (result + length, ' ', n);
2138 case TYPE_U16_STRING:
2140 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
2141 const uint16_t *arg_end;
2146 /* Use only PRECISION characters, from the left. */
2149 for (; precision > 0; precision--)
2151 int count = u16_strmblen (arg_end);
2156 if (!(result == resultbuf || result == NULL))
2158 if (buf_malloced != NULL)
2159 free (buf_malloced);
2170 /* Use the entire string, and count the number of
2176 int count = u16_strmblen (arg_end);
2181 if (!(result == resultbuf || result == NULL))
2183 if (buf_malloced != NULL)
2184 free (buf_malloced);
2195 /* Use the entire string. */
2196 arg_end = arg + u16_strlen (arg);
2197 /* The number of characters doesn't matter. */
2201 if (characters < width && !(dp->flags & FLAG_LEFT))
2203 size_t n = width - characters;
2204 ENSURE_ALLOCATION (xsum (length, n));
2205 DCHAR_SET (result + length, ' ', n);
2209 # if DCHAR_IS_UINT16_T
2211 size_t n = arg_end - arg;
2212 ENSURE_ALLOCATION (xsum (length, n));
2213 DCHAR_CPY (result + length, arg, n);
2218 DCHAR_T *converted = result + length;
2219 size_t converted_len = allocated - length;
2221 /* Convert from UTF-16 to locale encoding. */
2223 u16_conv_to_encoding (locale_charset (),
2224 iconveh_question_mark,
2225 arg, arg_end - arg, NULL,
2226 converted, &converted_len);
2228 /* Convert from UTF-16 to UTF-8/UTF-32. */
2230 U16_TO_DCHAR (arg, arg_end - arg,
2231 converted, &converted_len);
2233 if (converted == NULL)
2235 int saved_errno = errno;
2236 if (!(result == resultbuf || result == NULL))
2238 if (buf_malloced != NULL)
2239 free (buf_malloced);
2241 errno = saved_errno;
2244 if (converted != result + length)
2246 ENSURE_ALLOCATION (xsum (length, converted_len));
2247 DCHAR_CPY (result + length, converted, converted_len);
2250 length += converted_len;
2254 if (characters < width && (dp->flags & FLAG_LEFT))
2256 size_t n = width - characters;
2257 ENSURE_ALLOCATION (xsum (length, n));
2258 DCHAR_SET (result + length, ' ', n);
2264 case TYPE_U32_STRING:
2266 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
2267 const uint32_t *arg_end;
2272 /* Use only PRECISION characters, from the left. */
2275 for (; precision > 0; precision--)
2277 int count = u32_strmblen (arg_end);
2282 if (!(result == resultbuf || result == NULL))
2284 if (buf_malloced != NULL)
2285 free (buf_malloced);
2296 /* Use the entire string, and count the number of
2302 int count = u32_strmblen (arg_end);
2307 if (!(result == resultbuf || result == NULL))
2309 if (buf_malloced != NULL)
2310 free (buf_malloced);
2321 /* Use the entire string. */
2322 arg_end = arg + u32_strlen (arg);
2323 /* The number of characters doesn't matter. */
2327 if (characters < width && !(dp->flags & FLAG_LEFT))
2329 size_t n = width - characters;
2330 ENSURE_ALLOCATION (xsum (length, n));
2331 DCHAR_SET (result + length, ' ', n);
2335 # if DCHAR_IS_UINT32_T
2337 size_t n = arg_end - arg;
2338 ENSURE_ALLOCATION (xsum (length, n));
2339 DCHAR_CPY (result + length, arg, n);
2344 DCHAR_T *converted = result + length;
2345 size_t converted_len = allocated - length;
2347 /* Convert from UTF-32 to locale encoding. */
2349 u32_conv_to_encoding (locale_charset (),
2350 iconveh_question_mark,
2351 arg, arg_end - arg, NULL,
2352 converted, &converted_len);
2354 /* Convert from UTF-32 to UTF-8/UTF-16. */
2356 U32_TO_DCHAR (arg, arg_end - arg,
2357 converted, &converted_len);
2359 if (converted == NULL)
2361 int saved_errno = errno;
2362 if (!(result == resultbuf || result == NULL))
2364 if (buf_malloced != NULL)
2365 free (buf_malloced);
2367 errno = saved_errno;
2370 if (converted != result + length)
2372 ENSURE_ALLOCATION (xsum (length, converted_len));
2373 DCHAR_CPY (result + length, converted, converted_len);
2376 length += converted_len;
2380 if (characters < width && (dp->flags & FLAG_LEFT))
2382 size_t n = width - characters;
2383 ENSURE_ALLOCATION (xsum (length, n));
2384 DCHAR_SET (result + length, ' ', n);
2395 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T
2396 else if (dp->conversion == 's'
2397 # if WIDE_CHAR_VERSION
2398 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2400 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2404 /* The normal handling of the 's' directive below requires
2405 allocating a temporary buffer. The determination of its
2406 length (tmp_length), in the case when a precision is
2407 specified, below requires a conversion between a char[]
2408 string and a wchar_t[] wide string. It could be done, but
2409 we have no guarantee that the implementation of sprintf will
2410 use the exactly same algorithm. Without this guarantee, it
2411 is possible to have buffer overrun bugs. In order to avoid
2412 such bugs, we implement the entire processing of the 's'
2413 directive ourselves. */
2414 int flags = dp->flags;
2422 if (dp->width_start != dp->width_end)
2424 if (dp->width_arg_index != ARG_NONE)
2428 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2430 arg = a.arg[dp->width_arg_index].a.a_int;
2434 /* "A negative field width is taken as a '-' flag
2435 followed by a positive field width." */
2442 const FCHAR_T *digitp = dp->width_start;
2445 width = xsum (xtimes (width, 10), *digitp++ - '0');
2446 while (digitp != dp->width_end);
2453 if (dp->precision_start != dp->precision_end)
2455 if (dp->precision_arg_index != ARG_NONE)
2459 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2461 arg = a.arg[dp->precision_arg_index].a.a_int;
2462 /* "A negative precision is taken as if the precision
2472 const FCHAR_T *digitp = dp->precision_start + 1;
2475 while (digitp != dp->precision_end)
2476 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2481 # if WIDE_CHAR_VERSION
2482 /* %s in vasnwprintf. See the specification of fwprintf. */
2484 const char *arg = a.arg[dp->arg_index].a.a_string;
2485 const char *arg_end;
2490 /* Use only as many bytes as needed to produce PRECISION
2491 wide characters, from the left. */
2494 memset (&state, '\0', sizeof (mbstate_t));
2498 for (; precision > 0; precision--)
2502 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2504 count = mblen (arg_end, MB_CUR_MAX);
2507 /* Found the terminating NUL. */
2511 /* Invalid or incomplete multibyte character. */
2512 if (!(result == resultbuf || result == NULL))
2514 if (buf_malloced != NULL)
2515 free (buf_malloced);
2526 /* Use the entire string, and count the number of wide
2530 memset (&state, '\0', sizeof (mbstate_t));
2538 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2540 count = mblen (arg_end, MB_CUR_MAX);
2543 /* Found the terminating NUL. */
2547 /* Invalid or incomplete multibyte character. */
2548 if (!(result == resultbuf || result == NULL))
2550 if (buf_malloced != NULL)
2551 free (buf_malloced);
2562 /* Use the entire string. */
2563 arg_end = arg + strlen (arg);
2564 /* The number of characters doesn't matter. */
2568 if (characters < width && !(dp->flags & FLAG_LEFT))
2570 size_t n = width - characters;
2571 ENSURE_ALLOCATION (xsum (length, n));
2572 DCHAR_SET (result + length, ' ', n);
2576 if (has_precision || has_width)
2578 /* We know the number of wide characters in advance. */
2582 memset (&state, '\0', sizeof (mbstate_t));
2584 ENSURE_ALLOCATION (xsum (length, characters));
2585 for (remaining = characters; remaining > 0; remaining--)
2590 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2592 count = mbtowc (&wc, arg, arg_end - arg);
2595 /* mbrtowc not consistent with mbrlen, or mbtowc
2596 not consistent with mblen. */
2598 result[length++] = wc;
2601 if (!(arg == arg_end))
2608 memset (&state, '\0', sizeof (mbstate_t));
2610 while (arg < arg_end)
2615 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2617 count = mbtowc (&wc, arg, arg_end - arg);
2620 /* mbrtowc not consistent with mbrlen, or mbtowc
2621 not consistent with mblen. */
2623 ENSURE_ALLOCATION (xsum (length, 1));
2624 result[length++] = wc;
2629 if (characters < width && (dp->flags & FLAG_LEFT))
2631 size_t n = width - characters;
2632 ENSURE_ALLOCATION (xsum (length, n));
2633 DCHAR_SET (result + length, ' ', n);
2638 /* %ls in vasnprintf. See the specification of fprintf. */
2640 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2641 const wchar_t *arg_end;
2643 # if !DCHAR_IS_TCHAR
2644 /* This code assumes that TCHAR_T is 'char'. */
2645 verify (sizeof (TCHAR_T) == 1);
2654 /* Use only as many wide characters as needed to produce
2655 at most PRECISION bytes, from the left. */
2656 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2658 memset (&state, '\0', sizeof (mbstate_t));
2662 while (precision > 0)
2664 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2668 /* Found the terminating null wide character. */
2670 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2671 count = wcrtomb (cbuf, *arg_end, &state);
2673 count = wctomb (cbuf, *arg_end);
2677 /* Cannot convert. */
2678 if (!(result == resultbuf || result == NULL))
2680 if (buf_malloced != NULL)
2681 free (buf_malloced);
2686 if (precision < count)
2689 characters += count;
2699 /* Use the entire string, and count the number of
2701 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2703 memset (&state, '\0', sizeof (mbstate_t));
2709 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2713 /* Found the terminating null wide character. */
2715 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2716 count = wcrtomb (cbuf, *arg_end, &state);
2718 count = wctomb (cbuf, *arg_end);
2722 /* Cannot convert. */
2723 if (!(result == resultbuf || result == NULL))
2725 if (buf_malloced != NULL)
2726 free (buf_malloced);
2732 characters += count;
2738 /* Use the entire string. */
2739 arg_end = arg + local_wcslen (arg);
2740 /* The number of bytes doesn't matter. */
2745 # if !DCHAR_IS_TCHAR
2746 /* Convert the string into a piece of temporary memory. */
2747 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2751 TCHAR_T *tmpptr = tmpsrc;
2753 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2755 memset (&state, '\0', sizeof (mbstate_t));
2757 for (remaining = characters; remaining > 0; )
2759 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2764 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2765 count = wcrtomb (cbuf, *arg, &state);
2767 count = wctomb (cbuf, *arg);
2770 /* Inconsistency. */
2772 memcpy (tmpptr, cbuf, count);
2777 if (!(arg == arg_end))
2781 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2783 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2784 iconveh_question_mark,
2790 int saved_errno = errno;
2792 if (!(result == resultbuf || result == NULL))
2794 if (buf_malloced != NULL)
2795 free (buf_malloced);
2797 errno = saved_errno;
2805 # if ENABLE_UNISTDIO
2806 /* Outside POSIX, it's preferable to compare the width
2807 against the number of _characters_ of the converted
2809 w = DCHAR_MBSNLEN (result + length, characters);
2811 /* The width is compared against the number of _bytes_
2812 of the converted value, says POSIX. */
2817 /* w doesn't matter. */
2820 if (w < width && !(dp->flags & FLAG_LEFT))
2822 size_t n = width - w;
2823 ENSURE_ALLOCATION (xsum (length, n));
2824 DCHAR_SET (result + length, ' ', n);
2829 if (has_precision || has_width)
2831 /* We know the number of bytes in advance. */
2833 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2835 memset (&state, '\0', sizeof (mbstate_t));
2837 ENSURE_ALLOCATION (xsum (length, characters));
2838 for (remaining = characters; remaining > 0; )
2840 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2845 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2846 count = wcrtomb (cbuf, *arg, &state);
2848 count = wctomb (cbuf, *arg);
2851 /* Inconsistency. */
2853 memcpy (result + length, cbuf, count);
2858 if (!(arg == arg_end))
2863 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2865 memset (&state, '\0', sizeof (mbstate_t));
2867 while (arg < arg_end)
2869 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2874 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2875 count = wcrtomb (cbuf, *arg, &state);
2877 count = wctomb (cbuf, *arg);
2881 /* Cannot convert. */
2882 if (!(result == resultbuf || result == NULL))
2884 if (buf_malloced != NULL)
2885 free (buf_malloced);
2890 ENSURE_ALLOCATION (xsum (length, count));
2891 memcpy (result + length, cbuf, count);
2897 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2898 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2900 length += tmpdst_len;
2903 if (w < width && (dp->flags & FLAG_LEFT))
2905 size_t n = width - w;
2906 ENSURE_ALLOCATION (xsum (length, n));
2907 DCHAR_SET (result + length, ' ', n);
2914 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2915 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2916 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2918 # if NEED_PRINTF_DOUBLE
2919 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2921 # if NEED_PRINTF_LONG_DOUBLE
2922 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2928 arg_type type = a.arg[dp->arg_index].type;
2929 int flags = dp->flags;
2935 DCHAR_T tmpbuf[700];
2941 if (dp->width_start != dp->width_end)
2943 if (dp->width_arg_index != ARG_NONE)
2947 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2949 arg = a.arg[dp->width_arg_index].a.a_int;
2953 /* "A negative field width is taken as a '-' flag
2954 followed by a positive field width." */
2961 const FCHAR_T *digitp = dp->width_start;
2964 width = xsum (xtimes (width, 10), *digitp++ - '0');
2965 while (digitp != dp->width_end);
2971 if (dp->precision_start != dp->precision_end)
2973 if (dp->precision_arg_index != ARG_NONE)
2977 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2979 arg = a.arg[dp->precision_arg_index].a.a_int;
2980 /* "A negative precision is taken as if the precision
2990 const FCHAR_T *digitp = dp->precision_start + 1;
2993 while (digitp != dp->precision_end)
2994 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2999 /* Allocate a temporary buffer of sufficient size. */
3000 if (type == TYPE_LONGDOUBLE)
3002 (unsigned int) ((LDBL_DIG + 1)
3003 * 0.831 /* decimal -> hexadecimal */
3005 + 1; /* turn floor into ceil */
3008 (unsigned int) ((DBL_DIG + 1)
3009 * 0.831 /* decimal -> hexadecimal */
3011 + 1; /* turn floor into ceil */
3012 if (tmp_length < precision)
3013 tmp_length = precision;
3014 /* Account for sign, decimal point etc. */
3015 tmp_length = xsum (tmp_length, 12);
3017 if (tmp_length < width)
3020 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3022 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3026 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3028 if (size_overflow_p (tmp_memsize))
3029 /* Overflow, would lead to out of memory. */
3031 tmp = (DCHAR_T *) malloc (tmp_memsize);
3033 /* Out of memory. */
3039 if (type == TYPE_LONGDOUBLE)
3041 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
3042 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3046 if (dp->conversion == 'A')
3048 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3052 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3058 DECL_LONG_DOUBLE_ROUNDING
3060 BEGIN_LONG_DOUBLE_ROUNDING ();
3062 if (signbit (arg)) /* arg < 0.0L or negative zero */
3070 else if (flags & FLAG_SHOWSIGN)
3072 else if (flags & FLAG_SPACE)
3075 if (arg > 0.0L && arg + arg == arg)
3077 if (dp->conversion == 'A')
3079 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3083 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3089 long double mantissa;
3092 mantissa = printf_frexpl (arg, &exponent);
3100 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
3102 /* Round the mantissa. */
3103 long double tail = mantissa;
3106 for (q = precision; ; q--)
3108 int digit = (int) tail;
3112 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
3121 for (q = precision; q > 0; q--)
3127 *p++ = dp->conversion - 'A' + 'X';
3132 digit = (int) mantissa;
3135 if ((flags & FLAG_ALT)
3136 || mantissa > 0.0L || precision > 0)
3138 *p++ = decimal_point_char ();
3139 /* This loop terminates because we assume
3140 that FLT_RADIX is a power of 2. */
3141 while (mantissa > 0.0L)
3144 digit = (int) mantissa;
3149 : dp->conversion - 10);
3153 while (precision > 0)
3160 *p++ = dp->conversion - 'A' + 'P';
3161 # if WIDE_CHAR_VERSION
3163 static const wchar_t decimal_format[] =
3164 { '%', '+', 'd', '\0' };
3165 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3170 if (sizeof (DCHAR_T) == 1)
3172 sprintf ((char *) p, "%+d", exponent);
3180 sprintf (expbuf, "%+d", exponent);
3181 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3187 END_LONG_DOUBLE_ROUNDING ();
3195 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
3196 double arg = a.arg[dp->arg_index].a.a_double;
3200 if (dp->conversion == 'A')
3202 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3206 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3213 if (signbit (arg)) /* arg < 0.0 or negative zero */
3221 else if (flags & FLAG_SHOWSIGN)
3223 else if (flags & FLAG_SPACE)
3226 if (arg > 0.0 && arg + arg == arg)
3228 if (dp->conversion == 'A')
3230 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3234 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3243 mantissa = printf_frexp (arg, &exponent);
3251 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
3253 /* Round the mantissa. */
3254 double tail = mantissa;
3257 for (q = precision; ; q--)
3259 int digit = (int) tail;
3263 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
3272 for (q = precision; q > 0; q--)
3278 *p++ = dp->conversion - 'A' + 'X';
3283 digit = (int) mantissa;
3286 if ((flags & FLAG_ALT)
3287 || mantissa > 0.0 || precision > 0)
3289 *p++ = decimal_point_char ();
3290 /* This loop terminates because we assume
3291 that FLT_RADIX is a power of 2. */
3292 while (mantissa > 0.0)
3295 digit = (int) mantissa;
3300 : dp->conversion - 10);
3304 while (precision > 0)
3311 *p++ = dp->conversion - 'A' + 'P';
3312 # if WIDE_CHAR_VERSION
3314 static const wchar_t decimal_format[] =
3315 { '%', '+', 'd', '\0' };
3316 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3321 if (sizeof (DCHAR_T) == 1)
3323 sprintf ((char *) p, "%+d", exponent);
3331 sprintf (expbuf, "%+d", exponent);
3332 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3343 /* The generated string now extends from tmp to p, with the
3344 zero padding insertion point being at pad_ptr. */
3349 size_t pad = width - count;
3350 DCHAR_T *end = p + pad;
3352 if (flags & FLAG_LEFT)
3354 /* Pad with spaces on the right. */
3355 for (; pad > 0; pad--)
3358 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3360 /* Pad with zeroes. */
3365 for (; pad > 0; pad--)
3370 /* Pad with spaces on the left. */
3375 for (; pad > 0; pad--)
3384 if (count >= tmp_length)
3385 /* tmp_length was incorrectly calculated - fix the
3389 /* Make room for the result. */
3390 if (count >= allocated - length)
3392 size_t n = xsum (length, count);
3394 ENSURE_ALLOCATION (n);
3397 /* Append the result. */
3398 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3404 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3405 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3406 || dp->conversion == 'e' || dp->conversion == 'E'
3407 || dp->conversion == 'g' || dp->conversion == 'G'
3408 || dp->conversion == 'a' || dp->conversion == 'A')
3410 # if NEED_PRINTF_DOUBLE
3411 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3412 # elif NEED_PRINTF_INFINITE_DOUBLE
3413 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3414 /* The systems (mingw) which produce wrong output
3415 for Inf, -Inf, and NaN also do so for -0.0.
3416 Therefore we treat this case here as well. */
3417 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3419 # if NEED_PRINTF_LONG_DOUBLE
3420 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3421 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3422 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3423 /* Some systems produce wrong output for Inf,
3424 -Inf, and NaN. Some systems in this category
3425 (IRIX 5.3) also do so for -0.0. Therefore we
3426 treat this case here as well. */
3427 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3431 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3432 arg_type type = a.arg[dp->arg_index].type;
3434 int flags = dp->flags;
3440 DCHAR_T tmpbuf[700];
3446 if (dp->width_start != dp->width_end)
3448 if (dp->width_arg_index != ARG_NONE)
3452 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3454 arg = a.arg[dp->width_arg_index].a.a_int;
3458 /* "A negative field width is taken as a '-' flag
3459 followed by a positive field width." */
3466 const FCHAR_T *digitp = dp->width_start;
3469 width = xsum (xtimes (width, 10), *digitp++ - '0');
3470 while (digitp != dp->width_end);
3476 if (dp->precision_start != dp->precision_end)
3478 if (dp->precision_arg_index != ARG_NONE)
3482 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3484 arg = a.arg[dp->precision_arg_index].a.a_int;
3485 /* "A negative precision is taken as if the precision
3495 const FCHAR_T *digitp = dp->precision_start + 1;
3498 while (digitp != dp->precision_end)
3499 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3504 /* POSIX specifies the default precision to be 6 for %f, %F,
3505 %e, %E, but not for %g, %G. Implementations appear to use
3506 the same default precision also for %g, %G. But for %a, %A,
3507 the default precision is 0. */
3509 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3512 /* Allocate a temporary buffer of sufficient size. */
3513 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3514 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3515 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3516 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3517 # elif NEED_PRINTF_LONG_DOUBLE
3518 tmp_length = LDBL_DIG + 1;
3519 # elif NEED_PRINTF_DOUBLE
3520 tmp_length = DBL_DIG + 1;
3524 if (tmp_length < precision)
3525 tmp_length = precision;
3526 # if NEED_PRINTF_LONG_DOUBLE
3527 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3528 if (type == TYPE_LONGDOUBLE)
3530 if (dp->conversion == 'f' || dp->conversion == 'F')
3532 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3533 if (!(isnanl (arg) || arg + arg == arg))
3535 /* arg is finite and nonzero. */
3536 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3537 if (exponent >= 0 && tmp_length < exponent + precision)
3538 tmp_length = exponent + precision;
3542 # if NEED_PRINTF_DOUBLE
3543 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3544 if (type == TYPE_DOUBLE)
3546 if (dp->conversion == 'f' || dp->conversion == 'F')
3548 double arg = a.arg[dp->arg_index].a.a_double;
3549 if (!(isnand (arg) || arg + arg == arg))
3551 /* arg is finite and nonzero. */
3552 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3553 if (exponent >= 0 && tmp_length < exponent + precision)
3554 tmp_length = exponent + precision;
3558 /* Account for sign, decimal point etc. */
3559 tmp_length = xsum (tmp_length, 12);
3561 if (tmp_length < width)
3564 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3566 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3570 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3572 if (size_overflow_p (tmp_memsize))
3573 /* Overflow, would lead to out of memory. */
3575 tmp = (DCHAR_T *) malloc (tmp_memsize);
3577 /* Out of memory. */
3584 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3585 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3586 if (type == TYPE_LONGDOUBLE)
3589 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3593 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3595 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3599 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3605 DECL_LONG_DOUBLE_ROUNDING
3607 BEGIN_LONG_DOUBLE_ROUNDING ();
3609 if (signbit (arg)) /* arg < 0.0L or negative zero */
3617 else if (flags & FLAG_SHOWSIGN)
3619 else if (flags & FLAG_SPACE)
3622 if (arg > 0.0L && arg + arg == arg)
3624 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3626 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3630 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3635 # if NEED_PRINTF_LONG_DOUBLE
3638 if (dp->conversion == 'f' || dp->conversion == 'F')
3644 scale10_round_decimal_long_double (arg, precision);
3647 END_LONG_DOUBLE_ROUNDING ();
3650 ndigits = strlen (digits);
3652 if (ndigits > precision)
3656 *p++ = digits[ndigits];
3658 while (ndigits > precision);
3661 /* Here ndigits <= precision. */
3662 if ((flags & FLAG_ALT) || precision > 0)
3664 *p++ = decimal_point_char ();
3665 for (; precision > ndigits; precision--)
3670 *p++ = digits[ndigits];
3676 else if (dp->conversion == 'e' || dp->conversion == 'E')
3684 if ((flags & FLAG_ALT) || precision > 0)
3686 *p++ = decimal_point_char ();
3687 for (; precision > 0; precision--)
3698 exponent = floorlog10l (arg);
3703 scale10_round_decimal_long_double (arg,
3704 (int)precision - exponent);
3707 END_LONG_DOUBLE_ROUNDING ();
3710 ndigits = strlen (digits);
3712 if (ndigits == precision + 1)
3714 if (ndigits < precision
3715 || ndigits > precision + 2)
3716 /* The exponent was not guessed
3717 precisely enough. */
3720 /* None of two values of exponent is
3721 the right one. Prevent an endless
3725 if (ndigits == precision)
3731 /* Here ndigits = precision+1. */
3732 if (is_borderline (digits, precision))
3734 /* Maybe the exponent guess was too high
3735 and a smaller exponent can be reached
3736 by turning a 10...0 into 9...9x. */
3738 scale10_round_decimal_long_double (arg,
3739 (int)precision - exponent + 1);
3740 if (digits2 == NULL)
3743 END_LONG_DOUBLE_ROUNDING ();
3746 if (strlen (digits2) == precision + 1)
3755 /* Here ndigits = precision+1. */
3757 *p++ = digits[--ndigits];
3758 if ((flags & FLAG_ALT) || precision > 0)
3760 *p++ = decimal_point_char ();
3764 *p++ = digits[ndigits];
3771 *p++ = dp->conversion; /* 'e' or 'E' */
3772 # if WIDE_CHAR_VERSION
3774 static const wchar_t decimal_format[] =
3775 { '%', '+', '.', '2', 'd', '\0' };
3776 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3781 if (sizeof (DCHAR_T) == 1)
3783 sprintf ((char *) p, "%+.2d", exponent);
3791 sprintf (expbuf, "%+.2d", exponent);
3792 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3797 else if (dp->conversion == 'g' || dp->conversion == 'G')
3801 /* precision >= 1. */
3804 /* The exponent is 0, >= -4, < precision.
3805 Use fixed-point notation. */
3807 size_t ndigits = precision;
3808 /* Number of trailing zeroes that have to be
3811 (flags & FLAG_ALT ? 0 : precision - 1);
3815 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3817 *p++ = decimal_point_char ();
3818 while (ndigits > nzeroes)
3834 exponent = floorlog10l (arg);
3839 scale10_round_decimal_long_double (arg,
3840 (int)(precision - 1) - exponent);
3843 END_LONG_DOUBLE_ROUNDING ();
3846 ndigits = strlen (digits);
3848 if (ndigits == precision)
3850 if (ndigits < precision - 1
3851 || ndigits > precision + 1)
3852 /* The exponent was not guessed
3853 precisely enough. */
3856 /* None of two values of exponent is
3857 the right one. Prevent an endless
3861 if (ndigits < precision)
3867 /* Here ndigits = precision. */
3868 if (is_borderline (digits, precision - 1))
3870 /* Maybe the exponent guess was too high
3871 and a smaller exponent can be reached
3872 by turning a 10...0 into 9...9x. */
3874 scale10_round_decimal_long_double (arg,
3875 (int)(precision - 1) - exponent + 1);
3876 if (digits2 == NULL)
3879 END_LONG_DOUBLE_ROUNDING ();
3882 if (strlen (digits2) == precision)
3891 /* Here ndigits = precision. */
3893 /* Determine the number of trailing zeroes
3894 that have to be dropped. */
3896 if ((flags & FLAG_ALT) == 0)
3897 while (nzeroes < ndigits
3898 && digits[nzeroes] == '0')
3901 /* The exponent is now determined. */
3903 && exponent < (long)precision)
3905 /* Fixed-point notation:
3906 max(exponent,0)+1 digits, then the
3907 decimal point, then the remaining
3908 digits without trailing zeroes. */
3911 size_t ecount = exponent + 1;
3912 /* Note: count <= precision = ndigits. */
3913 for (; ecount > 0; ecount--)
3914 *p++ = digits[--ndigits];
3915 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3917 *p++ = decimal_point_char ();
3918 while (ndigits > nzeroes)
3921 *p++ = digits[ndigits];
3927 size_t ecount = -exponent - 1;
3929 *p++ = decimal_point_char ();
3930 for (; ecount > 0; ecount--)
3932 while (ndigits > nzeroes)
3935 *p++ = digits[ndigits];
3941 /* Exponential notation. */
3942 *p++ = digits[--ndigits];
3943 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3945 *p++ = decimal_point_char ();
3946 while (ndigits > nzeroes)
3949 *p++ = digits[ndigits];
3952 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3953 # if WIDE_CHAR_VERSION
3955 static const wchar_t decimal_format[] =
3956 { '%', '+', '.', '2', 'd', '\0' };
3957 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3962 if (sizeof (DCHAR_T) == 1)
3964 sprintf ((char *) p, "%+.2d", exponent);
3972 sprintf (expbuf, "%+.2d", exponent);
3973 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3985 /* arg is finite. */
3991 if (dp->conversion == 'f' || dp->conversion == 'F')
3994 if ((flags & FLAG_ALT) || precision > 0)
3996 *p++ = decimal_point_char ();
3997 for (; precision > 0; precision--)
4001 else if (dp->conversion == 'e' || dp->conversion == 'E')
4004 if ((flags & FLAG_ALT) || precision > 0)
4006 *p++ = decimal_point_char ();
4007 for (; precision > 0; precision--)
4010 *p++ = dp->conversion; /* 'e' or 'E' */
4015 else if (dp->conversion == 'g' || dp->conversion == 'G')
4018 if (flags & FLAG_ALT)
4021 (precision > 0 ? precision - 1 : 0);
4022 *p++ = decimal_point_char ();
4023 for (; ndigits > 0; --ndigits)
4027 else if (dp->conversion == 'a' || dp->conversion == 'A')
4030 *p++ = dp->conversion - 'A' + 'X';
4033 if ((flags & FLAG_ALT) || precision > 0)
4035 *p++ = decimal_point_char ();
4036 for (; precision > 0; precision--)
4039 *p++ = dp->conversion - 'A' + 'P';
4048 END_LONG_DOUBLE_ROUNDING ();
4051 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4055 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4057 double arg = a.arg[dp->arg_index].a.a_double;
4061 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4063 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4067 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4074 if (signbit (arg)) /* arg < 0.0 or negative zero */
4082 else if (flags & FLAG_SHOWSIGN)
4084 else if (flags & FLAG_SPACE)
4087 if (arg > 0.0 && arg + arg == arg)
4089 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4091 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4095 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4100 # if NEED_PRINTF_DOUBLE
4103 if (dp->conversion == 'f' || dp->conversion == 'F')
4109 scale10_round_decimal_double (arg, precision);
4112 ndigits = strlen (digits);
4114 if (ndigits > precision)
4118 *p++ = digits[ndigits];
4120 while (ndigits > precision);
4123 /* Here ndigits <= precision. */
4124 if ((flags & FLAG_ALT) || precision > 0)
4126 *p++ = decimal_point_char ();
4127 for (; precision > ndigits; precision--)
4132 *p++ = digits[ndigits];
4138 else if (dp->conversion == 'e' || dp->conversion == 'E')
4146 if ((flags & FLAG_ALT) || precision > 0)
4148 *p++ = decimal_point_char ();
4149 for (; precision > 0; precision--)
4160 exponent = floorlog10 (arg);
4165 scale10_round_decimal_double (arg,
4166 (int)precision - exponent);
4169 ndigits = strlen (digits);
4171 if (ndigits == precision + 1)
4173 if (ndigits < precision
4174 || ndigits > precision + 2)
4175 /* The exponent was not guessed
4176 precisely enough. */
4179 /* None of two values of exponent is
4180 the right one. Prevent an endless
4184 if (ndigits == precision)
4190 /* Here ndigits = precision+1. */
4191 if (is_borderline (digits, precision))
4193 /* Maybe the exponent guess was too high
4194 and a smaller exponent can be reached
4195 by turning a 10...0 into 9...9x. */
4197 scale10_round_decimal_double (arg,
4198 (int)precision - exponent + 1);
4199 if (digits2 == NULL)
4204 if (strlen (digits2) == precision + 1)
4213 /* Here ndigits = precision+1. */
4215 *p++ = digits[--ndigits];
4216 if ((flags & FLAG_ALT) || precision > 0)
4218 *p++ = decimal_point_char ();
4222 *p++ = digits[ndigits];
4229 *p++ = dp->conversion; /* 'e' or 'E' */
4230 # if WIDE_CHAR_VERSION
4232 static const wchar_t decimal_format[] =
4233 /* Produce the same number of exponent digits
4234 as the native printf implementation. */
4235 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4236 { '%', '+', '.', '3', 'd', '\0' };
4238 { '%', '+', '.', '2', 'd', '\0' };
4240 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4246 static const char decimal_format[] =
4247 /* Produce the same number of exponent digits
4248 as the native printf implementation. */
4249 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4254 if (sizeof (DCHAR_T) == 1)
4256 sprintf ((char *) p, decimal_format, exponent);
4264 sprintf (expbuf, decimal_format, exponent);
4265 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4271 else if (dp->conversion == 'g' || dp->conversion == 'G')
4275 /* precision >= 1. */
4278 /* The exponent is 0, >= -4, < precision.
4279 Use fixed-point notation. */
4281 size_t ndigits = precision;
4282 /* Number of trailing zeroes that have to be
4285 (flags & FLAG_ALT ? 0 : precision - 1);
4289 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4291 *p++ = decimal_point_char ();
4292 while (ndigits > nzeroes)
4308 exponent = floorlog10 (arg);
4313 scale10_round_decimal_double (arg,
4314 (int)(precision - 1) - exponent);
4317 ndigits = strlen (digits);
4319 if (ndigits == precision)
4321 if (ndigits < precision - 1
4322 || ndigits > precision + 1)
4323 /* The exponent was not guessed
4324 precisely enough. */
4327 /* None of two values of exponent is
4328 the right one. Prevent an endless
4332 if (ndigits < precision)
4338 /* Here ndigits = precision. */
4339 if (is_borderline (digits, precision - 1))
4341 /* Maybe the exponent guess was too high
4342 and a smaller exponent can be reached
4343 by turning a 10...0 into 9...9x. */
4345 scale10_round_decimal_double (arg,
4346 (int)(precision - 1) - exponent + 1);
4347 if (digits2 == NULL)
4352 if (strlen (digits2) == precision)
4361 /* Here ndigits = precision. */
4363 /* Determine the number of trailing zeroes
4364 that have to be dropped. */
4366 if ((flags & FLAG_ALT) == 0)
4367 while (nzeroes < ndigits
4368 && digits[nzeroes] == '0')
4371 /* The exponent is now determined. */
4373 && exponent < (long)precision)
4375 /* Fixed-point notation:
4376 max(exponent,0)+1 digits, then the
4377 decimal point, then the remaining
4378 digits without trailing zeroes. */
4381 size_t ecount = exponent + 1;
4382 /* Note: ecount <= precision = ndigits. */
4383 for (; ecount > 0; ecount--)
4384 *p++ = digits[--ndigits];
4385 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4387 *p++ = decimal_point_char ();
4388 while (ndigits > nzeroes)
4391 *p++ = digits[ndigits];
4397 size_t ecount = -exponent - 1;
4399 *p++ = decimal_point_char ();
4400 for (; ecount > 0; ecount--)
4402 while (ndigits > nzeroes)
4405 *p++ = digits[ndigits];
4411 /* Exponential notation. */
4412 *p++ = digits[--ndigits];
4413 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4415 *p++ = decimal_point_char ();
4416 while (ndigits > nzeroes)
4419 *p++ = digits[ndigits];
4422 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4423 # if WIDE_CHAR_VERSION
4425 static const wchar_t decimal_format[] =
4426 /* Produce the same number of exponent digits
4427 as the native printf implementation. */
4428 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4429 { '%', '+', '.', '3', 'd', '\0' };
4431 { '%', '+', '.', '2', 'd', '\0' };
4433 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4439 static const char decimal_format[] =
4440 /* Produce the same number of exponent digits
4441 as the native printf implementation. */
4442 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4447 if (sizeof (DCHAR_T) == 1)
4449 sprintf ((char *) p, decimal_format, exponent);
4457 sprintf (expbuf, decimal_format, exponent);
4458 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4471 /* arg is finite. */
4477 if (dp->conversion == 'f' || dp->conversion == 'F')
4480 if ((flags & FLAG_ALT) || precision > 0)
4482 *p++ = decimal_point_char ();
4483 for (; precision > 0; precision--)
4487 else if (dp->conversion == 'e' || dp->conversion == 'E')
4490 if ((flags & FLAG_ALT) || precision > 0)
4492 *p++ = decimal_point_char ();
4493 for (; precision > 0; precision--)
4496 *p++ = dp->conversion; /* 'e' or 'E' */
4498 /* Produce the same number of exponent digits as
4499 the native printf implementation. */
4500 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4506 else if (dp->conversion == 'g' || dp->conversion == 'G')
4509 if (flags & FLAG_ALT)
4512 (precision > 0 ? precision - 1 : 0);
4513 *p++ = decimal_point_char ();
4514 for (; ndigits > 0; --ndigits)
4526 /* The generated string now extends from tmp to p, with the
4527 zero padding insertion point being at pad_ptr. */
4532 size_t pad = width - count;
4533 DCHAR_T *end = p + pad;
4535 if (flags & FLAG_LEFT)
4537 /* Pad with spaces on the right. */
4538 for (; pad > 0; pad--)
4541 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4543 /* Pad with zeroes. */
4548 for (; pad > 0; pad--)
4553 /* Pad with spaces on the left. */
4558 for (; pad > 0; pad--)
4567 if (count >= tmp_length)
4568 /* tmp_length was incorrectly calculated - fix the
4572 /* Make room for the result. */
4573 if (count >= allocated - length)
4575 size_t n = xsum (length, count);
4577 ENSURE_ALLOCATION (n);
4580 /* Append the result. */
4581 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4589 arg_type type = a.arg[dp->arg_index].type;
4590 int flags = dp->flags;
4591 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4594 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4597 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4601 #if NEED_PRINTF_UNBOUNDED_PRECISION
4604 # define prec_ourselves 0
4606 #if NEED_PRINTF_FLAG_LEFTADJUST
4607 # define pad_ourselves 1
4608 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4611 # define pad_ourselves 0
4614 unsigned int prefix_count;
4615 int prefixes[2] IF_LINT (= { 0 });
4619 TCHAR_T tmpbuf[700];
4623 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4626 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4628 if (dp->width_start != dp->width_end)
4630 if (dp->width_arg_index != ARG_NONE)
4634 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4636 arg = a.arg[dp->width_arg_index].a.a_int;
4640 /* "A negative field width is taken as a '-' flag
4641 followed by a positive field width." */
4648 const FCHAR_T *digitp = dp->width_start;
4651 width = xsum (xtimes (width, 10), *digitp++ - '0');
4652 while (digitp != dp->width_end);
4654 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4660 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4663 if (dp->precision_start != dp->precision_end)
4665 if (dp->precision_arg_index != ARG_NONE)
4669 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4671 arg = a.arg[dp->precision_arg_index].a.a_int;
4672 /* "A negative precision is taken as if the precision
4682 const FCHAR_T *digitp = dp->precision_start + 1;
4685 while (digitp != dp->precision_end)
4686 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4692 /* Decide whether to handle the precision ourselves. */
4693 #if NEED_PRINTF_UNBOUNDED_PRECISION
4694 switch (dp->conversion)
4696 case 'd': case 'i': case 'u':
4698 case 'x': case 'X': case 'p':
4699 prec_ourselves = has_precision && (precision > 0);
4707 /* Decide whether to perform the padding ourselves. */
4708 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4709 switch (dp->conversion)
4711 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4712 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4713 to perform the padding after this conversion. Functions
4714 with unistdio extensions perform the padding based on
4715 character count rather than element count. */
4718 # if NEED_PRINTF_FLAG_ZERO
4719 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4725 pad_ourselves = prec_ourselves;
4731 /* Allocate a temporary buffer of sufficient size for calling
4734 MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
4735 flags, width, has_precision, precision,
4738 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4742 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4744 if (size_overflow_p (tmp_memsize))
4745 /* Overflow, would lead to out of memory. */
4747 tmp = (TCHAR_T *) malloc (tmp_memsize);
4749 /* Out of memory. */
4754 /* Construct the format string for calling snprintf or
4758 #if NEED_PRINTF_FLAG_GROUPING
4759 /* The underlying implementation doesn't support the ' flag.
4760 Produce no grouping characters in this case; this is
4761 acceptable because the grouping is locale dependent. */
4763 if (flags & FLAG_GROUP)
4766 if (flags & FLAG_LEFT)
4768 if (flags & FLAG_SHOWSIGN)
4770 if (flags & FLAG_SPACE)
4772 if (flags & FLAG_ALT)
4774 #if __GLIBC__ >= 2 && !defined __UCLIBC__
4775 if (flags & FLAG_LOCALIZED)
4780 if (flags & FLAG_ZERO)
4782 if (dp->width_start != dp->width_end)
4784 size_t n = dp->width_end - dp->width_start;
4785 /* The width specification is known to consist only
4786 of standard ASCII characters. */
4787 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4789 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4794 const FCHAR_T *mp = dp->width_start;
4801 if (!prec_ourselves)
4803 if (dp->precision_start != dp->precision_end)
4805 size_t n = dp->precision_end - dp->precision_start;
4806 /* The precision specification is known to consist only
4807 of standard ASCII characters. */
4808 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4810 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4815 const FCHAR_T *mp = dp->precision_start;
4825 #if HAVE_LONG_LONG_INT
4826 case TYPE_LONGLONGINT:
4827 case TYPE_ULONGLONGINT:
4828 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4841 case TYPE_WIDE_CHAR:
4844 case TYPE_WIDE_STRING:
4848 case TYPE_LONGDOUBLE:
4854 #if NEED_PRINTF_DIRECTIVE_F
4855 if (dp->conversion == 'F')
4859 *fbp = dp->conversion;
4861 # if !(((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) && !defined __UCLIBC__) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4866 /* On glibc2 systems from glibc >= 2.3 - probably also older
4867 ones - we know that snprintf's return value conforms to
4868 ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and
4869 gl_SNPRINTF_TRUNCATION_C99 pass.
4870 Therefore we can avoid using %n in this situation.
4871 On glibc2 systems from 2004-10-18 or newer, the use of %n
4872 in format strings in writable memory may crash the program
4873 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4874 in this situation. */
4875 /* On native Windows systems (such as mingw), we can avoid using
4877 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4878 snprintf does not write more than the specified number
4879 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4880 '4', '5', '6' into buf, not '4', '5', '\0'.)
4881 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4882 allows us to recognize the case of an insufficient
4883 buffer size: it returns -1 in this case.
4884 On native Windows systems (such as mingw) where the OS is
4885 Windows Vista, the use of %n in format strings by default
4886 crashes the program. See
4887 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4888 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4889 So we should avoid %n in this situation. */
4896 /* Construct the arguments for calling snprintf or sprintf. */
4898 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4900 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4902 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4904 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4906 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4908 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4912 /* The SNPRINTF result is appended after result[0..length].
4913 The latter is an array of DCHAR_T; SNPRINTF appends an
4914 array of TCHAR_T to it. This is possible because
4915 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4916 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4917 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4918 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4919 where an snprintf() with maxlen==1 acts like sprintf(). */
4920 ENSURE_ALLOCATION (xsum (length,
4921 (2 + TCHARS_PER_DCHAR - 1)
4922 / TCHARS_PER_DCHAR));
4923 /* Prepare checking whether snprintf returns the count
4925 *(TCHAR_T *) (result + length) = '\0';
4936 size_t maxlen = allocated - length;
4937 /* SNPRINTF can fail if its second argument is
4939 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4940 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4941 maxlen = maxlen * TCHARS_PER_DCHAR;
4942 # define SNPRINTF_BUF(arg) \
4943 switch (prefix_count) \
4946 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4951 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4953 prefixes[0], arg, &count); \
4956 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4958 prefixes[0], prefixes[1], arg, \
4965 # define SNPRINTF_BUF(arg) \
4966 switch (prefix_count) \
4969 count = sprintf (tmp, buf, arg); \
4972 count = sprintf (tmp, buf, prefixes[0], arg); \
4975 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4988 int arg = a.arg[dp->arg_index].a.a_schar;
4994 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
5000 int arg = a.arg[dp->arg_index].a.a_short;
5006 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
5012 int arg = a.arg[dp->arg_index].a.a_int;
5018 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
5024 long int arg = a.arg[dp->arg_index].a.a_longint;
5030 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
5034 #if HAVE_LONG_LONG_INT
5035 case TYPE_LONGLONGINT:
5037 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
5041 case TYPE_ULONGLONGINT:
5043 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
5050 double arg = a.arg[dp->arg_index].a.a_double;
5054 case TYPE_LONGDOUBLE:
5056 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5062 int arg = a.arg[dp->arg_index].a.a_char;
5067 case TYPE_WIDE_CHAR:
5069 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5076 const char *arg = a.arg[dp->arg_index].a.a_string;
5081 case TYPE_WIDE_STRING:
5083 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5090 void *arg = a.arg[dp->arg_index].a.a_pointer;
5099 /* Portability: Not all implementations of snprintf()
5100 are ISO C 99 compliant. Determine the number of
5101 bytes that snprintf() has produced or would have
5105 /* Verify that snprintf() has NUL-terminated its
5108 && ((TCHAR_T *) (result + length)) [count] != '\0')
5110 /* Portability hack. */
5111 if (retcount > count)
5116 /* snprintf() doesn't understand the '%n'
5120 /* Don't use the '%n' directive; instead, look
5121 at the snprintf() return value. */
5127 /* Look at the snprintf() return value. */
5130 # if !HAVE_SNPRINTF_RETVAL_C99
5131 /* HP-UX 10.20 snprintf() is doubly deficient:
5132 It doesn't understand the '%n' directive,
5133 *and* it returns -1 (rather than the length
5134 that would have been required) when the
5135 buffer is too small.
5136 But a failure at this point can also come
5137 from other reasons than a too small buffer,
5138 such as an invalid wide string argument to
5139 the %ls directive, or possibly an invalid
5140 floating-point argument. */
5142 MAX_ROOM_NEEDED (&a, dp->arg_index,
5143 dp->conversion, type, flags,
5146 precision, pad_ourselves);
5148 if (maxlen < tmp_length)
5150 /* Make more room. But try to do through
5151 this reallocation only once. */
5152 size_t bigger_need =
5155 TCHARS_PER_DCHAR - 1)
5156 / TCHARS_PER_DCHAR);
5157 /* And always grow proportionally.
5158 (There may be several arguments, each
5159 needing a little more room than the
5161 size_t bigger_need2 =
5162 xsum (xtimes (allocated, 2), 12);
5163 if (bigger_need < bigger_need2)
5164 bigger_need = bigger_need2;
5165 ENSURE_ALLOCATION (bigger_need);
5176 /* Attempt to handle failure. */
5179 /* SNPRINTF or sprintf failed. Save and use the errno
5180 that it has set, if any. */
5181 int saved_errno = errno;
5182 if (saved_errno == 0)
5184 if (dp->conversion == 'c' || dp->conversion == 's')
5185 saved_errno = EILSEQ;
5187 saved_errno = EINVAL;
5190 if (!(result == resultbuf || result == NULL))
5192 if (buf_malloced != NULL)
5193 free (buf_malloced);
5196 errno = saved_errno;
5201 /* Handle overflow of the allocated buffer.
5202 If such an overflow occurs, a C99 compliant snprintf()
5203 returns a count >= maxlen. However, a non-compliant
5204 snprintf() function returns only count = maxlen - 1. To
5205 cover both cases, test whether count >= maxlen - 1. */
5206 if ((unsigned int) count + 1 >= maxlen)
5208 /* If maxlen already has attained its allowed maximum,
5209 allocating more memory will not increase maxlen.
5210 Instead of looping, bail out. */
5211 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5215 /* Need at least (count + 1) * sizeof (TCHAR_T)
5216 bytes. (The +1 is for the trailing NUL.)
5217 But ask for (count + 2) * sizeof (TCHAR_T)
5218 bytes, so that in the next round, we likely get
5219 maxlen > (unsigned int) count + 1
5220 and so we don't get here again.
5221 And allocate proportionally, to avoid looping
5222 eternally if snprintf() reports a too small
5226 ((unsigned int) count + 2
5227 + TCHARS_PER_DCHAR - 1)
5228 / TCHARS_PER_DCHAR),
5229 xtimes (allocated, 2));
5231 ENSURE_ALLOCATION (n);
5237 #if NEED_PRINTF_UNBOUNDED_PRECISION
5240 /* Handle the precision. */
5243 (TCHAR_T *) (result + length);
5247 size_t prefix_count;
5251 /* Put the additional zeroes after the sign. */
5253 && (*prec_ptr == '-' || *prec_ptr == '+'
5254 || *prec_ptr == ' '))
5256 /* Put the additional zeroes after the 0x prefix if
5257 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5259 && prec_ptr[0] == '0'
5260 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5263 move = count - prefix_count;
5264 if (precision > move)
5266 /* Insert zeroes. */
5267 size_t insert = precision - move;
5273 (count + insert + TCHARS_PER_DCHAR - 1)
5274 / TCHARS_PER_DCHAR);
5275 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5276 ENSURE_ALLOCATION (n);
5277 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5278 prec_ptr = (TCHAR_T *) (result + length);
5281 prec_end = prec_ptr + count;
5282 prec_ptr += prefix_count;
5284 while (prec_end > prec_ptr)
5287 prec_end[insert] = prec_end[0];
5293 while (prec_end > prec_ptr);
5301 if (count >= tmp_length)
5302 /* tmp_length was incorrectly calculated - fix the
5308 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5309 if (dp->conversion == 'c' || dp->conversion == 's')
5311 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5313 The result string is not certainly ASCII. */
5314 const TCHAR_T *tmpsrc;
5317 /* This code assumes that TCHAR_T is 'char'. */
5318 verify (sizeof (TCHAR_T) == 1);
5320 tmpsrc = (TCHAR_T *) (result + length);
5325 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5326 iconveh_question_mark,
5332 int saved_errno = errno;
5333 if (!(result == resultbuf || result == NULL))
5335 if (buf_malloced != NULL)
5336 free (buf_malloced);
5338 errno = saved_errno;
5341 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5342 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5348 /* The result string is ASCII.
5349 Simple 1:1 conversion. */
5351 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5352 no-op conversion, in-place on the array starting
5353 at (result + length). */
5354 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5357 const TCHAR_T *tmpsrc;
5362 if (result == resultbuf)
5364 tmpsrc = (TCHAR_T *) (result + length);
5365 /* ENSURE_ALLOCATION will not move tmpsrc
5366 (because it's part of resultbuf). */
5367 ENSURE_ALLOCATION (xsum (length, count));
5371 /* ENSURE_ALLOCATION will move the array
5372 (because it uses realloc(). */
5373 ENSURE_ALLOCATION (xsum (length, count));
5374 tmpsrc = (TCHAR_T *) (result + length);
5378 ENSURE_ALLOCATION (xsum (length, count));
5380 tmpdst = result + length;
5381 /* Copy backwards, because of overlapping. */
5384 for (n = count; n > 0; n--)
5385 *--tmpdst = *--tmpsrc;
5390 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5391 /* Make room for the result. */
5392 if (count > allocated - length)
5394 /* Need at least count elements. But allocate
5397 xmax (xsum (length, count), xtimes (allocated, 2));
5399 ENSURE_ALLOCATION (n);
5403 /* Here count <= allocated - length. */
5405 /* Perform padding. */
5406 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5407 if (pad_ourselves && has_width)
5410 # if ENABLE_UNISTDIO
5411 /* Outside POSIX, it's preferable to compare the width
5412 against the number of _characters_ of the converted
5414 w = DCHAR_MBSNLEN (result + length, count);
5416 /* The width is compared against the number of _bytes_
5417 of the converted value, says POSIX. */
5422 size_t pad = width - w;
5424 /* Make room for the result. */
5425 if (xsum (count, pad) > allocated - length)
5427 /* Need at least count + pad elements. But
5428 allocate proportionally. */
5430 xmax (xsum3 (length, count, pad),
5431 xtimes (allocated, 2));
5435 ENSURE_ALLOCATION (n);
5438 ENSURE_ALLOCATION (n);
5441 /* Here count + pad <= allocated - length. */
5444 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5445 DCHAR_T * const rp = result + length;
5447 DCHAR_T * const rp = tmp;
5449 DCHAR_T *p = rp + count;
5450 DCHAR_T *end = p + pad;
5452 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5453 if (dp->conversion == 'c'
5454 || dp->conversion == 's')
5455 /* No zero-padding for string directives. */
5460 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5461 /* No zero-padding of "inf" and "nan". */
5462 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5463 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5466 /* The generated string now extends from rp to p,
5467 with the zero padding insertion point being at
5470 count = count + pad; /* = end - rp */
5472 if (flags & FLAG_LEFT)
5474 /* Pad with spaces on the right. */
5475 for (; pad > 0; pad--)
5478 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5480 /* Pad with zeroes. */
5485 for (; pad > 0; pad--)
5490 /* Pad with spaces on the left. */
5495 for (; pad > 0; pad--)
5503 /* Here still count <= allocated - length. */
5505 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5506 /* The snprintf() result did fit. */
5508 /* Append the sprintf() result. */
5509 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5516 #if NEED_PRINTF_DIRECTIVE_F
5517 if (dp->conversion == 'F')
5519 /* Convert the %f result to upper case for %F. */
5520 DCHAR_T *rp = result + length;
5522 for (rc = count; rc > 0; rc--, rp++)
5523 if (*rp >= 'a' && *rp <= 'z')
5524 *rp = *rp - 'a' + 'A';
5532 #undef pad_ourselves
5533 #undef prec_ourselves
5538 /* Add the final NUL. */
5539 ENSURE_ALLOCATION (xsum (length, 1));
5540 result[length] = '\0';
5542 if (result != resultbuf && length + 1 < allocated)
5544 /* Shrink the allocated memory if possible. */
5547 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5552 if (buf_malloced != NULL)
5553 free (buf_malloced);
5556 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5557 says that snprintf() fails with errno = EOVERFLOW in this case, but
5558 that's only because snprintf() returns an 'int'. This function does
5559 not have this limitation. */
5564 if (!(result == resultbuf || result == NULL))
5566 if (buf_malloced != NULL)
5567 free (buf_malloced);
5574 if (!(result == resultbuf || result == NULL))
5576 if (buf_malloced != NULL)
5577 free (buf_malloced);
5585 #undef MAX_ROOM_NEEDED
5586 #undef TCHARS_PER_DCHAR
5594 #undef DCHAR_IS_TCHAR