1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2011 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* This file can be parametrized with the following macros:
19 VASNPRINTF The name of the function being defined.
20 FCHAR_T The element type of the format string.
21 DCHAR_T The element type of the destination (result) string.
22 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
23 in the format string are ASCII. MUST be set if
24 FCHAR_T and DCHAR_T are not the same type.
25 DIRECTIVE Structure denoting a format directive.
27 DIRECTIVES Structure denoting the set of format directives of a
28 format string. Depends on FCHAR_T.
29 PRINTF_PARSE Function that parses a format string.
31 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
32 DCHAR_SET memset like function for DCHAR_T[] arrays.
33 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
34 SNPRINTF The system's snprintf (or similar) function.
35 This may be either snprintf or swprintf.
36 TCHAR_T The element type of the argument and result string
37 of the said SNPRINTF function. This may be either
38 char or wchar_t. The code exploits that
39 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
40 alignof (TCHAR_T) <= alignof (DCHAR_T).
41 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
42 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
43 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
44 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
45 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
47 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
48 This must come before <config.h> because <config.h> may include
49 <features.h>, and once <features.h> has been included, it's too late. */
51 # define _GNU_SOURCE 1
63 # if WIDE_CHAR_VERSION
64 # include "vasnwprintf.h"
66 # include "vasnprintf.h"
70 #include <locale.h> /* localeconv() */
71 #include <stdio.h> /* snprintf(), sprintf() */
72 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
73 #include <string.h> /* memcpy(), strlen() */
74 #include <errno.h> /* errno */
75 #include <limits.h> /* CHAR_BIT */
76 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
78 # include <langinfo.h>
81 # if WIDE_CHAR_VERSION
82 # include "wprintf-parse.h"
84 # include "printf-parse.h"
88 /* Checked size_t computations. */
93 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
98 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
100 # include "isnand-nolibm.h"
103 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
105 # include "isnanl-nolibm.h"
109 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
111 # include "isnand-nolibm.h"
112 # include "printf-frexp.h"
115 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
117 # include "isnanl-nolibm.h"
118 # include "printf-frexpl.h"
122 /* Default parameters. */
124 # if WIDE_CHAR_VERSION
125 # define VASNPRINTF vasnwprintf
126 # define FCHAR_T wchar_t
127 # define DCHAR_T wchar_t
128 # define TCHAR_T wchar_t
129 # define DCHAR_IS_TCHAR 1
130 # define DIRECTIVE wchar_t_directive
131 # define DIRECTIVES wchar_t_directives
132 # define PRINTF_PARSE wprintf_parse
133 # define DCHAR_CPY wmemcpy
134 # define DCHAR_SET wmemset
136 # define VASNPRINTF vasnprintf
137 # define FCHAR_T char
138 # define DCHAR_T char
139 # define TCHAR_T char
140 # define DCHAR_IS_TCHAR 1
141 # define DIRECTIVE char_directive
142 # define DIRECTIVES char_directives
143 # define PRINTF_PARSE printf_parse
144 # define DCHAR_CPY memcpy
145 # define DCHAR_SET memset
148 #if WIDE_CHAR_VERSION
149 /* TCHAR_T is wchar_t. */
150 # define USE_SNPRINTF 1
151 # if HAVE_DECL__SNWPRINTF
152 /* On Windows, the function swprintf() has a different signature than
153 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
154 instead. The mingw function snwprintf() has fewer bugs than the
155 MSVCRT function _snwprintf(), so prefer that. */
156 # if defined __MINGW32__
157 # define SNPRINTF snwprintf
159 # define SNPRINTF _snwprintf
163 # define SNPRINTF swprintf
166 /* TCHAR_T is char. */
167 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
168 But don't use it on BeOS, since BeOS snprintf produces no output if the
169 size argument is >= 0x3000000.
170 Also don't use it on Linux libc5, since there snprintf with size = 1
171 writes any output without bounds, like sprintf. */
172 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
173 # define USE_SNPRINTF 1
175 # define USE_SNPRINTF 0
177 # if HAVE_DECL__SNPRINTF
178 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
179 function _snprintf(), so prefer that. */
180 # if defined __MINGW32__
181 # define SNPRINTF snprintf
182 /* Here we need to call the native snprintf, not rpl_snprintf. */
185 # define SNPRINTF _snprintf
189 # define SNPRINTF snprintf
190 /* Here we need to call the native snprintf, not rpl_snprintf. */
194 /* Here we need to call the native sprintf, not rpl_sprintf. */
197 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
198 warnings in this file. Use -Dlint to suppress them. */
200 # define IF_LINT(Code) Code
202 # define IF_LINT(Code) /* empty */
205 /* Avoid some warnings from "gcc -Wshadow".
206 This file doesn't use the exp() and remainder() functions. */
210 #define remainder rem
212 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && !WIDE_CHAR_VERSION
213 # if (HAVE_STRNLEN && !defined _AIX)
214 # define local_strnlen strnlen
216 # ifndef local_strnlen_defined
217 # define local_strnlen_defined 1
219 local_strnlen (const char *string, size_t maxlen)
221 const char *end = memchr (string, '\0', maxlen);
222 return end ? (size_t) (end - string) : maxlen;
228 #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
230 # define local_wcslen wcslen
232 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
233 a dependency towards this library, here is a local substitute.
234 Define this substitute only once, even if this file is included
235 twice in the same compilation unit. */
236 # ifndef local_wcslen_defined
237 # define local_wcslen_defined 1
239 local_wcslen (const wchar_t *s)
243 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
251 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
253 # define local_wcsnlen wcsnlen
255 # ifndef local_wcsnlen_defined
256 # define local_wcsnlen_defined 1
258 local_wcsnlen (const wchar_t *s, size_t maxlen)
262 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
270 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
271 /* Determine the decimal-point character according to the current locale. */
272 # ifndef decimal_point_char_defined
273 # define decimal_point_char_defined 1
275 decimal_point_char (void)
278 /* Determine it in a multithread-safe way. We know nl_langinfo is
279 multithread-safe on glibc systems and MacOS X systems, but is not required
280 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
281 localeconv() is rarely multithread-safe. */
282 # if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
283 point = nl_langinfo (RADIXCHAR);
286 sprintf (pointbuf, "%#.0f", 1.0);
287 point = &pointbuf[1];
289 point = localeconv () -> decimal_point;
291 /* The decimal point is always a single byte: either '.' or ','. */
292 return (point[0] != '\0' ? point[0] : '.');
297 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
299 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
301 is_infinite_or_zero (double x)
303 return isnand (x) || x + x == x;
308 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
310 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
312 is_infinite_or_zerol (long double x)
314 return isnanl (x) || x + x == x;
319 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
321 /* Converting 'long double' to decimal without rare rounding bugs requires
322 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
323 (and slower) algorithms. */
325 typedef unsigned int mp_limb_t;
326 # define GMP_LIMB_BITS 32
327 verify (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS);
329 typedef unsigned long long mp_twolimb_t;
330 # define GMP_TWOLIMB_BITS 64
331 verify (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS);
333 /* Representation of a bignum >= 0. */
337 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
340 /* Compute the product of two bignums >= 0.
341 Return the allocated memory in case of success, NULL in case of memory
342 allocation failure. */
344 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
351 if (src1.nlimbs <= src2.nlimbs)
365 /* Now 0 <= len1 <= len2. */
368 /* src1 or src2 is zero. */
370 dest->limbs = (mp_limb_t *) malloc (1);
374 /* Here 1 <= len1 <= len2. */
380 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
383 for (k = len2; k > 0; )
385 for (i = 0; i < len1; i++)
387 mp_limb_t digit1 = p1[i];
388 mp_twolimb_t carry = 0;
389 for (j = 0; j < len2; j++)
391 mp_limb_t digit2 = p2[j];
392 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
394 dp[i + j] = (mp_limb_t) carry;
395 carry = carry >> GMP_LIMB_BITS;
397 dp[i + len2] = (mp_limb_t) carry;
400 while (dlen > 0 && dp[dlen - 1] == 0)
408 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
409 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
411 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
413 Return the allocated memory in case of success, NULL in case of memory
414 allocation failure. */
416 divide (mpn_t a, mpn_t b, mpn_t *q)
419 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
420 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
421 If m<n, then q:=0 and r:=a.
422 If m>=n=1, perform a single-precision division:
425 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
426 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
427 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
428 Normalise [q[m-1],...,q[0]], yields q.
429 If m>=n>1, perform a multiple-precision division:
430 We have a/b < beta^(m-n+1).
431 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
432 Shift a and b left by s bits, copying them. r:=a.
433 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
434 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
436 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
437 In case of overflow (q* >= beta) set q* := beta-1.
438 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
439 and c3 := b[n-2] * q*.
440 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
441 occurred. Furthermore 0 <= c3 < beta^2.
442 If there was overflow and
443 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
444 the next test can be skipped.}
445 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
446 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
448 Put r := r - b * q* * beta^j. In detail:
449 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
450 hence: u:=0, for i:=0 to n-1 do
452 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
453 u:=u div beta (+ 1, if carry in subtraction)
455 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
457 the carry u does not overflow.}
458 If a negative carry occurs, put q* := q* - 1
459 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
461 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
462 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
464 The room for q[j] can be allocated at the memory location of r[n+j].
465 Finally, round-to-even:
466 Shift r left by 1 bit.
467 If r > b or if r = b and q[0] is odd, q := q+1.
469 const mp_limb_t *a_ptr = a.limbs;
470 size_t a_len = a.nlimbs;
471 const mp_limb_t *b_ptr = b.limbs;
472 size_t b_len = b.nlimbs;
474 mp_limb_t *tmp_roomptr = NULL;
480 /* Allocate room for a_len+2 digits.
481 (Need a_len+1 digits for the real division and 1 more digit for the
482 final rounding of q.) */
483 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
488 while (a_len > 0 && a_ptr[a_len - 1] == 0)
495 /* Division by zero. */
497 if (b_ptr[b_len - 1] == 0)
503 /* Here m = a_len >= 0 and n = b_len > 0. */
507 /* m<n: trivial case. q=0, r := copy of a. */
510 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
511 q_ptr = roomptr + a_len;
516 /* n=1: single precision division.
517 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
521 mp_limb_t den = b_ptr[0];
522 mp_limb_t remainder = 0;
523 const mp_limb_t *sourceptr = a_ptr + a_len;
524 mp_limb_t *destptr = q_ptr + a_len;
526 for (count = a_len; count > 0; count--)
529 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
530 *--destptr = num / den;
531 remainder = num % den;
533 /* Normalise and store r. */
536 r_ptr[0] = remainder;
543 if (q_ptr[q_len - 1] == 0)
549 /* n>1: multiple precision division.
550 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
551 beta^(m-n-1) <= a/b < beta^(m-n+1). */
555 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
556 /* Determine s = GMP_LIMB_BITS - integer_length (msd).
557 Code copied from gnulib's integer_length.c. */
558 # if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
559 s = __builtin_clz (msd);
561 # if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT
562 if (GMP_LIMB_BITS <= DBL_MANT_BIT)
564 /* Use 'double' operations.
565 Assumes an IEEE 754 'double' implementation. */
566 # define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)
567 # define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1)
569 ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
570 union { double value; unsigned int word[NWORDS]; } m;
572 /* Use a single integer to floating-point conversion. */
576 - (((m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK)
612 /* 0 <= s < GMP_LIMB_BITS.
613 Copy b, shifting it left by s bits. */
616 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
617 if (tmp_roomptr == NULL)
623 const mp_limb_t *sourceptr = b_ptr;
624 mp_limb_t *destptr = tmp_roomptr;
625 mp_twolimb_t accu = 0;
627 for (count = b_len; count > 0; count--)
629 accu += (mp_twolimb_t) *sourceptr++ << s;
630 *destptr++ = (mp_limb_t) accu;
631 accu = accu >> GMP_LIMB_BITS;
633 /* accu must be zero, since that was how s was determined. */
639 /* Copy a, shifting it left by s bits, yields r.
641 At the beginning: r = roomptr[0..a_len],
642 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
646 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
651 const mp_limb_t *sourceptr = a_ptr;
652 mp_limb_t *destptr = r_ptr;
653 mp_twolimb_t accu = 0;
655 for (count = a_len; count > 0; count--)
657 accu += (mp_twolimb_t) *sourceptr++ << s;
658 *destptr++ = (mp_limb_t) accu;
659 accu = accu >> GMP_LIMB_BITS;
661 *destptr++ = (mp_limb_t) accu;
663 q_ptr = roomptr + b_len;
664 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
666 size_t j = a_len - b_len; /* m-n */
667 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
668 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
669 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
670 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
671 /* Division loop, traversed m-n+1 times.
672 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
677 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
679 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
681 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
682 | r_ptr[j + b_len - 1];
683 q_star = num / b_msd;
688 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
689 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
690 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
691 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
692 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
694 If yes, jump directly to the subtraction loop.
695 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
696 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
697 if (r_ptr[j + b_len] > b_msd
698 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
699 /* r[j+n] >= b[n-1]+1 or
700 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
705 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
707 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
708 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
709 mp_twolimb_t c3 = /* b[n-2] * q* */
710 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
711 /* While c2 < c3, increase c2 and decrease c3.
712 Consider c3-c2. While it is > 0, decrease it by
713 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
714 this can happen only twice. */
717 q_star = q_star - 1; /* q* := q* - 1 */
718 if (c3 - c2 > b_msdd)
719 q_star = q_star - 1; /* q* := q* - 1 */
725 /* Subtract r := r - b * q* * beta^j. */
728 const mp_limb_t *sourceptr = b_ptr;
729 mp_limb_t *destptr = r_ptr + j;
730 mp_twolimb_t carry = 0;
732 for (count = b_len; count > 0; count--)
734 /* Here 0 <= carry <= q*. */
737 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
738 + (mp_limb_t) ~(*destptr);
739 /* Here 0 <= carry <= beta*q* + beta-1. */
740 *destptr++ = ~(mp_limb_t) carry;
741 carry = carry >> GMP_LIMB_BITS; /* <= q* */
743 cr = (mp_limb_t) carry;
745 /* Subtract cr from r_ptr[j + b_len], then forget about
747 if (cr > r_ptr[j + b_len])
749 /* Subtraction gave a carry. */
750 q_star = q_star - 1; /* q* := q* - 1 */
753 const mp_limb_t *sourceptr = b_ptr;
754 mp_limb_t *destptr = r_ptr + j;
757 for (count = b_len; count > 0; count--)
759 mp_limb_t source1 = *sourceptr++;
760 mp_limb_t source2 = *destptr;
761 *destptr++ = source1 + source2 + carry;
764 ? source1 >= (mp_limb_t) ~source2
765 : source1 > (mp_limb_t) ~source2);
768 /* Forget about the carry and about r[j+n]. */
771 /* q* is determined. Store it as q[j]. */
780 if (q_ptr[q_len - 1] == 0)
782 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
783 b is shifted left by s bits. */
784 /* Shift r right by s bits. */
787 mp_limb_t ptr = r_ptr + r_len;
788 mp_twolimb_t accu = 0;
790 for (count = r_len; count > 0; count--)
792 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
793 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
794 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
799 while (r_len > 0 && r_ptr[r_len - 1] == 0)
802 /* Compare r << 1 with b. */
810 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
811 | (i < r_len ? r_ptr[i] << 1 : 0);
812 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
822 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
827 for (i = 0; i < q_len; i++)
828 if (++(q_ptr[i]) != 0)
833 if (tmp_roomptr != NULL)
840 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
842 Destroys the contents of a.
843 Return the allocated memory - containing the decimal digits in low-to-high
844 order, terminated with a NUL character - in case of success, NULL in case
845 of memory allocation failure. */
847 convert_to_decimal (mpn_t a, size_t extra_zeroes)
849 mp_limb_t *a_ptr = a.limbs;
850 size_t a_len = a.nlimbs;
851 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
852 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
853 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
857 for (; extra_zeroes > 0; extra_zeroes--)
861 /* Divide a by 10^9, in-place. */
862 mp_limb_t remainder = 0;
863 mp_limb_t *ptr = a_ptr + a_len;
865 for (count = a_len; count > 0; count--)
868 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
869 *ptr = num / 1000000000;
870 remainder = num % 1000000000;
872 /* Store the remainder as 9 decimal digits. */
873 for (count = 9; count > 0; count--)
875 *d_ptr++ = '0' + (remainder % 10);
876 remainder = remainder / 10;
879 if (a_ptr[a_len - 1] == 0)
882 /* Remove leading zeroes. */
883 while (d_ptr > c_ptr && d_ptr[-1] == '0')
885 /* But keep at least one zero. */
888 /* Terminate the string. */
894 # if NEED_PRINTF_LONG_DOUBLE
896 /* Assuming x is finite and >= 0:
897 write x as x = 2^e * m, where m is a bignum.
898 Return the allocated memory in case of success, NULL in case of memory
899 allocation failure. */
901 decode_long_double (long double x, int *ep, mpn_t *mp)
908 /* Allocate memory for result. */
909 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
910 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
913 /* Split into exponential part and mantissa. */
914 y = frexpl (x, &exp);
915 if (!(y >= 0.0L && y < 1.0L))
917 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the
918 latter is an integer. */
919 /* Convert the mantissa (y * 2^LDBL_MANT_BIT) to a sequence of limbs.
920 I'm not sure whether it's safe to cast a 'long double' value between
921 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
922 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
924 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
925 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
928 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
931 if (!(y >= 0.0L && y < 1.0L))
933 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
936 if (!(y >= 0.0L && y < 1.0L))
938 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
943 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
946 if (!(y >= 0.0L && y < 1.0L))
948 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
952 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
955 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
958 if (!(y >= 0.0L && y < 1.0L))
960 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
963 if (!(y >= 0.0L && y < 1.0L))
965 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
967 # if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
973 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
976 *ep = exp - LDBL_MANT_BIT;
982 # if NEED_PRINTF_DOUBLE
984 /* Assuming x is finite and >= 0:
985 write x as x = 2^e * m, where m is a bignum.
986 Return the allocated memory in case of success, NULL in case of memory
987 allocation failure. */
989 decode_double (double x, int *ep, mpn_t *mp)
996 /* Allocate memory for result. */
997 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
998 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
1001 /* Split into exponential part and mantissa. */
1002 y = frexp (x, &exp);
1003 if (!(y >= 0.0 && y < 1.0))
1005 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the
1006 latter is an integer. */
1007 /* Convert the mantissa (y * 2^DBL_MANT_BIT) to a sequence of limbs.
1008 I'm not sure whether it's safe to cast a 'double' value between
1009 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1010 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1012 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
1013 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1016 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
1019 if (!(y >= 0.0 && y < 1.0))
1021 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1024 if (!(y >= 0.0 && y < 1.0))
1026 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1031 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
1034 if (!(y >= 0.0 && y < 1.0))
1036 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
1040 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1043 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1046 if (!(y >= 0.0 && y < 1.0))
1048 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1051 if (!(y >= 0.0 && y < 1.0))
1053 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1058 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1061 *ep = exp - DBL_MANT_BIT;
1067 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1068 Returns the decimal representation of round (x * 10^n).
1069 Return the allocated memory - containing the decimal digits in low-to-high
1070 order, terminated with a NUL character - in case of success, NULL in case
1071 of memory allocation failure. */
1073 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1076 size_t extra_zeroes;
1079 mp_limb_t *pow5_ptr;
1081 unsigned int s_limbs;
1082 unsigned int s_bits;
1090 /* x = 2^e * m, hence
1091 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1092 = round (2^s * 5^n * m). */
1095 /* Factor out a common power of 10 if possible. */
1098 extra_zeroes = (s < n ? s : n);
1102 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1103 Before converting to decimal, we need to compute
1104 z = round (2^s * 5^n * m). */
1105 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1106 sign. 2.322 is slightly larger than log(5)/log(2). */
1107 abs_n = (n >= 0 ? n : -n);
1108 abs_s = (s >= 0 ? s : -s);
1109 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1110 + abs_s / GMP_LIMB_BITS + 1)
1111 * sizeof (mp_limb_t));
1112 if (pow5_ptr == NULL)
1117 /* Initialize with 1. */
1120 /* Multiply with 5^|n|. */
1123 static mp_limb_t const small_pow5[13 + 1] =
1125 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1126 48828125, 244140625, 1220703125
1129 for (n13 = 0; n13 <= abs_n; n13 += 13)
1131 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1133 mp_twolimb_t carry = 0;
1134 for (j = 0; j < pow5_len; j++)
1136 mp_limb_t digit2 = pow5_ptr[j];
1137 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1138 pow5_ptr[j] = (mp_limb_t) carry;
1139 carry = carry >> GMP_LIMB_BITS;
1142 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1145 s_limbs = abs_s / GMP_LIMB_BITS;
1146 s_bits = abs_s % GMP_LIMB_BITS;
1147 if (n >= 0 ? s >= 0 : s <= 0)
1149 /* Multiply with 2^|s|. */
1152 mp_limb_t *ptr = pow5_ptr;
1153 mp_twolimb_t accu = 0;
1155 for (count = pow5_len; count > 0; count--)
1157 accu += (mp_twolimb_t) *ptr << s_bits;
1158 *ptr++ = (mp_limb_t) accu;
1159 accu = accu >> GMP_LIMB_BITS;
1163 *ptr = (mp_limb_t) accu;
1170 for (count = pow5_len; count > 0;)
1173 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1175 for (count = s_limbs; count > 0;)
1178 pow5_ptr[count] = 0;
1180 pow5_len += s_limbs;
1182 pow5.limbs = pow5_ptr;
1183 pow5.nlimbs = pow5_len;
1186 /* Multiply m with pow5. No division needed. */
1187 z_memory = multiply (m, pow5, &z);
1191 /* Divide m by pow5 and round. */
1192 z_memory = divide (m, pow5, &z);
1197 pow5.limbs = pow5_ptr;
1198 pow5.nlimbs = pow5_len;
1202 Multiply m with pow5, then divide by 2^|s|. */
1206 tmp_memory = multiply (m, pow5, &numerator);
1207 if (tmp_memory == NULL)
1213 /* Construct 2^|s|. */
1215 mp_limb_t *ptr = pow5_ptr + pow5_len;
1217 for (i = 0; i < s_limbs; i++)
1219 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1220 denominator.limbs = ptr;
1221 denominator.nlimbs = s_limbs + 1;
1223 z_memory = divide (numerator, denominator, &z);
1229 Multiply m with 2^s, then divide by pow5. */
1232 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1233 * sizeof (mp_limb_t));
1234 if (num_ptr == NULL)
1241 mp_limb_t *destptr = num_ptr;
1244 for (i = 0; i < s_limbs; i++)
1249 const mp_limb_t *sourceptr = m.limbs;
1250 mp_twolimb_t accu = 0;
1252 for (count = m.nlimbs; count > 0; count--)
1254 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1255 *destptr++ = (mp_limb_t) accu;
1256 accu = accu >> GMP_LIMB_BITS;
1259 *destptr++ = (mp_limb_t) accu;
1263 const mp_limb_t *sourceptr = m.limbs;
1265 for (count = m.nlimbs; count > 0; count--)
1266 *destptr++ = *sourceptr++;
1268 numerator.limbs = num_ptr;
1269 numerator.nlimbs = destptr - num_ptr;
1271 z_memory = divide (numerator, pow5, &z);
1278 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1280 if (z_memory == NULL)
1282 digits = convert_to_decimal (z, extra_zeroes);
1287 # if NEED_PRINTF_LONG_DOUBLE
1289 /* Assuming x is finite and >= 0, and n is an integer:
1290 Returns the decimal representation of round (x * 10^n).
1291 Return the allocated memory - containing the decimal digits in low-to-high
1292 order, terminated with a NUL character - in case of success, NULL in case
1293 of memory allocation failure. */
1295 scale10_round_decimal_long_double (long double x, int n)
1299 void *memory = decode_long_double (x, &e, &m);
1300 return scale10_round_decimal_decoded (e, m, memory, n);
1305 # if NEED_PRINTF_DOUBLE
1307 /* Assuming x is finite and >= 0, and n is an integer:
1308 Returns the decimal representation of round (x * 10^n).
1309 Return the allocated memory - containing the decimal digits in low-to-high
1310 order, terminated with a NUL character - in case of success, NULL in case
1311 of memory allocation failure. */
1313 scale10_round_decimal_double (double x, int n)
1317 void *memory = decode_double (x, &e, &m);
1318 return scale10_round_decimal_decoded (e, m, memory, n);
1323 # if NEED_PRINTF_LONG_DOUBLE
1325 /* Assuming x is finite and > 0:
1326 Return an approximation for n with 10^n <= x < 10^(n+1).
1327 The approximation is usually the right n, but may be off by 1 sometimes. */
1329 floorlog10l (long double x)
1336 /* Split into exponential part and mantissa. */
1337 y = frexpl (x, &exp);
1338 if (!(y >= 0.0L && y < 1.0L))
1344 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1346 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1347 exp -= GMP_LIMB_BITS;
1349 if (y < (1.0L / (1 << 16)))
1351 y *= 1.0L * (1 << 16);
1354 if (y < (1.0L / (1 << 8)))
1356 y *= 1.0L * (1 << 8);
1359 if (y < (1.0L / (1 << 4)))
1361 y *= 1.0L * (1 << 4);
1364 if (y < (1.0L / (1 << 2)))
1366 y *= 1.0L * (1 << 2);
1369 if (y < (1.0L / (1 << 1)))
1371 y *= 1.0L * (1 << 1);
1375 if (!(y >= 0.5L && y < 1.0L))
1377 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1380 if (z < 0.70710678118654752444)
1382 z *= 1.4142135623730950488;
1385 if (z < 0.8408964152537145431)
1387 z *= 1.1892071150027210667;
1390 if (z < 0.91700404320467123175)
1392 z *= 1.0905077326652576592;
1395 if (z < 0.9576032806985736469)
1397 z *= 1.0442737824274138403;
1400 /* Now 0.95 <= z <= 1.01. */
1402 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1403 Four terms are enough to get an approximation with error < 10^-7. */
1404 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1405 /* Finally multiply with log(2)/log(10), yields an approximation for
1407 l *= 0.30102999566398119523;
1408 /* Round down to the next integer. */
1409 return (int) l + (l < 0 ? -1 : 0);
1414 # if NEED_PRINTF_DOUBLE
1416 /* Assuming x is finite and > 0:
1417 Return an approximation for n with 10^n <= x < 10^(n+1).
1418 The approximation is usually the right n, but may be off by 1 sometimes. */
1420 floorlog10 (double x)
1427 /* Split into exponential part and mantissa. */
1428 y = frexp (x, &exp);
1429 if (!(y >= 0.0 && y < 1.0))
1435 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1437 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1438 exp -= GMP_LIMB_BITS;
1440 if (y < (1.0 / (1 << 16)))
1442 y *= 1.0 * (1 << 16);
1445 if (y < (1.0 / (1 << 8)))
1447 y *= 1.0 * (1 << 8);
1450 if (y < (1.0 / (1 << 4)))
1452 y *= 1.0 * (1 << 4);
1455 if (y < (1.0 / (1 << 2)))
1457 y *= 1.0 * (1 << 2);
1460 if (y < (1.0 / (1 << 1)))
1462 y *= 1.0 * (1 << 1);
1466 if (!(y >= 0.5 && y < 1.0))
1468 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1471 if (z < 0.70710678118654752444)
1473 z *= 1.4142135623730950488;
1476 if (z < 0.8408964152537145431)
1478 z *= 1.1892071150027210667;
1481 if (z < 0.91700404320467123175)
1483 z *= 1.0905077326652576592;
1486 if (z < 0.9576032806985736469)
1488 z *= 1.0442737824274138403;
1491 /* Now 0.95 <= z <= 1.01. */
1493 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1494 Four terms are enough to get an approximation with error < 10^-7. */
1495 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1496 /* Finally multiply with log(2)/log(10), yields an approximation for
1498 l *= 0.30102999566398119523;
1499 /* Round down to the next integer. */
1500 return (int) l + (l < 0 ? -1 : 0);
1505 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1506 a single '1' digit. */
1508 is_borderline (const char *digits, size_t precision)
1510 for (; precision > 0; precision--, digits++)
1516 return *digits == '\0';
1521 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99
1523 /* Use a different function name, to make it possible that the 'wchar_t'
1524 parametrization and the 'char' parametrization get compiled in the same
1525 translation unit. */
1526 # if WIDE_CHAR_VERSION
1527 # define MAX_ROOM_NEEDED wmax_room_needed
1529 # define MAX_ROOM_NEEDED max_room_needed
1532 /* Returns the number of TCHAR_T units needed as temporary space for the result
1533 of sprintf or SNPRINTF of a single conversion directive. */
1534 static inline size_t
1535 MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
1536 arg_type type, int flags, size_t width, int has_precision,
1537 size_t precision, int pad_ourselves)
1543 case 'd': case 'i': case 'u':
1544 # if HAVE_LONG_LONG_INT
1545 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1547 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1548 * 0.30103 /* binary -> decimal */
1550 + 1; /* turn floor into ceil */
1553 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1555 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1556 * 0.30103 /* binary -> decimal */
1558 + 1; /* turn floor into ceil */
1561 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1562 * 0.30103 /* binary -> decimal */
1564 + 1; /* turn floor into ceil */
1565 if (tmp_length < precision)
1566 tmp_length = precision;
1567 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1568 tmp_length = xsum (tmp_length, tmp_length);
1569 /* Add 1, to account for a leading sign. */
1570 tmp_length = xsum (tmp_length, 1);
1574 # if HAVE_LONG_LONG_INT
1575 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1577 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1578 * 0.333334 /* binary -> octal */
1580 + 1; /* turn floor into ceil */
1583 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1585 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1586 * 0.333334 /* binary -> octal */
1588 + 1; /* turn floor into ceil */
1591 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1592 * 0.333334 /* binary -> octal */
1594 + 1; /* turn floor into ceil */
1595 if (tmp_length < precision)
1596 tmp_length = precision;
1597 /* Add 1, to account for a leading sign. */
1598 tmp_length = xsum (tmp_length, 1);
1602 # if HAVE_LONG_LONG_INT
1603 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1605 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1606 * 0.25 /* binary -> hexadecimal */
1608 + 1; /* turn floor into ceil */
1611 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1613 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1614 * 0.25 /* binary -> hexadecimal */
1616 + 1; /* turn floor into ceil */
1619 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1620 * 0.25 /* binary -> hexadecimal */
1622 + 1; /* turn floor into ceil */
1623 if (tmp_length < precision)
1624 tmp_length = precision;
1625 /* Add 2, to account for a leading sign or alternate form. */
1626 tmp_length = xsum (tmp_length, 2);
1630 if (type == TYPE_LONGDOUBLE)
1632 (unsigned int) (LDBL_MAX_EXP
1633 * 0.30103 /* binary -> decimal */
1634 * 2 /* estimate for FLAG_GROUP */
1636 + 1 /* turn floor into ceil */
1637 + 10; /* sign, decimal point etc. */
1640 (unsigned int) (DBL_MAX_EXP
1641 * 0.30103 /* binary -> decimal */
1642 * 2 /* estimate for FLAG_GROUP */
1644 + 1 /* turn floor into ceil */
1645 + 10; /* sign, decimal point etc. */
1646 tmp_length = xsum (tmp_length, precision);
1649 case 'e': case 'E': case 'g': case 'G':
1651 12; /* sign, decimal point, exponent etc. */
1652 tmp_length = xsum (tmp_length, precision);
1656 if (type == TYPE_LONGDOUBLE)
1658 (unsigned int) (LDBL_DIG
1659 * 0.831 /* decimal -> hexadecimal */
1661 + 1; /* turn floor into ceil */
1664 (unsigned int) (DBL_DIG
1665 * 0.831 /* decimal -> hexadecimal */
1667 + 1; /* turn floor into ceil */
1668 if (tmp_length < precision)
1669 tmp_length = precision;
1670 /* Account for sign, decimal point etc. */
1671 tmp_length = xsum (tmp_length, 12);
1675 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
1676 if (type == TYPE_WIDE_CHAR)
1677 tmp_length = MB_CUR_MAX;
1685 if (type == TYPE_WIDE_STRING)
1687 # if WIDE_CHAR_VERSION
1688 /* ISO C says about %ls in fwprintf:
1689 "If the precision is not specified or is greater than the size
1690 of the array, the array shall contain a null wide character."
1691 So if there is a precision, we must not use wcslen. */
1692 const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
1695 tmp_length = local_wcsnlen (arg, precision);
1697 tmp_length = local_wcslen (arg);
1699 /* ISO C says about %ls in fprintf:
1700 "If a precision is specified, no more than that many bytes are
1701 written (including shift sequences, if any), and the array
1702 shall contain a null wide character if, to equal the multibyte
1703 character sequence length given by the precision, the function
1704 would need to access a wide character one past the end of the
1706 So if there is a precision, we must not use wcslen. */
1707 /* This case has already been handled separately in VASNPRINTF. */
1714 # if WIDE_CHAR_VERSION
1715 /* ISO C says about %s in fwprintf:
1716 "If the precision is not specified or is greater than the size
1717 of the converted array, the converted array shall contain a
1718 null wide character."
1719 So if there is a precision, we must not use strlen. */
1720 /* This case has already been handled separately in VASNPRINTF. */
1723 /* ISO C says about %s in fprintf:
1724 "If the precision is not specified or greater than the size of
1725 the array, the array shall contain a null character."
1726 So if there is a precision, we must not use strlen. */
1727 const char *arg = ap->arg[arg_index].a.a_string;
1730 tmp_length = local_strnlen (arg, precision);
1732 tmp_length = strlen (arg);
1739 (unsigned int) (sizeof (void *) * CHAR_BIT
1740 * 0.25 /* binary -> hexadecimal */
1742 + 1 /* turn floor into ceil */
1743 + 2; /* account for leading 0x */
1752 # if ENABLE_UNISTDIO
1753 /* Padding considers the number of characters, therefore the number of
1754 elements after padding may be
1755 > max (tmp_length, width)
1757 <= tmp_length + width. */
1758 tmp_length = xsum (tmp_length, width);
1760 /* Padding considers the number of elements, says POSIX. */
1761 if (tmp_length < width)
1766 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1774 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1775 const FCHAR_T *format, va_list args)
1780 if (PRINTF_PARSE (format, &d, &a) < 0)
1781 /* errno is already set. */
1785 if (d.dir != d.direct_alloc_dir) \
1787 if (a.arg != a.direct_alloc_arg) \
1790 if (PRINTF_FETCHARGS (args, &a) < 0)
1798 size_t buf_neededlength;
1800 TCHAR_T *buf_malloced;
1804 /* Output string accumulator. */
1809 /* Allocate a small buffer that will hold a directive passed to
1810 sprintf or snprintf. */
1812 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1814 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1816 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1817 buf_malloced = NULL;
1822 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1823 if (size_overflow_p (buf_memsize))
1824 goto out_of_memory_1;
1825 buf = (TCHAR_T *) malloc (buf_memsize);
1827 goto out_of_memory_1;
1831 if (resultbuf != NULL)
1834 allocated = *lengthp;
1843 result is either == resultbuf or == NULL or malloc-allocated.
1844 If length > 0, then result != NULL. */
1846 /* Ensures that allocated >= needed. Aborts through a jump to
1847 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1848 #define ENSURE_ALLOCATION(needed) \
1849 if ((needed) > allocated) \
1851 size_t memory_size; \
1854 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1855 if ((needed) > allocated) \
1856 allocated = (needed); \
1857 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1858 if (size_overflow_p (memory_size)) \
1859 goto out_of_memory; \
1860 if (result == resultbuf || result == NULL) \
1861 memory = (DCHAR_T *) malloc (memory_size); \
1863 memory = (DCHAR_T *) realloc (result, memory_size); \
1864 if (memory == NULL) \
1865 goto out_of_memory; \
1866 if (result == resultbuf && length > 0) \
1867 DCHAR_CPY (memory, result, length); \
1871 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1873 if (cp != dp->dir_start)
1875 size_t n = dp->dir_start - cp;
1876 size_t augmented_length = xsum (length, n);
1878 ENSURE_ALLOCATION (augmented_length);
1879 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1880 need that the format string contains only ASCII characters
1881 if FCHAR_T and DCHAR_T are not the same type. */
1882 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1884 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1885 length = augmented_length;
1890 result[length++] = (unsigned char) *cp++;
1897 /* Execute a single directive. */
1898 if (dp->conversion == '%')
1900 size_t augmented_length;
1902 if (!(dp->arg_index == ARG_NONE))
1904 augmented_length = xsum (length, 1);
1905 ENSURE_ALLOCATION (augmented_length);
1906 result[length] = '%';
1907 length = augmented_length;
1911 if (!(dp->arg_index != ARG_NONE))
1914 if (dp->conversion == 'n')
1916 switch (a.arg[dp->arg_index].type)
1918 case TYPE_COUNT_SCHAR_POINTER:
1919 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1921 case TYPE_COUNT_SHORT_POINTER:
1922 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1924 case TYPE_COUNT_INT_POINTER:
1925 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1927 case TYPE_COUNT_LONGINT_POINTER:
1928 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1930 #if HAVE_LONG_LONG_INT
1931 case TYPE_COUNT_LONGLONGINT_POINTER:
1932 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1940 /* The unistdio extensions. */
1941 else if (dp->conversion == 'U')
1943 arg_type type = a.arg[dp->arg_index].type;
1944 int flags = dp->flags;
1952 if (dp->width_start != dp->width_end)
1954 if (dp->width_arg_index != ARG_NONE)
1958 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1960 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." */
1966 width = (unsigned int) (-arg);
1973 const FCHAR_T *digitp = dp->width_start;
1976 width = xsum (xtimes (width, 10), *digitp++ - '0');
1977 while (digitp != dp->width_end);
1984 if (dp->precision_start != dp->precision_end)
1986 if (dp->precision_arg_index != ARG_NONE)
1990 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1992 arg = a.arg[dp->precision_arg_index].a.a_int;
1993 /* "A negative precision is taken as if the precision
2003 const FCHAR_T *digitp = dp->precision_start + 1;
2006 while (digitp != dp->precision_end)
2007 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2014 case TYPE_U8_STRING:
2016 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
2017 const uint8_t *arg_end;
2022 /* Use only PRECISION characters, from the left. */
2025 for (; precision > 0; precision--)
2027 int count = u8_strmblen (arg_end);
2032 if (!(result == resultbuf || result == NULL))
2034 if (buf_malloced != NULL)
2035 free (buf_malloced);
2046 /* Use the entire string, and count the number of
2052 int count = u8_strmblen (arg_end);
2057 if (!(result == resultbuf || result == NULL))
2059 if (buf_malloced != NULL)
2060 free (buf_malloced);
2071 /* Use the entire string. */
2072 arg_end = arg + u8_strlen (arg);
2073 /* The number of characters doesn't matter. */
2077 if (has_width && width > characters
2078 && !(dp->flags & FLAG_LEFT))
2080 size_t n = width - characters;
2081 ENSURE_ALLOCATION (xsum (length, n));
2082 DCHAR_SET (result + length, ' ', n);
2086 # if DCHAR_IS_UINT8_T
2088 size_t n = arg_end - arg;
2089 ENSURE_ALLOCATION (xsum (length, n));
2090 DCHAR_CPY (result + length, arg, n);
2095 DCHAR_T *converted = result + length;
2096 size_t converted_len = allocated - length;
2098 /* Convert from UTF-8 to locale encoding. */
2100 u8_conv_to_encoding (locale_charset (),
2101 iconveh_question_mark,
2102 arg, arg_end - arg, NULL,
2103 converted, &converted_len);
2105 /* Convert from UTF-8 to UTF-16/UTF-32. */
2107 U8_TO_DCHAR (arg, arg_end - arg,
2108 converted, &converted_len);
2110 if (converted == NULL)
2112 int saved_errno = errno;
2113 if (!(result == resultbuf || result == NULL))
2115 if (buf_malloced != NULL)
2116 free (buf_malloced);
2118 errno = saved_errno;
2121 if (converted != result + length)
2123 ENSURE_ALLOCATION (xsum (length, converted_len));
2124 DCHAR_CPY (result + length, converted, converted_len);
2127 length += converted_len;
2131 if (has_width && width > characters
2132 && (dp->flags & FLAG_LEFT))
2134 size_t n = width - characters;
2135 ENSURE_ALLOCATION (xsum (length, n));
2136 DCHAR_SET (result + length, ' ', n);
2142 case TYPE_U16_STRING:
2144 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
2145 const uint16_t *arg_end;
2150 /* Use only PRECISION characters, from the left. */
2153 for (; precision > 0; precision--)
2155 int count = u16_strmblen (arg_end);
2160 if (!(result == resultbuf || result == NULL))
2162 if (buf_malloced != NULL)
2163 free (buf_malloced);
2174 /* Use the entire string, and count the number of
2180 int count = u16_strmblen (arg_end);
2185 if (!(result == resultbuf || result == NULL))
2187 if (buf_malloced != NULL)
2188 free (buf_malloced);
2199 /* Use the entire string. */
2200 arg_end = arg + u16_strlen (arg);
2201 /* The number of characters doesn't matter. */
2205 if (has_width && width > characters
2206 && !(dp->flags & FLAG_LEFT))
2208 size_t n = width - characters;
2209 ENSURE_ALLOCATION (xsum (length, n));
2210 DCHAR_SET (result + length, ' ', n);
2214 # if DCHAR_IS_UINT16_T
2216 size_t n = arg_end - arg;
2217 ENSURE_ALLOCATION (xsum (length, n));
2218 DCHAR_CPY (result + length, arg, n);
2223 DCHAR_T *converted = result + length;
2224 size_t converted_len = allocated - length;
2226 /* Convert from UTF-16 to locale encoding. */
2228 u16_conv_to_encoding (locale_charset (),
2229 iconveh_question_mark,
2230 arg, arg_end - arg, NULL,
2231 converted, &converted_len);
2233 /* Convert from UTF-16 to UTF-8/UTF-32. */
2235 U16_TO_DCHAR (arg, arg_end - arg,
2236 converted, &converted_len);
2238 if (converted == NULL)
2240 int saved_errno = errno;
2241 if (!(result == resultbuf || result == NULL))
2243 if (buf_malloced != NULL)
2244 free (buf_malloced);
2246 errno = saved_errno;
2249 if (converted != result + length)
2251 ENSURE_ALLOCATION (xsum (length, converted_len));
2252 DCHAR_CPY (result + length, converted, converted_len);
2255 length += converted_len;
2259 if (has_width && width > characters
2260 && (dp->flags & FLAG_LEFT))
2262 size_t n = width - characters;
2263 ENSURE_ALLOCATION (xsum (length, n));
2264 DCHAR_SET (result + length, ' ', n);
2270 case TYPE_U32_STRING:
2272 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
2273 const uint32_t *arg_end;
2278 /* Use only PRECISION characters, from the left. */
2281 for (; precision > 0; precision--)
2283 int count = u32_strmblen (arg_end);
2288 if (!(result == resultbuf || result == NULL))
2290 if (buf_malloced != NULL)
2291 free (buf_malloced);
2302 /* Use the entire string, and count the number of
2308 int count = u32_strmblen (arg_end);
2313 if (!(result == resultbuf || result == NULL))
2315 if (buf_malloced != NULL)
2316 free (buf_malloced);
2327 /* Use the entire string. */
2328 arg_end = arg + u32_strlen (arg);
2329 /* The number of characters doesn't matter. */
2333 if (has_width && width > characters
2334 && !(dp->flags & FLAG_LEFT))
2336 size_t n = width - characters;
2337 ENSURE_ALLOCATION (xsum (length, n));
2338 DCHAR_SET (result + length, ' ', n);
2342 # if DCHAR_IS_UINT32_T
2344 size_t n = arg_end - arg;
2345 ENSURE_ALLOCATION (xsum (length, n));
2346 DCHAR_CPY (result + length, arg, n);
2351 DCHAR_T *converted = result + length;
2352 size_t converted_len = allocated - length;
2354 /* Convert from UTF-32 to locale encoding. */
2356 u32_conv_to_encoding (locale_charset (),
2357 iconveh_question_mark,
2358 arg, arg_end - arg, NULL,
2359 converted, &converted_len);
2361 /* Convert from UTF-32 to UTF-8/UTF-16. */
2363 U32_TO_DCHAR (arg, arg_end - arg,
2364 converted, &converted_len);
2366 if (converted == NULL)
2368 int saved_errno = errno;
2369 if (!(result == resultbuf || result == NULL))
2371 if (buf_malloced != NULL)
2372 free (buf_malloced);
2374 errno = saved_errno;
2377 if (converted != result + length)
2379 ENSURE_ALLOCATION (xsum (length, converted_len));
2380 DCHAR_CPY (result + length, converted, converted_len);
2383 length += converted_len;
2387 if (has_width && width > characters
2388 && (dp->flags & FLAG_LEFT))
2390 size_t n = width - characters;
2391 ENSURE_ALLOCATION (xsum (length, n));
2392 DCHAR_SET (result + length, ' ', n);
2403 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T
2404 else if (dp->conversion == 's'
2405 # if WIDE_CHAR_VERSION
2406 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2408 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2412 /* The normal handling of the 's' directive below requires
2413 allocating a temporary buffer. The determination of its
2414 length (tmp_length), in the case when a precision is
2415 specified, below requires a conversion between a char[]
2416 string and a wchar_t[] wide string. It could be done, but
2417 we have no guarantee that the implementation of sprintf will
2418 use the exactly same algorithm. Without this guarantee, it
2419 is possible to have buffer overrun bugs. In order to avoid
2420 such bugs, we implement the entire processing of the 's'
2421 directive ourselves. */
2422 int flags = dp->flags;
2430 if (dp->width_start != dp->width_end)
2432 if (dp->width_arg_index != ARG_NONE)
2436 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2438 arg = a.arg[dp->width_arg_index].a.a_int;
2441 /* "A negative field width is taken as a '-' flag
2442 followed by a positive field width." */
2444 width = (unsigned int) (-arg);
2451 const FCHAR_T *digitp = dp->width_start;
2454 width = xsum (xtimes (width, 10), *digitp++ - '0');
2455 while (digitp != dp->width_end);
2462 if (dp->precision_start != dp->precision_end)
2464 if (dp->precision_arg_index != ARG_NONE)
2468 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2470 arg = a.arg[dp->precision_arg_index].a.a_int;
2471 /* "A negative precision is taken as if the precision
2481 const FCHAR_T *digitp = dp->precision_start + 1;
2484 while (digitp != dp->precision_end)
2485 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2490 # if WIDE_CHAR_VERSION
2491 /* %s in vasnwprintf. See the specification of fwprintf. */
2493 const char *arg = a.arg[dp->arg_index].a.a_string;
2494 const char *arg_end;
2499 /* Use only as many bytes as needed to produce PRECISION
2500 wide characters, from the left. */
2503 memset (&state, '\0', sizeof (mbstate_t));
2507 for (; precision > 0; precision--)
2511 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2513 count = mblen (arg_end, MB_CUR_MAX);
2516 /* Found the terminating NUL. */
2520 /* Invalid or incomplete multibyte character. */
2521 if (!(result == resultbuf || result == NULL))
2523 if (buf_malloced != NULL)
2524 free (buf_malloced);
2535 /* Use the entire string, and count the number of wide
2539 memset (&state, '\0', sizeof (mbstate_t));
2547 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2549 count = mblen (arg_end, MB_CUR_MAX);
2552 /* Found the terminating NUL. */
2556 /* Invalid or incomplete multibyte character. */
2557 if (!(result == resultbuf || result == NULL))
2559 if (buf_malloced != NULL)
2560 free (buf_malloced);
2571 /* Use the entire string. */
2572 arg_end = arg + strlen (arg);
2573 /* The number of characters doesn't matter. */
2577 if (has_width && width > characters
2578 && !(dp->flags & FLAG_LEFT))
2580 size_t n = width - characters;
2581 ENSURE_ALLOCATION (xsum (length, n));
2582 DCHAR_SET (result + length, ' ', n);
2586 if (has_precision || has_width)
2588 /* We know the number of wide characters in advance. */
2592 memset (&state, '\0', sizeof (mbstate_t));
2594 ENSURE_ALLOCATION (xsum (length, characters));
2595 for (remaining = characters; remaining > 0; remaining--)
2600 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2602 count = mbtowc (&wc, arg, arg_end - arg);
2605 /* mbrtowc not consistent with mbrlen, or mbtowc
2606 not consistent with mblen. */
2608 result[length++] = wc;
2611 if (!(arg == arg_end))
2618 memset (&state, '\0', sizeof (mbstate_t));
2620 while (arg < arg_end)
2625 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2627 count = mbtowc (&wc, arg, arg_end - arg);
2630 /* mbrtowc not consistent with mbrlen, or mbtowc
2631 not consistent with mblen. */
2633 ENSURE_ALLOCATION (xsum (length, 1));
2634 result[length++] = wc;
2639 if (has_width && width > characters
2640 && (dp->flags & FLAG_LEFT))
2642 size_t n = width - characters;
2643 ENSURE_ALLOCATION (xsum (length, n));
2644 DCHAR_SET (result + length, ' ', n);
2649 /* %ls in vasnprintf. See the specification of fprintf. */
2651 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2652 const wchar_t *arg_end;
2654 # if !DCHAR_IS_TCHAR
2655 /* This code assumes that TCHAR_T is 'char'. */
2656 verify (sizeof (TCHAR_T) == 1);
2665 /* Use only as many wide characters as needed to produce
2666 at most PRECISION bytes, from the left. */
2667 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2669 memset (&state, '\0', sizeof (mbstate_t));
2673 while (precision > 0)
2675 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2679 /* Found the terminating null wide character. */
2681 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2682 count = wcrtomb (cbuf, *arg_end, &state);
2684 count = wctomb (cbuf, *arg_end);
2688 /* Cannot convert. */
2689 if (!(result == resultbuf || result == NULL))
2691 if (buf_malloced != NULL)
2692 free (buf_malloced);
2697 if (precision < count)
2700 characters += count;
2710 /* Use the entire string, and count the number of
2712 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2714 memset (&state, '\0', sizeof (mbstate_t));
2720 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2724 /* Found the terminating null wide character. */
2726 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2727 count = wcrtomb (cbuf, *arg_end, &state);
2729 count = wctomb (cbuf, *arg_end);
2733 /* Cannot convert. */
2734 if (!(result == resultbuf || result == NULL))
2736 if (buf_malloced != NULL)
2737 free (buf_malloced);
2743 characters += count;
2749 /* Use the entire string. */
2750 arg_end = arg + local_wcslen (arg);
2751 /* The number of bytes doesn't matter. */
2756 # if !DCHAR_IS_TCHAR
2757 /* Convert the string into a piece of temporary memory. */
2758 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2762 TCHAR_T *tmpptr = tmpsrc;
2764 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2766 memset (&state, '\0', sizeof (mbstate_t));
2768 for (remaining = characters; remaining > 0; )
2770 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2775 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2776 count = wcrtomb (cbuf, *arg, &state);
2778 count = wctomb (cbuf, *arg);
2781 /* Inconsistency. */
2783 memcpy (tmpptr, cbuf, count);
2788 if (!(arg == arg_end))
2792 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2794 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2795 iconveh_question_mark,
2801 int saved_errno = errno;
2803 if (!(result == resultbuf || result == NULL))
2805 if (buf_malloced != NULL)
2806 free (buf_malloced);
2808 errno = saved_errno;
2816 # if ENABLE_UNISTDIO
2817 /* Outside POSIX, it's preferrable to compare the width
2818 against the number of _characters_ of the converted
2820 w = DCHAR_MBSNLEN (result + length, characters);
2822 /* The width is compared against the number of _bytes_
2823 of the converted value, says POSIX. */
2828 /* w doesn't matter. */
2831 if (has_width && width > w
2832 && !(dp->flags & FLAG_LEFT))
2834 size_t n = width - w;
2835 ENSURE_ALLOCATION (xsum (length, n));
2836 DCHAR_SET (result + length, ' ', n);
2841 if (has_precision || has_width)
2843 /* We know the number of bytes in advance. */
2845 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2847 memset (&state, '\0', sizeof (mbstate_t));
2849 ENSURE_ALLOCATION (xsum (length, characters));
2850 for (remaining = characters; remaining > 0; )
2852 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2857 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2858 count = wcrtomb (cbuf, *arg, &state);
2860 count = wctomb (cbuf, *arg);
2863 /* Inconsistency. */
2865 memcpy (result + length, cbuf, count);
2870 if (!(arg == arg_end))
2875 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2877 memset (&state, '\0', sizeof (mbstate_t));
2879 while (arg < arg_end)
2881 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2886 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2887 count = wcrtomb (cbuf, *arg, &state);
2889 count = wctomb (cbuf, *arg);
2893 /* Cannot convert. */
2894 if (!(result == resultbuf || result == NULL))
2896 if (buf_malloced != NULL)
2897 free (buf_malloced);
2902 ENSURE_ALLOCATION (xsum (length, count));
2903 memcpy (result + length, cbuf, count);
2909 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2910 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2912 length += tmpdst_len;
2915 if (has_width && width > w
2916 && (dp->flags & FLAG_LEFT))
2918 size_t n = width - w;
2919 ENSURE_ALLOCATION (xsum (length, n));
2920 DCHAR_SET (result + length, ' ', n);
2927 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2928 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2929 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2931 # if NEED_PRINTF_DOUBLE
2932 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2934 # if NEED_PRINTF_LONG_DOUBLE
2935 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2941 arg_type type = a.arg[dp->arg_index].type;
2942 int flags = dp->flags;
2948 DCHAR_T tmpbuf[700];
2955 if (dp->width_start != dp->width_end)
2957 if (dp->width_arg_index != ARG_NONE)
2961 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2963 arg = a.arg[dp->width_arg_index].a.a_int;
2966 /* "A negative field width is taken as a '-' flag
2967 followed by a positive field width." */
2969 width = (unsigned int) (-arg);
2976 const FCHAR_T *digitp = dp->width_start;
2979 width = xsum (xtimes (width, 10), *digitp++ - '0');
2980 while (digitp != dp->width_end);
2987 if (dp->precision_start != dp->precision_end)
2989 if (dp->precision_arg_index != ARG_NONE)
2993 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2995 arg = a.arg[dp->precision_arg_index].a.a_int;
2996 /* "A negative precision is taken as if the precision
3006 const FCHAR_T *digitp = dp->precision_start + 1;
3009 while (digitp != dp->precision_end)
3010 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3015 /* Allocate a temporary buffer of sufficient size. */
3016 if (type == TYPE_LONGDOUBLE)
3018 (unsigned int) ((LDBL_DIG + 1)
3019 * 0.831 /* decimal -> hexadecimal */
3021 + 1; /* turn floor into ceil */
3024 (unsigned int) ((DBL_DIG + 1)
3025 * 0.831 /* decimal -> hexadecimal */
3027 + 1; /* turn floor into ceil */
3028 if (tmp_length < precision)
3029 tmp_length = precision;
3030 /* Account for sign, decimal point etc. */
3031 tmp_length = xsum (tmp_length, 12);
3033 if (tmp_length < width)
3036 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3038 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3042 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3044 if (size_overflow_p (tmp_memsize))
3045 /* Overflow, would lead to out of memory. */
3047 tmp = (DCHAR_T *) malloc (tmp_memsize);
3049 /* Out of memory. */
3055 if (type == TYPE_LONGDOUBLE)
3057 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
3058 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3062 if (dp->conversion == 'A')
3064 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3068 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3074 DECL_LONG_DOUBLE_ROUNDING
3076 BEGIN_LONG_DOUBLE_ROUNDING ();
3078 if (signbit (arg)) /* arg < 0.0L or negative zero */
3086 else if (flags & FLAG_SHOWSIGN)
3088 else if (flags & FLAG_SPACE)
3091 if (arg > 0.0L && arg + arg == arg)
3093 if (dp->conversion == 'A')
3095 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3099 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3105 long double mantissa;
3108 mantissa = printf_frexpl (arg, &exponent);
3116 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
3118 /* Round the mantissa. */
3119 long double tail = mantissa;
3122 for (q = precision; ; q--)
3124 int digit = (int) tail;
3128 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
3137 for (q = precision; q > 0; q--)
3143 *p++ = dp->conversion - 'A' + 'X';
3148 digit = (int) mantissa;
3151 if ((flags & FLAG_ALT)
3152 || mantissa > 0.0L || precision > 0)
3154 *p++ = decimal_point_char ();
3155 /* This loop terminates because we assume
3156 that FLT_RADIX is a power of 2. */
3157 while (mantissa > 0.0L)
3160 digit = (int) mantissa;
3165 : dp->conversion - 10);
3169 while (precision > 0)
3176 *p++ = dp->conversion - 'A' + 'P';
3177 # if WIDE_CHAR_VERSION
3179 static const wchar_t decimal_format[] =
3180 { '%', '+', 'd', '\0' };
3181 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3186 if (sizeof (DCHAR_T) == 1)
3188 sprintf ((char *) p, "%+d", exponent);
3196 sprintf (expbuf, "%+d", exponent);
3197 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3203 END_LONG_DOUBLE_ROUNDING ();
3211 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
3212 double arg = a.arg[dp->arg_index].a.a_double;
3216 if (dp->conversion == 'A')
3218 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3222 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3229 if (signbit (arg)) /* arg < 0.0 or negative zero */
3237 else if (flags & FLAG_SHOWSIGN)
3239 else if (flags & FLAG_SPACE)
3242 if (arg > 0.0 && arg + arg == arg)
3244 if (dp->conversion == 'A')
3246 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3250 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3259 mantissa = printf_frexp (arg, &exponent);
3267 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
3269 /* Round the mantissa. */
3270 double tail = mantissa;
3273 for (q = precision; ; q--)
3275 int digit = (int) tail;
3279 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
3288 for (q = precision; q > 0; q--)
3294 *p++ = dp->conversion - 'A' + 'X';
3299 digit = (int) mantissa;
3302 if ((flags & FLAG_ALT)
3303 || mantissa > 0.0 || precision > 0)
3305 *p++ = decimal_point_char ();
3306 /* This loop terminates because we assume
3307 that FLT_RADIX is a power of 2. */
3308 while (mantissa > 0.0)
3311 digit = (int) mantissa;
3316 : dp->conversion - 10);
3320 while (precision > 0)
3327 *p++ = dp->conversion - 'A' + 'P';
3328 # if WIDE_CHAR_VERSION
3330 static const wchar_t decimal_format[] =
3331 { '%', '+', 'd', '\0' };
3332 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3337 if (sizeof (DCHAR_T) == 1)
3339 sprintf ((char *) p, "%+d", exponent);
3347 sprintf (expbuf, "%+d", exponent);
3348 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3358 /* The generated string now extends from tmp to p, with the
3359 zero padding insertion point being at pad_ptr. */
3360 if (has_width && p - tmp < width)
3362 size_t pad = width - (p - tmp);
3363 DCHAR_T *end = p + pad;
3365 if (flags & FLAG_LEFT)
3367 /* Pad with spaces on the right. */
3368 for (; pad > 0; pad--)
3371 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3373 /* Pad with zeroes. */
3378 for (; pad > 0; pad--)
3383 /* Pad with spaces on the left. */
3388 for (; pad > 0; pad--)
3396 size_t count = p - tmp;
3398 if (count >= tmp_length)
3399 /* tmp_length was incorrectly calculated - fix the
3403 /* Make room for the result. */
3404 if (count >= allocated - length)
3406 size_t n = xsum (length, count);
3408 ENSURE_ALLOCATION (n);
3411 /* Append the result. */
3412 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3419 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3420 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3421 || dp->conversion == 'e' || dp->conversion == 'E'
3422 || dp->conversion == 'g' || dp->conversion == 'G'
3423 || dp->conversion == 'a' || dp->conversion == 'A')
3425 # if NEED_PRINTF_DOUBLE
3426 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3427 # elif NEED_PRINTF_INFINITE_DOUBLE
3428 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3429 /* The systems (mingw) which produce wrong output
3430 for Inf, -Inf, and NaN also do so for -0.0.
3431 Therefore we treat this case here as well. */
3432 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3434 # if NEED_PRINTF_LONG_DOUBLE
3435 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3436 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3437 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3438 /* Some systems produce wrong output for Inf,
3439 -Inf, and NaN. Some systems in this category
3440 (IRIX 5.3) also do so for -0.0. Therefore we
3441 treat this case here as well. */
3442 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3446 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3447 arg_type type = a.arg[dp->arg_index].type;
3449 int flags = dp->flags;
3455 DCHAR_T tmpbuf[700];
3462 if (dp->width_start != dp->width_end)
3464 if (dp->width_arg_index != ARG_NONE)
3468 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3470 arg = a.arg[dp->width_arg_index].a.a_int;
3473 /* "A negative field width is taken as a '-' flag
3474 followed by a positive field width." */
3476 width = (unsigned int) (-arg);
3483 const FCHAR_T *digitp = dp->width_start;
3486 width = xsum (xtimes (width, 10), *digitp++ - '0');
3487 while (digitp != dp->width_end);
3494 if (dp->precision_start != dp->precision_end)
3496 if (dp->precision_arg_index != ARG_NONE)
3500 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3502 arg = a.arg[dp->precision_arg_index].a.a_int;
3503 /* "A negative precision is taken as if the precision
3513 const FCHAR_T *digitp = dp->precision_start + 1;
3516 while (digitp != dp->precision_end)
3517 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3522 /* POSIX specifies the default precision to be 6 for %f, %F,
3523 %e, %E, but not for %g, %G. Implementations appear to use
3524 the same default precision also for %g, %G. But for %a, %A,
3525 the default precision is 0. */
3527 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3530 /* Allocate a temporary buffer of sufficient size. */
3531 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3532 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3533 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3534 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3535 # elif NEED_PRINTF_LONG_DOUBLE
3536 tmp_length = LDBL_DIG + 1;
3537 # elif NEED_PRINTF_DOUBLE
3538 tmp_length = DBL_DIG + 1;
3542 if (tmp_length < precision)
3543 tmp_length = precision;
3544 # if NEED_PRINTF_LONG_DOUBLE
3545 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3546 if (type == TYPE_LONGDOUBLE)
3548 if (dp->conversion == 'f' || dp->conversion == 'F')
3550 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3551 if (!(isnanl (arg) || arg + arg == arg))
3553 /* arg is finite and nonzero. */
3554 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3555 if (exponent >= 0 && tmp_length < exponent + precision)
3556 tmp_length = exponent + precision;
3560 # if NEED_PRINTF_DOUBLE
3561 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3562 if (type == TYPE_DOUBLE)
3564 if (dp->conversion == 'f' || dp->conversion == 'F')
3566 double arg = a.arg[dp->arg_index].a.a_double;
3567 if (!(isnand (arg) || arg + arg == arg))
3569 /* arg is finite and nonzero. */
3570 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3571 if (exponent >= 0 && tmp_length < exponent + precision)
3572 tmp_length = exponent + precision;
3576 /* Account for sign, decimal point etc. */
3577 tmp_length = xsum (tmp_length, 12);
3579 if (tmp_length < width)
3582 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3584 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3588 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3590 if (size_overflow_p (tmp_memsize))
3591 /* Overflow, would lead to out of memory. */
3593 tmp = (DCHAR_T *) malloc (tmp_memsize);
3595 /* Out of memory. */
3602 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3603 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3604 if (type == TYPE_LONGDOUBLE)
3607 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3611 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3613 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3617 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3623 DECL_LONG_DOUBLE_ROUNDING
3625 BEGIN_LONG_DOUBLE_ROUNDING ();
3627 if (signbit (arg)) /* arg < 0.0L or negative zero */
3635 else if (flags & FLAG_SHOWSIGN)
3637 else if (flags & FLAG_SPACE)
3640 if (arg > 0.0L && arg + arg == arg)
3642 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3644 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3648 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3653 # if NEED_PRINTF_LONG_DOUBLE
3656 if (dp->conversion == 'f' || dp->conversion == 'F')
3662 scale10_round_decimal_long_double (arg, precision);
3665 END_LONG_DOUBLE_ROUNDING ();
3668 ndigits = strlen (digits);
3670 if (ndigits > precision)
3674 *p++ = digits[ndigits];
3676 while (ndigits > precision);
3679 /* Here ndigits <= precision. */
3680 if ((flags & FLAG_ALT) || precision > 0)
3682 *p++ = decimal_point_char ();
3683 for (; precision > ndigits; precision--)
3688 *p++ = digits[ndigits];
3694 else if (dp->conversion == 'e' || dp->conversion == 'E')
3702 if ((flags & FLAG_ALT) || precision > 0)
3704 *p++ = decimal_point_char ();
3705 for (; precision > 0; precision--)
3716 exponent = floorlog10l (arg);
3721 scale10_round_decimal_long_double (arg,
3722 (int)precision - exponent);
3725 END_LONG_DOUBLE_ROUNDING ();
3728 ndigits = strlen (digits);
3730 if (ndigits == precision + 1)
3732 if (ndigits < precision
3733 || ndigits > precision + 2)
3734 /* The exponent was not guessed
3735 precisely enough. */
3738 /* None of two values of exponent is
3739 the right one. Prevent an endless
3743 if (ndigits == precision)
3749 /* Here ndigits = precision+1. */
3750 if (is_borderline (digits, precision))
3752 /* Maybe the exponent guess was too high
3753 and a smaller exponent can be reached
3754 by turning a 10...0 into 9...9x. */
3756 scale10_round_decimal_long_double (arg,
3757 (int)precision - exponent + 1);
3758 if (digits2 == NULL)
3761 END_LONG_DOUBLE_ROUNDING ();
3764 if (strlen (digits2) == precision + 1)
3773 /* Here ndigits = precision+1. */
3775 *p++ = digits[--ndigits];
3776 if ((flags & FLAG_ALT) || precision > 0)
3778 *p++ = decimal_point_char ();
3782 *p++ = digits[ndigits];
3789 *p++ = dp->conversion; /* 'e' or 'E' */
3790 # if WIDE_CHAR_VERSION
3792 static const wchar_t decimal_format[] =
3793 { '%', '+', '.', '2', 'd', '\0' };
3794 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3799 if (sizeof (DCHAR_T) == 1)
3801 sprintf ((char *) p, "%+.2d", exponent);
3809 sprintf (expbuf, "%+.2d", exponent);
3810 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3815 else if (dp->conversion == 'g' || dp->conversion == 'G')
3819 /* precision >= 1. */
3822 /* The exponent is 0, >= -4, < precision.
3823 Use fixed-point notation. */
3825 size_t ndigits = precision;
3826 /* Number of trailing zeroes that have to be
3829 (flags & FLAG_ALT ? 0 : precision - 1);
3833 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3835 *p++ = decimal_point_char ();
3836 while (ndigits > nzeroes)
3852 exponent = floorlog10l (arg);
3857 scale10_round_decimal_long_double (arg,
3858 (int)(precision - 1) - exponent);
3861 END_LONG_DOUBLE_ROUNDING ();
3864 ndigits = strlen (digits);
3866 if (ndigits == precision)
3868 if (ndigits < precision - 1
3869 || ndigits > precision + 1)
3870 /* The exponent was not guessed
3871 precisely enough. */
3874 /* None of two values of exponent is
3875 the right one. Prevent an endless
3879 if (ndigits < precision)
3885 /* Here ndigits = precision. */
3886 if (is_borderline (digits, precision - 1))
3888 /* Maybe the exponent guess was too high
3889 and a smaller exponent can be reached
3890 by turning a 10...0 into 9...9x. */
3892 scale10_round_decimal_long_double (arg,
3893 (int)(precision - 1) - exponent + 1);
3894 if (digits2 == NULL)
3897 END_LONG_DOUBLE_ROUNDING ();
3900 if (strlen (digits2) == precision)
3909 /* Here ndigits = precision. */
3911 /* Determine the number of trailing zeroes
3912 that have to be dropped. */
3914 if ((flags & FLAG_ALT) == 0)
3915 while (nzeroes < ndigits
3916 && digits[nzeroes] == '0')
3919 /* The exponent is now determined. */
3921 && exponent < (long)precision)
3923 /* Fixed-point notation:
3924 max(exponent,0)+1 digits, then the
3925 decimal point, then the remaining
3926 digits without trailing zeroes. */
3929 size_t count = exponent + 1;
3930 /* Note: count <= precision = ndigits. */
3931 for (; count > 0; count--)
3932 *p++ = digits[--ndigits];
3933 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3935 *p++ = decimal_point_char ();
3936 while (ndigits > nzeroes)
3939 *p++ = digits[ndigits];
3945 size_t count = -exponent - 1;
3947 *p++ = decimal_point_char ();
3948 for (; count > 0; count--)
3950 while (ndigits > nzeroes)
3953 *p++ = digits[ndigits];
3959 /* Exponential notation. */
3960 *p++ = digits[--ndigits];
3961 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3963 *p++ = decimal_point_char ();
3964 while (ndigits > nzeroes)
3967 *p++ = digits[ndigits];
3970 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3971 # if WIDE_CHAR_VERSION
3973 static const wchar_t decimal_format[] =
3974 { '%', '+', '.', '2', 'd', '\0' };
3975 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3980 if (sizeof (DCHAR_T) == 1)
3982 sprintf ((char *) p, "%+.2d", exponent);
3990 sprintf (expbuf, "%+.2d", exponent);
3991 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4003 /* arg is finite. */
4009 if (dp->conversion == 'f' || dp->conversion == 'F')
4012 if ((flags & FLAG_ALT) || precision > 0)
4014 *p++ = decimal_point_char ();
4015 for (; precision > 0; precision--)
4019 else if (dp->conversion == 'e' || dp->conversion == 'E')
4022 if ((flags & FLAG_ALT) || precision > 0)
4024 *p++ = decimal_point_char ();
4025 for (; precision > 0; precision--)
4028 *p++ = dp->conversion; /* 'e' or 'E' */
4033 else if (dp->conversion == 'g' || dp->conversion == 'G')
4036 if (flags & FLAG_ALT)
4039 (precision > 0 ? precision - 1 : 0);
4040 *p++ = decimal_point_char ();
4041 for (; ndigits > 0; --ndigits)
4045 else if (dp->conversion == 'a' || dp->conversion == 'A')
4048 *p++ = dp->conversion - 'A' + 'X';
4051 if ((flags & FLAG_ALT) || precision > 0)
4053 *p++ = decimal_point_char ();
4054 for (; precision > 0; precision--)
4057 *p++ = dp->conversion - 'A' + 'P';
4066 END_LONG_DOUBLE_ROUNDING ();
4069 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4073 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4075 double arg = a.arg[dp->arg_index].a.a_double;
4079 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4081 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4085 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4092 if (signbit (arg)) /* arg < 0.0 or negative zero */
4100 else if (flags & FLAG_SHOWSIGN)
4102 else if (flags & FLAG_SPACE)
4105 if (arg > 0.0 && arg + arg == arg)
4107 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4109 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4113 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4118 # if NEED_PRINTF_DOUBLE
4121 if (dp->conversion == 'f' || dp->conversion == 'F')
4127 scale10_round_decimal_double (arg, precision);
4130 ndigits = strlen (digits);
4132 if (ndigits > precision)
4136 *p++ = digits[ndigits];
4138 while (ndigits > precision);
4141 /* Here ndigits <= precision. */
4142 if ((flags & FLAG_ALT) || precision > 0)
4144 *p++ = decimal_point_char ();
4145 for (; precision > ndigits; precision--)
4150 *p++ = digits[ndigits];
4156 else if (dp->conversion == 'e' || dp->conversion == 'E')
4164 if ((flags & FLAG_ALT) || precision > 0)
4166 *p++ = decimal_point_char ();
4167 for (; precision > 0; precision--)
4178 exponent = floorlog10 (arg);
4183 scale10_round_decimal_double (arg,
4184 (int)precision - exponent);
4187 ndigits = strlen (digits);
4189 if (ndigits == precision + 1)
4191 if (ndigits < precision
4192 || ndigits > precision + 2)
4193 /* The exponent was not guessed
4194 precisely enough. */
4197 /* None of two values of exponent is
4198 the right one. Prevent an endless
4202 if (ndigits == precision)
4208 /* Here ndigits = precision+1. */
4209 if (is_borderline (digits, precision))
4211 /* Maybe the exponent guess was too high
4212 and a smaller exponent can be reached
4213 by turning a 10...0 into 9...9x. */
4215 scale10_round_decimal_double (arg,
4216 (int)precision - exponent + 1);
4217 if (digits2 == NULL)
4222 if (strlen (digits2) == precision + 1)
4231 /* Here ndigits = precision+1. */
4233 *p++ = digits[--ndigits];
4234 if ((flags & FLAG_ALT) || precision > 0)
4236 *p++ = decimal_point_char ();
4240 *p++ = digits[ndigits];
4247 *p++ = dp->conversion; /* 'e' or 'E' */
4248 # if WIDE_CHAR_VERSION
4250 static const wchar_t decimal_format[] =
4251 /* Produce the same number of exponent digits
4252 as the native printf implementation. */
4253 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4254 { '%', '+', '.', '3', 'd', '\0' };
4256 { '%', '+', '.', '2', 'd', '\0' };
4258 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4264 static const char decimal_format[] =
4265 /* Produce the same number of exponent digits
4266 as the native printf implementation. */
4267 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4272 if (sizeof (DCHAR_T) == 1)
4274 sprintf ((char *) p, decimal_format, exponent);
4282 sprintf (expbuf, decimal_format, exponent);
4283 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4289 else if (dp->conversion == 'g' || dp->conversion == 'G')
4293 /* precision >= 1. */
4296 /* The exponent is 0, >= -4, < precision.
4297 Use fixed-point notation. */
4299 size_t ndigits = precision;
4300 /* Number of trailing zeroes that have to be
4303 (flags & FLAG_ALT ? 0 : precision - 1);
4307 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4309 *p++ = decimal_point_char ();
4310 while (ndigits > nzeroes)
4326 exponent = floorlog10 (arg);
4331 scale10_round_decimal_double (arg,
4332 (int)(precision - 1) - exponent);
4335 ndigits = strlen (digits);
4337 if (ndigits == precision)
4339 if (ndigits < precision - 1
4340 || ndigits > precision + 1)
4341 /* The exponent was not guessed
4342 precisely enough. */
4345 /* None of two values of exponent is
4346 the right one. Prevent an endless
4350 if (ndigits < precision)
4356 /* Here ndigits = precision. */
4357 if (is_borderline (digits, precision - 1))
4359 /* Maybe the exponent guess was too high
4360 and a smaller exponent can be reached
4361 by turning a 10...0 into 9...9x. */
4363 scale10_round_decimal_double (arg,
4364 (int)(precision - 1) - exponent + 1);
4365 if (digits2 == NULL)
4370 if (strlen (digits2) == precision)
4379 /* Here ndigits = precision. */
4381 /* Determine the number of trailing zeroes
4382 that have to be dropped. */
4384 if ((flags & FLAG_ALT) == 0)
4385 while (nzeroes < ndigits
4386 && digits[nzeroes] == '0')
4389 /* The exponent is now determined. */
4391 && exponent < (long)precision)
4393 /* Fixed-point notation:
4394 max(exponent,0)+1 digits, then the
4395 decimal point, then the remaining
4396 digits without trailing zeroes. */
4399 size_t count = exponent + 1;
4400 /* Note: count <= precision = ndigits. */
4401 for (; count > 0; count--)
4402 *p++ = digits[--ndigits];
4403 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4405 *p++ = decimal_point_char ();
4406 while (ndigits > nzeroes)
4409 *p++ = digits[ndigits];
4415 size_t count = -exponent - 1;
4417 *p++ = decimal_point_char ();
4418 for (; count > 0; count--)
4420 while (ndigits > nzeroes)
4423 *p++ = digits[ndigits];
4429 /* Exponential notation. */
4430 *p++ = digits[--ndigits];
4431 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4433 *p++ = decimal_point_char ();
4434 while (ndigits > nzeroes)
4437 *p++ = digits[ndigits];
4440 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4441 # if WIDE_CHAR_VERSION
4443 static const wchar_t decimal_format[] =
4444 /* Produce the same number of exponent digits
4445 as the native printf implementation. */
4446 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4447 { '%', '+', '.', '3', 'd', '\0' };
4449 { '%', '+', '.', '2', 'd', '\0' };
4451 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4457 static const char decimal_format[] =
4458 /* Produce the same number of exponent digits
4459 as the native printf implementation. */
4460 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4465 if (sizeof (DCHAR_T) == 1)
4467 sprintf ((char *) p, decimal_format, exponent);
4475 sprintf (expbuf, decimal_format, exponent);
4476 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4489 /* arg is finite. */
4495 if (dp->conversion == 'f' || dp->conversion == 'F')
4498 if ((flags & FLAG_ALT) || precision > 0)
4500 *p++ = decimal_point_char ();
4501 for (; precision > 0; precision--)
4505 else if (dp->conversion == 'e' || dp->conversion == 'E')
4508 if ((flags & FLAG_ALT) || precision > 0)
4510 *p++ = decimal_point_char ();
4511 for (; precision > 0; precision--)
4514 *p++ = dp->conversion; /* 'e' or 'E' */
4516 /* Produce the same number of exponent digits as
4517 the native printf implementation. */
4518 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4524 else if (dp->conversion == 'g' || dp->conversion == 'G')
4527 if (flags & FLAG_ALT)
4530 (precision > 0 ? precision - 1 : 0);
4531 *p++ = decimal_point_char ();
4532 for (; ndigits > 0; --ndigits)
4544 /* The generated string now extends from tmp to p, with the
4545 zero padding insertion point being at pad_ptr. */
4546 if (has_width && p - tmp < width)
4548 size_t pad = width - (p - tmp);
4549 DCHAR_T *end = p + pad;
4551 if (flags & FLAG_LEFT)
4553 /* Pad with spaces on the right. */
4554 for (; pad > 0; pad--)
4557 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4559 /* Pad with zeroes. */
4564 for (; pad > 0; pad--)
4569 /* Pad with spaces on the left. */
4574 for (; pad > 0; pad--)
4582 size_t count = p - tmp;
4584 if (count >= tmp_length)
4585 /* tmp_length was incorrectly calculated - fix the
4589 /* Make room for the result. */
4590 if (count >= allocated - length)
4592 size_t n = xsum (length, count);
4594 ENSURE_ALLOCATION (n);
4597 /* Append the result. */
4598 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4607 arg_type type = a.arg[dp->arg_index].type;
4608 int flags = dp->flags;
4609 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4613 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4617 #if NEED_PRINTF_UNBOUNDED_PRECISION
4620 # define prec_ourselves 0
4622 #if NEED_PRINTF_FLAG_LEFTADJUST
4623 # define pad_ourselves 1
4624 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4627 # define pad_ourselves 0
4630 unsigned int prefix_count;
4631 int prefixes[2] IF_LINT (= { 0 });
4635 TCHAR_T tmpbuf[700];
4639 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4642 if (dp->width_start != dp->width_end)
4644 if (dp->width_arg_index != ARG_NONE)
4648 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4650 arg = a.arg[dp->width_arg_index].a.a_int;
4653 /* "A negative field width is taken as a '-' flag
4654 followed by a positive field width." */
4656 width = (unsigned int) (-arg);
4663 const FCHAR_T *digitp = dp->width_start;
4666 width = xsum (xtimes (width, 10), *digitp++ - '0');
4667 while (digitp != dp->width_end);
4673 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4676 if (dp->precision_start != dp->precision_end)
4678 if (dp->precision_arg_index != ARG_NONE)
4682 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4684 arg = a.arg[dp->precision_arg_index].a.a_int;
4685 /* "A negative precision is taken as if the precision
4695 const FCHAR_T *digitp = dp->precision_start + 1;
4698 while (digitp != dp->precision_end)
4699 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4705 /* Decide whether to handle the precision ourselves. */
4706 #if NEED_PRINTF_UNBOUNDED_PRECISION
4707 switch (dp->conversion)
4709 case 'd': case 'i': case 'u':
4711 case 'x': case 'X': case 'p':
4712 prec_ourselves = has_precision && (precision > 0);
4720 /* Decide whether to perform the padding ourselves. */
4721 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4722 switch (dp->conversion)
4724 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4725 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4726 to perform the padding after this conversion. Functions
4727 with unistdio extensions perform the padding based on
4728 character count rather than element count. */
4731 # if NEED_PRINTF_FLAG_ZERO
4732 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4738 pad_ourselves = prec_ourselves;
4744 /* Allocate a temporary buffer of sufficient size for calling
4747 MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
4748 flags, width, has_precision, precision,
4751 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4755 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4757 if (size_overflow_p (tmp_memsize))
4758 /* Overflow, would lead to out of memory. */
4760 tmp = (TCHAR_T *) malloc (tmp_memsize);
4762 /* Out of memory. */
4767 /* Construct the format string for calling snprintf or
4771 #if NEED_PRINTF_FLAG_GROUPING
4772 /* The underlying implementation doesn't support the ' flag.
4773 Produce no grouping characters in this case; this is
4774 acceptable because the grouping is locale dependent. */
4776 if (flags & FLAG_GROUP)
4779 if (flags & FLAG_LEFT)
4781 if (flags & FLAG_SHOWSIGN)
4783 if (flags & FLAG_SPACE)
4785 if (flags & FLAG_ALT)
4787 #if __GLIBC__ >= 2 && !defined __UCLIBC__
4788 if (flags & FLAG_LOCALIZED)
4793 if (flags & FLAG_ZERO)
4795 if (dp->width_start != dp->width_end)
4797 size_t n = dp->width_end - dp->width_start;
4798 /* The width specification is known to consist only
4799 of standard ASCII characters. */
4800 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4802 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4807 const FCHAR_T *mp = dp->width_start;
4809 *fbp++ = (unsigned char) *mp++;
4814 if (!prec_ourselves)
4816 if (dp->precision_start != dp->precision_end)
4818 size_t n = dp->precision_end - dp->precision_start;
4819 /* The precision specification is known to consist only
4820 of standard ASCII characters. */
4821 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4823 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4828 const FCHAR_T *mp = dp->precision_start;
4830 *fbp++ = (unsigned char) *mp++;
4838 #if HAVE_LONG_LONG_INT
4839 case TYPE_LONGLONGINT:
4840 case TYPE_ULONGLONGINT:
4841 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4854 case TYPE_WIDE_CHAR:
4857 case TYPE_WIDE_STRING:
4861 case TYPE_LONGDOUBLE:
4867 #if NEED_PRINTF_DIRECTIVE_F
4868 if (dp->conversion == 'F')
4872 *fbp = dp->conversion;
4874 # if !(((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) && !defined __UCLIBC__) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4879 /* On glibc2 systems from glibc >= 2.3 - probably also older
4880 ones - we know that snprintf's return value conforms to
4881 ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and
4882 gl_SNPRINTF_TRUNCATION_C99 pass.
4883 Therefore we can avoid using %n in this situation.
4884 On glibc2 systems from 2004-10-18 or newer, the use of %n
4885 in format strings in writable memory may crash the program
4886 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4887 in this situation. */
4888 /* On native Win32 systems (such as mingw), we can avoid using
4890 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4891 snprintf does not write more than the specified number
4892 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4893 '4', '5', '6' into buf, not '4', '5', '\0'.)
4894 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4895 allows us to recognize the case of an insufficient
4896 buffer size: it returns -1 in this case.
4897 On native Win32 systems (such as mingw) where the OS is
4898 Windows Vista, the use of %n in format strings by default
4899 crashes the program. See
4900 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4901 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4902 So we should avoid %n in this situation. */
4909 /* Construct the arguments for calling snprintf or sprintf. */
4911 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4913 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4915 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4917 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4919 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4921 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4925 /* The SNPRINTF result is appended after result[0..length].
4926 The latter is an array of DCHAR_T; SNPRINTF appends an
4927 array of TCHAR_T to it. This is possible because
4928 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4929 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4930 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4931 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4932 where an snprintf() with maxlen==1 acts like sprintf(). */
4933 ENSURE_ALLOCATION (xsum (length,
4934 (2 + TCHARS_PER_DCHAR - 1)
4935 / TCHARS_PER_DCHAR));
4936 /* Prepare checking whether snprintf returns the count
4938 *(TCHAR_T *) (result + length) = '\0';
4949 size_t maxlen = allocated - length;
4950 /* SNPRINTF can fail if its second argument is
4952 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4953 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4954 maxlen = maxlen * TCHARS_PER_DCHAR;
4955 # define SNPRINTF_BUF(arg) \
4956 switch (prefix_count) \
4959 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4964 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4966 prefixes[0], arg, &count); \
4969 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4971 prefixes[0], prefixes[1], arg, \
4978 # define SNPRINTF_BUF(arg) \
4979 switch (prefix_count) \
4982 count = sprintf (tmp, buf, arg); \
4985 count = sprintf (tmp, buf, prefixes[0], arg); \
4988 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
5001 int arg = a.arg[dp->arg_index].a.a_schar;
5007 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
5013 int arg = a.arg[dp->arg_index].a.a_short;
5019 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
5025 int arg = a.arg[dp->arg_index].a.a_int;
5031 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
5037 long int arg = a.arg[dp->arg_index].a.a_longint;
5043 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
5047 #if HAVE_LONG_LONG_INT
5048 case TYPE_LONGLONGINT:
5050 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
5054 case TYPE_ULONGLONGINT:
5056 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
5063 double arg = a.arg[dp->arg_index].a.a_double;
5067 case TYPE_LONGDOUBLE:
5069 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5075 int arg = a.arg[dp->arg_index].a.a_char;
5080 case TYPE_WIDE_CHAR:
5082 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5089 const char *arg = a.arg[dp->arg_index].a.a_string;
5094 case TYPE_WIDE_STRING:
5096 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5103 void *arg = a.arg[dp->arg_index].a.a_pointer;
5112 /* Portability: Not all implementations of snprintf()
5113 are ISO C 99 compliant. Determine the number of
5114 bytes that snprintf() has produced or would have
5118 /* Verify that snprintf() has NUL-terminated its
5121 && ((TCHAR_T *) (result + length)) [count] != '\0')
5123 /* Portability hack. */
5124 if (retcount > count)
5129 /* snprintf() doesn't understand the '%n'
5133 /* Don't use the '%n' directive; instead, look
5134 at the snprintf() return value. */
5140 /* Look at the snprintf() return value. */
5143 # if !HAVE_SNPRINTF_RETVAL_C99
5144 /* HP-UX 10.20 snprintf() is doubly deficient:
5145 It doesn't understand the '%n' directive,
5146 *and* it returns -1 (rather than the length
5147 that would have been required) when the
5148 buffer is too small.
5149 But a failure at this point can also come
5150 from other reasons than a too small buffer,
5151 such as an invalid wide string argument to
5152 the %ls directive, or possibly an invalid
5153 floating-point argument. */
5155 MAX_ROOM_NEEDED (&a, dp->arg_index,
5156 dp->conversion, type, flags,
5157 width, has_precision,
5158 precision, pad_ourselves);
5160 if (maxlen < tmp_length)
5162 /* Make more room. But try to do through
5163 this reallocation only once. */
5164 size_t bigger_need =
5167 TCHARS_PER_DCHAR - 1)
5168 / TCHARS_PER_DCHAR);
5169 /* And always grow proportionally.
5170 (There may be several arguments, each
5171 needing a little more room than the
5173 size_t bigger_need2 =
5174 xsum (xtimes (allocated, 2), 12);
5175 if (bigger_need < bigger_need2)
5176 bigger_need = bigger_need2;
5177 ENSURE_ALLOCATION (bigger_need);
5188 /* Attempt to handle failure. */
5191 /* SNPRINTF or sprintf failed. Save and use the errno
5192 that it has set, if any. */
5193 int saved_errno = errno;
5195 if (!(result == resultbuf || result == NULL))
5197 if (buf_malloced != NULL)
5198 free (buf_malloced);
5203 : (dp->conversion == 'c' || dp->conversion == 's'
5210 /* Handle overflow of the allocated buffer.
5211 If such an overflow occurs, a C99 compliant snprintf()
5212 returns a count >= maxlen. However, a non-compliant
5213 snprintf() function returns only count = maxlen - 1. To
5214 cover both cases, test whether count >= maxlen - 1. */
5215 if ((unsigned int) count + 1 >= maxlen)
5217 /* If maxlen already has attained its allowed maximum,
5218 allocating more memory will not increase maxlen.
5219 Instead of looping, bail out. */
5220 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5224 /* Need at least (count + 1) * sizeof (TCHAR_T)
5225 bytes. (The +1 is for the trailing NUL.)
5226 But ask for (count + 2) * sizeof (TCHAR_T)
5227 bytes, so that in the next round, we likely get
5228 maxlen > (unsigned int) count + 1
5229 and so we don't get here again.
5230 And allocate proportionally, to avoid looping
5231 eternally if snprintf() reports a too small
5235 ((unsigned int) count + 2
5236 + TCHARS_PER_DCHAR - 1)
5237 / TCHARS_PER_DCHAR),
5238 xtimes (allocated, 2));
5240 ENSURE_ALLOCATION (n);
5246 #if NEED_PRINTF_UNBOUNDED_PRECISION
5249 /* Handle the precision. */
5252 (TCHAR_T *) (result + length);
5256 size_t prefix_count;
5260 /* Put the additional zeroes after the sign. */
5262 && (*prec_ptr == '-' || *prec_ptr == '+'
5263 || *prec_ptr == ' '))
5265 /* Put the additional zeroes after the 0x prefix if
5266 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5268 && prec_ptr[0] == '0'
5269 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5272 move = count - prefix_count;
5273 if (precision > move)
5275 /* Insert zeroes. */
5276 size_t insert = precision - move;
5282 (count + insert + TCHARS_PER_DCHAR - 1)
5283 / TCHARS_PER_DCHAR);
5284 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5285 ENSURE_ALLOCATION (n);
5286 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5287 prec_ptr = (TCHAR_T *) (result + length);
5290 prec_end = prec_ptr + count;
5291 prec_ptr += prefix_count;
5293 while (prec_end > prec_ptr)
5296 prec_end[insert] = prec_end[0];
5302 while (prec_end > prec_ptr);
5310 if (count >= tmp_length)
5311 /* tmp_length was incorrectly calculated - fix the
5317 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5318 if (dp->conversion == 'c' || dp->conversion == 's')
5320 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5322 The result string is not certainly ASCII. */
5323 const TCHAR_T *tmpsrc;
5326 /* This code assumes that TCHAR_T is 'char'. */
5327 verify (sizeof (TCHAR_T) == 1);
5329 tmpsrc = (TCHAR_T *) (result + length);
5334 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5335 iconveh_question_mark,
5341 int saved_errno = errno;
5342 if (!(result == resultbuf || result == NULL))
5344 if (buf_malloced != NULL)
5345 free (buf_malloced);
5347 errno = saved_errno;
5350 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5351 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5357 /* The result string is ASCII.
5358 Simple 1:1 conversion. */
5360 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5361 no-op conversion, in-place on the array starting
5362 at (result + length). */
5363 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5366 const TCHAR_T *tmpsrc;
5371 if (result == resultbuf)
5373 tmpsrc = (TCHAR_T *) (result + length);
5374 /* ENSURE_ALLOCATION will not move tmpsrc
5375 (because it's part of resultbuf). */
5376 ENSURE_ALLOCATION (xsum (length, count));
5380 /* ENSURE_ALLOCATION will move the array
5381 (because it uses realloc(). */
5382 ENSURE_ALLOCATION (xsum (length, count));
5383 tmpsrc = (TCHAR_T *) (result + length);
5387 ENSURE_ALLOCATION (xsum (length, count));
5389 tmpdst = result + length;
5390 /* Copy backwards, because of overlapping. */
5393 for (n = count; n > 0; n--)
5394 *--tmpdst = (unsigned char) *--tmpsrc;
5399 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5400 /* Make room for the result. */
5401 if (count > allocated - length)
5403 /* Need at least count elements. But allocate
5406 xmax (xsum (length, count), xtimes (allocated, 2));
5408 ENSURE_ALLOCATION (n);
5412 /* Here count <= allocated - length. */
5414 /* Perform padding. */
5415 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5416 if (pad_ourselves && has_width)
5419 # if ENABLE_UNISTDIO
5420 /* Outside POSIX, it's preferrable to compare the width
5421 against the number of _characters_ of the converted
5423 w = DCHAR_MBSNLEN (result + length, count);
5425 /* The width is compared against the number of _bytes_
5426 of the converted value, says POSIX. */
5431 size_t pad = width - w;
5433 /* Make room for the result. */
5434 if (xsum (count, pad) > allocated - length)
5436 /* Need at least count + pad elements. But
5437 allocate proportionally. */
5439 xmax (xsum3 (length, count, pad),
5440 xtimes (allocated, 2));
5444 ENSURE_ALLOCATION (n);
5447 ENSURE_ALLOCATION (n);
5450 /* Here count + pad <= allocated - length. */
5453 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5454 DCHAR_T * const rp = result + length;
5456 DCHAR_T * const rp = tmp;
5458 DCHAR_T *p = rp + count;
5459 DCHAR_T *end = p + pad;
5461 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5462 if (dp->conversion == 'c'
5463 || dp->conversion == 's')
5464 /* No zero-padding for string directives. */
5469 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5470 /* No zero-padding of "inf" and "nan". */
5471 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5472 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5475 /* The generated string now extends from rp to p,
5476 with the zero padding insertion point being at
5479 count = count + pad; /* = end - rp */
5481 if (flags & FLAG_LEFT)
5483 /* Pad with spaces on the right. */
5484 for (; pad > 0; pad--)
5487 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5489 /* Pad with zeroes. */
5494 for (; pad > 0; pad--)
5499 /* Pad with spaces on the left. */
5504 for (; pad > 0; pad--)
5512 /* Here still count <= allocated - length. */
5514 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5515 /* The snprintf() result did fit. */
5517 /* Append the sprintf() result. */
5518 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5525 #if NEED_PRINTF_DIRECTIVE_F
5526 if (dp->conversion == 'F')
5528 /* Convert the %f result to upper case for %F. */
5529 DCHAR_T *rp = result + length;
5531 for (rc = count; rc > 0; rc--, rp++)
5532 if (*rp >= 'a' && *rp <= 'z')
5533 *rp = *rp - 'a' + 'A';
5541 #undef pad_ourselves
5542 #undef prec_ourselves
5547 /* Add the final NUL. */
5548 ENSURE_ALLOCATION (xsum (length, 1));
5549 result[length] = '\0';
5551 if (result != resultbuf && length + 1 < allocated)
5553 /* Shrink the allocated memory if possible. */
5556 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5561 if (buf_malloced != NULL)
5562 free (buf_malloced);
5565 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5566 says that snprintf() fails with errno = EOVERFLOW in this case, but
5567 that's only because snprintf() returns an 'int'. This function does
5568 not have this limitation. */
5573 if (!(result == resultbuf || result == NULL))
5575 if (buf_malloced != NULL)
5576 free (buf_malloced);
5583 if (!(result == resultbuf || result == NULL))
5585 if (buf_malloced != NULL)
5586 free (buf_malloced);
5594 #undef MAX_ROOM_NEEDED
5595 #undef TCHARS_PER_DCHAR
5603 #undef DCHAR_IS_TCHAR