1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2010 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* This file can be parametrized with the following macros:
19 VASNPRINTF The name of the function being defined.
20 FCHAR_T The element type of the format string.
21 DCHAR_T The element type of the destination (result) string.
22 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
23 in the format string are ASCII. MUST be set if
24 FCHAR_T and DCHAR_T are not the same type.
25 DIRECTIVE Structure denoting a format directive.
27 DIRECTIVES Structure denoting the set of format directives of a
28 format string. Depends on FCHAR_T.
29 PRINTF_PARSE Function that parses a format string.
31 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
32 DCHAR_SET memset like function for DCHAR_T[] arrays.
33 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
34 SNPRINTF The system's snprintf (or similar) function.
35 This may be either snprintf or swprintf.
36 TCHAR_T The element type of the argument and result string
37 of the said SNPRINTF function. This may be either
38 char or wchar_t. The code exploits that
39 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
40 alignof (TCHAR_T) <= alignof (DCHAR_T).
41 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
42 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
43 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
44 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
45 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
47 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
48 This must come before <config.h> because <config.h> may include
49 <features.h>, and once <features.h> has been included, it's too late. */
51 # define _GNU_SOURCE 1
63 # if WIDE_CHAR_VERSION
64 # include "vasnwprintf.h"
66 # include "vasnprintf.h"
70 #include <locale.h> /* localeconv() */
71 #include <stdio.h> /* snprintf(), sprintf() */
72 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
73 #include <string.h> /* memcpy(), strlen() */
74 #include <errno.h> /* errno */
75 #include <limits.h> /* CHAR_BIT */
76 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
78 # include <langinfo.h>
81 # if WIDE_CHAR_VERSION
82 # include "wprintf-parse.h"
84 # include "printf-parse.h"
88 /* Checked size_t computations. */
91 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
96 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
98 # include "isnand-nolibm.h"
101 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
103 # include "isnanl-nolibm.h"
107 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
109 # include "isnand-nolibm.h"
110 # include "printf-frexp.h"
113 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
115 # include "isnanl-nolibm.h"
116 # include "printf-frexpl.h"
120 /* Default parameters. */
122 # if WIDE_CHAR_VERSION
123 # define VASNPRINTF vasnwprintf
124 # define FCHAR_T wchar_t
125 # define DCHAR_T wchar_t
126 # define TCHAR_T wchar_t
127 # define DCHAR_IS_TCHAR 1
128 # define DIRECTIVE wchar_t_directive
129 # define DIRECTIVES wchar_t_directives
130 # define PRINTF_PARSE wprintf_parse
131 # define DCHAR_CPY wmemcpy
132 # define DCHAR_SET wmemset
134 # define VASNPRINTF vasnprintf
135 # define FCHAR_T char
136 # define DCHAR_T char
137 # define TCHAR_T char
138 # define DCHAR_IS_TCHAR 1
139 # define DIRECTIVE char_directive
140 # define DIRECTIVES char_directives
141 # define PRINTF_PARSE printf_parse
142 # define DCHAR_CPY memcpy
143 # define DCHAR_SET memset
146 #if WIDE_CHAR_VERSION
147 /* TCHAR_T is wchar_t. */
148 # define USE_SNPRINTF 1
149 # if HAVE_DECL__SNWPRINTF
150 /* On Windows, the function swprintf() has a different signature than
151 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
152 instead. The mingw function snwprintf() has fewer bugs than the
153 MSVCRT function _snwprintf(), so prefer that. */
154 # if defined __MINGW32__
155 # define SNPRINTF snwprintf
157 # define SNPRINTF _snwprintf
161 # define SNPRINTF swprintf
164 /* TCHAR_T is char. */
165 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
166 But don't use it on BeOS, since BeOS snprintf produces no output if the
167 size argument is >= 0x3000000.
168 Also don't use it on Linux libc5, since there snprintf with size = 1
169 writes any output without bounds, like sprintf. */
170 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
171 # define USE_SNPRINTF 1
173 # define USE_SNPRINTF 0
175 # if HAVE_DECL__SNPRINTF
176 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
177 function _snprintf(), so prefer that. */
178 # if defined __MINGW32__
179 # define SNPRINTF snprintf
180 /* Here we need to call the native snprintf, not rpl_snprintf. */
183 # define SNPRINTF _snprintf
187 # define SNPRINTF snprintf
188 /* Here we need to call the native snprintf, not rpl_snprintf. */
192 /* Here we need to call the native sprintf, not rpl_sprintf. */
195 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
196 warnings in this file. Use -Dlint to suppress them. */
198 # define IF_LINT(Code) Code
200 # define IF_LINT(Code) /* empty */
203 /* Avoid some warnings from "gcc -Wshadow".
204 This file doesn't use the exp() and remainder() functions. */
208 #define remainder rem
210 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && !WIDE_CHAR_VERSION
211 # if (HAVE_STRNLEN && !defined _AIX)
212 # define local_strnlen strnlen
214 # ifndef local_strnlen_defined
215 # define local_strnlen_defined 1
217 local_strnlen (const char *string, size_t maxlen)
219 const char *end = memchr (string, '\0', maxlen);
220 return end ? (size_t) (end - string) : maxlen;
226 #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
228 # define local_wcslen wcslen
230 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
231 a dependency towards this library, here is a local substitute.
232 Define this substitute only once, even if this file is included
233 twice in the same compilation unit. */
234 # ifndef local_wcslen_defined
235 # define local_wcslen_defined 1
237 local_wcslen (const wchar_t *s)
241 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
249 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
251 # define local_wcsnlen wcsnlen
253 # ifndef local_wcsnlen_defined
254 # define local_wcsnlen_defined 1
256 local_wcsnlen (const wchar_t *s, size_t maxlen)
260 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
268 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
269 /* Determine the decimal-point character according to the current locale. */
270 # ifndef decimal_point_char_defined
271 # define decimal_point_char_defined 1
273 decimal_point_char (void)
276 /* Determine it in a multithread-safe way. We know nl_langinfo is
277 multithread-safe on glibc systems and MacOS X systems, but is not required
278 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
279 localeconv() is rarely multithread-safe. */
280 # if HAVE_NL_LANGINFO && (__GLIBC__ || (defined __APPLE__ && defined __MACH__))
281 point = nl_langinfo (RADIXCHAR);
284 sprintf (pointbuf, "%#.0f", 1.0);
285 point = &pointbuf[1];
287 point = localeconv () -> decimal_point;
289 /* The decimal point is always a single byte: either '.' or ','. */
290 return (point[0] != '\0' ? point[0] : '.');
295 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
297 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
299 is_infinite_or_zero (double x)
301 return isnand (x) || x + x == x;
306 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
308 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
310 is_infinite_or_zerol (long double x)
312 return isnanl (x) || x + x == x;
317 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
319 /* Converting 'long double' to decimal without rare rounding bugs requires
320 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
321 (and slower) algorithms. */
323 typedef unsigned int mp_limb_t;
324 # define GMP_LIMB_BITS 32
325 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
327 typedef unsigned long long mp_twolimb_t;
328 # define GMP_TWOLIMB_BITS 64
329 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
331 /* Representation of a bignum >= 0. */
335 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
338 /* Compute the product of two bignums >= 0.
339 Return the allocated memory in case of success, NULL in case of memory
340 allocation failure. */
342 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
349 if (src1.nlimbs <= src2.nlimbs)
363 /* Now 0 <= len1 <= len2. */
366 /* src1 or src2 is zero. */
368 dest->limbs = (mp_limb_t *) malloc (1);
372 /* Here 1 <= len1 <= len2. */
378 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
381 for (k = len2; k > 0; )
383 for (i = 0; i < len1; i++)
385 mp_limb_t digit1 = p1[i];
386 mp_twolimb_t carry = 0;
387 for (j = 0; j < len2; j++)
389 mp_limb_t digit2 = p2[j];
390 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
392 dp[i + j] = (mp_limb_t) carry;
393 carry = carry >> GMP_LIMB_BITS;
395 dp[i + len2] = (mp_limb_t) carry;
398 while (dlen > 0 && dp[dlen - 1] == 0)
406 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
407 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
409 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
411 Return the allocated memory in case of success, NULL in case of memory
412 allocation failure. */
414 divide (mpn_t a, mpn_t b, mpn_t *q)
417 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
418 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
419 If m<n, then q:=0 and r:=a.
420 If m>=n=1, perform a single-precision division:
423 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
424 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
425 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
426 Normalise [q[m-1],...,q[0]], yields q.
427 If m>=n>1, perform a multiple-precision division:
428 We have a/b < beta^(m-n+1).
429 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
430 Shift a and b left by s bits, copying them. r:=a.
431 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
432 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
434 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
435 In case of overflow (q* >= beta) set q* := beta-1.
436 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
437 and c3 := b[n-2] * q*.
438 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
439 occurred. Furthermore 0 <= c3 < beta^2.
440 If there was overflow and
441 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
442 the next test can be skipped.}
443 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
444 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
446 Put r := r - b * q* * beta^j. In detail:
447 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
448 hence: u:=0, for i:=0 to n-1 do
450 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
451 u:=u div beta (+ 1, if carry in subtraction)
453 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
455 the carry u does not overflow.}
456 If a negative carry occurs, put q* := q* - 1
457 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
459 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
460 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
462 The room for q[j] can be allocated at the memory location of r[n+j].
463 Finally, round-to-even:
464 Shift r left by 1 bit.
465 If r > b or if r = b and q[0] is odd, q := q+1.
467 const mp_limb_t *a_ptr = a.limbs;
468 size_t a_len = a.nlimbs;
469 const mp_limb_t *b_ptr = b.limbs;
470 size_t b_len = b.nlimbs;
472 mp_limb_t *tmp_roomptr = NULL;
478 /* Allocate room for a_len+2 digits.
479 (Need a_len+1 digits for the real division and 1 more digit for the
480 final rounding of q.) */
481 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
486 while (a_len > 0 && a_ptr[a_len - 1] == 0)
493 /* Division by zero. */
495 if (b_ptr[b_len - 1] == 0)
501 /* Here m = a_len >= 0 and n = b_len > 0. */
505 /* m<n: trivial case. q=0, r := copy of a. */
508 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
509 q_ptr = roomptr + a_len;
514 /* n=1: single precision division.
515 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
519 mp_limb_t den = b_ptr[0];
520 mp_limb_t remainder = 0;
521 const mp_limb_t *sourceptr = a_ptr + a_len;
522 mp_limb_t *destptr = q_ptr + a_len;
524 for (count = a_len; count > 0; count--)
527 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
528 *--destptr = num / den;
529 remainder = num % den;
531 /* Normalise and store r. */
534 r_ptr[0] = remainder;
541 if (q_ptr[q_len - 1] == 0)
547 /* n>1: multiple precision division.
548 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
549 beta^(m-n-1) <= a/b < beta^(m-n+1). */
553 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
581 /* 0 <= s < GMP_LIMB_BITS.
582 Copy b, shifting it left by s bits. */
585 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
586 if (tmp_roomptr == NULL)
592 const mp_limb_t *sourceptr = b_ptr;
593 mp_limb_t *destptr = tmp_roomptr;
594 mp_twolimb_t accu = 0;
596 for (count = b_len; count > 0; count--)
598 accu += (mp_twolimb_t) *sourceptr++ << s;
599 *destptr++ = (mp_limb_t) accu;
600 accu = accu >> GMP_LIMB_BITS;
602 /* accu must be zero, since that was how s was determined. */
608 /* Copy a, shifting it left by s bits, yields r.
610 At the beginning: r = roomptr[0..a_len],
611 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
615 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
620 const mp_limb_t *sourceptr = a_ptr;
621 mp_limb_t *destptr = r_ptr;
622 mp_twolimb_t accu = 0;
624 for (count = a_len; count > 0; count--)
626 accu += (mp_twolimb_t) *sourceptr++ << s;
627 *destptr++ = (mp_limb_t) accu;
628 accu = accu >> GMP_LIMB_BITS;
630 *destptr++ = (mp_limb_t) accu;
632 q_ptr = roomptr + b_len;
633 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
635 size_t j = a_len - b_len; /* m-n */
636 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
637 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
638 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
639 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
640 /* Division loop, traversed m-n+1 times.
641 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
646 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
648 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
650 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
651 | r_ptr[j + b_len - 1];
652 q_star = num / b_msd;
657 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
658 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
659 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
660 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
661 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
663 If yes, jump directly to the subtraction loop.
664 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
665 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
666 if (r_ptr[j + b_len] > b_msd
667 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
668 /* r[j+n] >= b[n-1]+1 or
669 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
674 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
676 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
677 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
678 mp_twolimb_t c3 = /* b[n-2] * q* */
679 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
680 /* While c2 < c3, increase c2 and decrease c3.
681 Consider c3-c2. While it is > 0, decrease it by
682 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
683 this can happen only twice. */
686 q_star = q_star - 1; /* q* := q* - 1 */
687 if (c3 - c2 > b_msdd)
688 q_star = q_star - 1; /* q* := q* - 1 */
694 /* Subtract r := r - b * q* * beta^j. */
697 const mp_limb_t *sourceptr = b_ptr;
698 mp_limb_t *destptr = r_ptr + j;
699 mp_twolimb_t carry = 0;
701 for (count = b_len; count > 0; count--)
703 /* Here 0 <= carry <= q*. */
706 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
707 + (mp_limb_t) ~(*destptr);
708 /* Here 0 <= carry <= beta*q* + beta-1. */
709 *destptr++ = ~(mp_limb_t) carry;
710 carry = carry >> GMP_LIMB_BITS; /* <= q* */
712 cr = (mp_limb_t) carry;
714 /* Subtract cr from r_ptr[j + b_len], then forget about
716 if (cr > r_ptr[j + b_len])
718 /* Subtraction gave a carry. */
719 q_star = q_star - 1; /* q* := q* - 1 */
722 const mp_limb_t *sourceptr = b_ptr;
723 mp_limb_t *destptr = r_ptr + j;
726 for (count = b_len; count > 0; count--)
728 mp_limb_t source1 = *sourceptr++;
729 mp_limb_t source2 = *destptr;
730 *destptr++ = source1 + source2 + carry;
733 ? source1 >= (mp_limb_t) ~source2
734 : source1 > (mp_limb_t) ~source2);
737 /* Forget about the carry and about r[j+n]. */
740 /* q* is determined. Store it as q[j]. */
749 if (q_ptr[q_len - 1] == 0)
751 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
752 b is shifted left by s bits. */
753 /* Shift r right by s bits. */
756 mp_limb_t ptr = r_ptr + r_len;
757 mp_twolimb_t accu = 0;
759 for (count = r_len; count > 0; count--)
761 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
762 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
763 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
768 while (r_len > 0 && r_ptr[r_len - 1] == 0)
771 /* Compare r << 1 with b. */
779 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
780 | (i < r_len ? r_ptr[i] << 1 : 0);
781 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
791 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
796 for (i = 0; i < q_len; i++)
797 if (++(q_ptr[i]) != 0)
802 if (tmp_roomptr != NULL)
809 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
811 Destroys the contents of a.
812 Return the allocated memory - containing the decimal digits in low-to-high
813 order, terminated with a NUL character - in case of success, NULL in case
814 of memory allocation failure. */
816 convert_to_decimal (mpn_t a, size_t extra_zeroes)
818 mp_limb_t *a_ptr = a.limbs;
819 size_t a_len = a.nlimbs;
820 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
821 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
822 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
826 for (; extra_zeroes > 0; extra_zeroes--)
830 /* Divide a by 10^9, in-place. */
831 mp_limb_t remainder = 0;
832 mp_limb_t *ptr = a_ptr + a_len;
834 for (count = a_len; count > 0; count--)
837 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
838 *ptr = num / 1000000000;
839 remainder = num % 1000000000;
841 /* Store the remainder as 9 decimal digits. */
842 for (count = 9; count > 0; count--)
844 *d_ptr++ = '0' + (remainder % 10);
845 remainder = remainder / 10;
848 if (a_ptr[a_len - 1] == 0)
851 /* Remove leading zeroes. */
852 while (d_ptr > c_ptr && d_ptr[-1] == '0')
854 /* But keep at least one zero. */
857 /* Terminate the string. */
863 # if NEED_PRINTF_LONG_DOUBLE
865 /* Assuming x is finite and >= 0:
866 write x as x = 2^e * m, where m is a bignum.
867 Return the allocated memory in case of success, NULL in case of memory
868 allocation failure. */
870 decode_long_double (long double x, int *ep, mpn_t *mp)
877 /* Allocate memory for result. */
878 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
879 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
882 /* Split into exponential part and mantissa. */
883 y = frexpl (x, &exp);
884 if (!(y >= 0.0L && y < 1.0L))
886 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
887 latter is an integer. */
888 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
889 I'm not sure whether it's safe to cast a 'long double' value between
890 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
891 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
893 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
894 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
897 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
900 if (!(y >= 0.0L && y < 1.0L))
902 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
905 if (!(y >= 0.0L && y < 1.0L))
907 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
912 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
915 if (!(y >= 0.0L && y < 1.0L))
917 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
921 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
924 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
927 if (!(y >= 0.0L && y < 1.0L))
929 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
932 if (!(y >= 0.0L && y < 1.0L))
934 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
936 #if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
942 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
945 *ep = exp - LDBL_MANT_BIT;
951 # if NEED_PRINTF_DOUBLE
953 /* Assuming x is finite and >= 0:
954 write x as x = 2^e * m, where m is a bignum.
955 Return the allocated memory in case of success, NULL in case of memory
956 allocation failure. */
958 decode_double (double x, int *ep, mpn_t *mp)
965 /* Allocate memory for result. */
966 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
967 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
970 /* Split into exponential part and mantissa. */
972 if (!(y >= 0.0 && y < 1.0))
974 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
975 latter is an integer. */
976 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
977 I'm not sure whether it's safe to cast a 'double' value between
978 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
979 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
981 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
982 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
985 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
988 if (!(y >= 0.0 && y < 1.0))
990 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
993 if (!(y >= 0.0 && y < 1.0))
995 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1000 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
1003 if (!(y >= 0.0 && y < 1.0))
1005 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
1009 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1012 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1015 if (!(y >= 0.0 && y < 1.0))
1017 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1020 if (!(y >= 0.0 && y < 1.0))
1022 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1027 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1030 *ep = exp - DBL_MANT_BIT;
1036 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1037 Returns the decimal representation of round (x * 10^n).
1038 Return the allocated memory - containing the decimal digits in low-to-high
1039 order, terminated with a NUL character - in case of success, NULL in case
1040 of memory allocation failure. */
1042 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1045 size_t extra_zeroes;
1048 mp_limb_t *pow5_ptr;
1050 unsigned int s_limbs;
1051 unsigned int s_bits;
1059 /* x = 2^e * m, hence
1060 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1061 = round (2^s * 5^n * m). */
1064 /* Factor out a common power of 10 if possible. */
1067 extra_zeroes = (s < n ? s : n);
1071 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1072 Before converting to decimal, we need to compute
1073 z = round (2^s * 5^n * m). */
1074 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1075 sign. 2.322 is slightly larger than log(5)/log(2). */
1076 abs_n = (n >= 0 ? n : -n);
1077 abs_s = (s >= 0 ? s : -s);
1078 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1079 + abs_s / GMP_LIMB_BITS + 1)
1080 * sizeof (mp_limb_t));
1081 if (pow5_ptr == NULL)
1086 /* Initialize with 1. */
1089 /* Multiply with 5^|n|. */
1092 static mp_limb_t const small_pow5[13 + 1] =
1094 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1095 48828125, 244140625, 1220703125
1098 for (n13 = 0; n13 <= abs_n; n13 += 13)
1100 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1102 mp_twolimb_t carry = 0;
1103 for (j = 0; j < pow5_len; j++)
1105 mp_limb_t digit2 = pow5_ptr[j];
1106 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1107 pow5_ptr[j] = (mp_limb_t) carry;
1108 carry = carry >> GMP_LIMB_BITS;
1111 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1114 s_limbs = abs_s / GMP_LIMB_BITS;
1115 s_bits = abs_s % GMP_LIMB_BITS;
1116 if (n >= 0 ? s >= 0 : s <= 0)
1118 /* Multiply with 2^|s|. */
1121 mp_limb_t *ptr = pow5_ptr;
1122 mp_twolimb_t accu = 0;
1124 for (count = pow5_len; count > 0; count--)
1126 accu += (mp_twolimb_t) *ptr << s_bits;
1127 *ptr++ = (mp_limb_t) accu;
1128 accu = accu >> GMP_LIMB_BITS;
1132 *ptr = (mp_limb_t) accu;
1139 for (count = pow5_len; count > 0;)
1142 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1144 for (count = s_limbs; count > 0;)
1147 pow5_ptr[count] = 0;
1149 pow5_len += s_limbs;
1151 pow5.limbs = pow5_ptr;
1152 pow5.nlimbs = pow5_len;
1155 /* Multiply m with pow5. No division needed. */
1156 z_memory = multiply (m, pow5, &z);
1160 /* Divide m by pow5 and round. */
1161 z_memory = divide (m, pow5, &z);
1166 pow5.limbs = pow5_ptr;
1167 pow5.nlimbs = pow5_len;
1171 Multiply m with pow5, then divide by 2^|s|. */
1175 tmp_memory = multiply (m, pow5, &numerator);
1176 if (tmp_memory == NULL)
1182 /* Construct 2^|s|. */
1184 mp_limb_t *ptr = pow5_ptr + pow5_len;
1186 for (i = 0; i < s_limbs; i++)
1188 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1189 denominator.limbs = ptr;
1190 denominator.nlimbs = s_limbs + 1;
1192 z_memory = divide (numerator, denominator, &z);
1198 Multiply m with 2^s, then divide by pow5. */
1201 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1202 * sizeof (mp_limb_t));
1203 if (num_ptr == NULL)
1210 mp_limb_t *destptr = num_ptr;
1213 for (i = 0; i < s_limbs; i++)
1218 const mp_limb_t *sourceptr = m.limbs;
1219 mp_twolimb_t accu = 0;
1221 for (count = m.nlimbs; count > 0; count--)
1223 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1224 *destptr++ = (mp_limb_t) accu;
1225 accu = accu >> GMP_LIMB_BITS;
1228 *destptr++ = (mp_limb_t) accu;
1232 const mp_limb_t *sourceptr = m.limbs;
1234 for (count = m.nlimbs; count > 0; count--)
1235 *destptr++ = *sourceptr++;
1237 numerator.limbs = num_ptr;
1238 numerator.nlimbs = destptr - num_ptr;
1240 z_memory = divide (numerator, pow5, &z);
1247 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1249 if (z_memory == NULL)
1251 digits = convert_to_decimal (z, extra_zeroes);
1256 # if NEED_PRINTF_LONG_DOUBLE
1258 /* Assuming x is finite and >= 0, and n is an integer:
1259 Returns the decimal representation of round (x * 10^n).
1260 Return the allocated memory - containing the decimal digits in low-to-high
1261 order, terminated with a NUL character - in case of success, NULL in case
1262 of memory allocation failure. */
1264 scale10_round_decimal_long_double (long double x, int n)
1268 void *memory = decode_long_double (x, &e, &m);
1269 return scale10_round_decimal_decoded (e, m, memory, n);
1274 # if NEED_PRINTF_DOUBLE
1276 /* Assuming x is finite and >= 0, and n is an integer:
1277 Returns the decimal representation of round (x * 10^n).
1278 Return the allocated memory - containing the decimal digits in low-to-high
1279 order, terminated with a NUL character - in case of success, NULL in case
1280 of memory allocation failure. */
1282 scale10_round_decimal_double (double x, int n)
1286 void *memory = decode_double (x, &e, &m);
1287 return scale10_round_decimal_decoded (e, m, memory, n);
1292 # if NEED_PRINTF_LONG_DOUBLE
1294 /* Assuming x is finite and > 0:
1295 Return an approximation for n with 10^n <= x < 10^(n+1).
1296 The approximation is usually the right n, but may be off by 1 sometimes. */
1298 floorlog10l (long double x)
1305 /* Split into exponential part and mantissa. */
1306 y = frexpl (x, &exp);
1307 if (!(y >= 0.0L && y < 1.0L))
1313 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1315 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1316 exp -= GMP_LIMB_BITS;
1318 if (y < (1.0L / (1 << 16)))
1320 y *= 1.0L * (1 << 16);
1323 if (y < (1.0L / (1 << 8)))
1325 y *= 1.0L * (1 << 8);
1328 if (y < (1.0L / (1 << 4)))
1330 y *= 1.0L * (1 << 4);
1333 if (y < (1.0L / (1 << 2)))
1335 y *= 1.0L * (1 << 2);
1338 if (y < (1.0L / (1 << 1)))
1340 y *= 1.0L * (1 << 1);
1344 if (!(y >= 0.5L && y < 1.0L))
1346 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1349 if (z < 0.70710678118654752444)
1351 z *= 1.4142135623730950488;
1354 if (z < 0.8408964152537145431)
1356 z *= 1.1892071150027210667;
1359 if (z < 0.91700404320467123175)
1361 z *= 1.0905077326652576592;
1364 if (z < 0.9576032806985736469)
1366 z *= 1.0442737824274138403;
1369 /* Now 0.95 <= z <= 1.01. */
1371 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1372 Four terms are enough to get an approximation with error < 10^-7. */
1373 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1374 /* Finally multiply with log(2)/log(10), yields an approximation for
1376 l *= 0.30102999566398119523;
1377 /* Round down to the next integer. */
1378 return (int) l + (l < 0 ? -1 : 0);
1383 # if NEED_PRINTF_DOUBLE
1385 /* Assuming x is finite and > 0:
1386 Return an approximation for n with 10^n <= x < 10^(n+1).
1387 The approximation is usually the right n, but may be off by 1 sometimes. */
1389 floorlog10 (double x)
1396 /* Split into exponential part and mantissa. */
1397 y = frexp (x, &exp);
1398 if (!(y >= 0.0 && y < 1.0))
1404 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1406 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1407 exp -= GMP_LIMB_BITS;
1409 if (y < (1.0 / (1 << 16)))
1411 y *= 1.0 * (1 << 16);
1414 if (y < (1.0 / (1 << 8)))
1416 y *= 1.0 * (1 << 8);
1419 if (y < (1.0 / (1 << 4)))
1421 y *= 1.0 * (1 << 4);
1424 if (y < (1.0 / (1 << 2)))
1426 y *= 1.0 * (1 << 2);
1429 if (y < (1.0 / (1 << 1)))
1431 y *= 1.0 * (1 << 1);
1435 if (!(y >= 0.5 && y < 1.0))
1437 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1440 if (z < 0.70710678118654752444)
1442 z *= 1.4142135623730950488;
1445 if (z < 0.8408964152537145431)
1447 z *= 1.1892071150027210667;
1450 if (z < 0.91700404320467123175)
1452 z *= 1.0905077326652576592;
1455 if (z < 0.9576032806985736469)
1457 z *= 1.0442737824274138403;
1460 /* Now 0.95 <= z <= 1.01. */
1462 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1463 Four terms are enough to get an approximation with error < 10^-7. */
1464 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1465 /* Finally multiply with log(2)/log(10), yields an approximation for
1467 l *= 0.30102999566398119523;
1468 /* Round down to the next integer. */
1469 return (int) l + (l < 0 ? -1 : 0);
1474 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1475 a single '1' digit. */
1477 is_borderline (const char *digits, size_t precision)
1479 for (; precision > 0; precision--, digits++)
1485 return *digits == '\0';
1490 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99
1492 /* Use a different function name, to make it possible that the 'wchar_t'
1493 parametrization and the 'char' parametrization get compiled in the same
1494 translation unit. */
1495 # if WIDE_CHAR_VERSION
1496 # define MAX_ROOM_NEEDED wmax_room_needed
1498 # define MAX_ROOM_NEEDED max_room_needed
1501 /* Returns the number of TCHAR_T units needed as temporary space for the result
1502 of sprintf or SNPRINTF of a single conversion directive. */
1503 static inline size_t
1504 MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
1505 arg_type type, int flags, size_t width, int has_precision,
1506 size_t precision, int pad_ourselves)
1512 case 'd': case 'i': case 'u':
1513 # if HAVE_LONG_LONG_INT
1514 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1516 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1517 * 0.30103 /* binary -> decimal */
1519 + 1; /* turn floor into ceil */
1522 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1524 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1525 * 0.30103 /* binary -> decimal */
1527 + 1; /* turn floor into ceil */
1530 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1531 * 0.30103 /* binary -> decimal */
1533 + 1; /* turn floor into ceil */
1534 if (tmp_length < precision)
1535 tmp_length = precision;
1536 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1537 tmp_length = xsum (tmp_length, tmp_length);
1538 /* Add 1, to account for a leading sign. */
1539 tmp_length = xsum (tmp_length, 1);
1543 # if HAVE_LONG_LONG_INT
1544 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1546 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1547 * 0.333334 /* binary -> octal */
1549 + 1; /* turn floor into ceil */
1552 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1554 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1555 * 0.333334 /* binary -> octal */
1557 + 1; /* turn floor into ceil */
1560 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1561 * 0.333334 /* binary -> octal */
1563 + 1; /* turn floor into ceil */
1564 if (tmp_length < precision)
1565 tmp_length = precision;
1566 /* Add 1, to account for a leading sign. */
1567 tmp_length = xsum (tmp_length, 1);
1571 # if HAVE_LONG_LONG_INT
1572 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1574 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1575 * 0.25 /* binary -> hexadecimal */
1577 + 1; /* turn floor into ceil */
1580 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1582 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1583 * 0.25 /* binary -> hexadecimal */
1585 + 1; /* turn floor into ceil */
1588 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1589 * 0.25 /* binary -> hexadecimal */
1591 + 1; /* turn floor into ceil */
1592 if (tmp_length < precision)
1593 tmp_length = precision;
1594 /* Add 2, to account for a leading sign or alternate form. */
1595 tmp_length = xsum (tmp_length, 2);
1599 if (type == TYPE_LONGDOUBLE)
1601 (unsigned int) (LDBL_MAX_EXP
1602 * 0.30103 /* binary -> decimal */
1603 * 2 /* estimate for FLAG_GROUP */
1605 + 1 /* turn floor into ceil */
1606 + 10; /* sign, decimal point etc. */
1609 (unsigned int) (DBL_MAX_EXP
1610 * 0.30103 /* binary -> decimal */
1611 * 2 /* estimate for FLAG_GROUP */
1613 + 1 /* turn floor into ceil */
1614 + 10; /* sign, decimal point etc. */
1615 tmp_length = xsum (tmp_length, precision);
1618 case 'e': case 'E': case 'g': case 'G':
1620 12; /* sign, decimal point, exponent etc. */
1621 tmp_length = xsum (tmp_length, precision);
1625 if (type == TYPE_LONGDOUBLE)
1627 (unsigned int) (LDBL_DIG
1628 * 0.831 /* decimal -> hexadecimal */
1630 + 1; /* turn floor into ceil */
1633 (unsigned int) (DBL_DIG
1634 * 0.831 /* decimal -> hexadecimal */
1636 + 1; /* turn floor into ceil */
1637 if (tmp_length < precision)
1638 tmp_length = precision;
1639 /* Account for sign, decimal point etc. */
1640 tmp_length = xsum (tmp_length, 12);
1644 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
1645 if (type == TYPE_WIDE_CHAR)
1646 tmp_length = MB_CUR_MAX;
1654 if (type == TYPE_WIDE_STRING)
1656 # if WIDE_CHAR_VERSION
1657 /* ISO C says about %ls in fwprintf:
1658 "If the precision is not specified or is greater than the size
1659 of the array, the array shall contain a null wide character."
1660 So if there is a precision, we must not use wcslen. */
1661 const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
1664 tmp_length = local_wcsnlen (arg, precision);
1666 tmp_length = local_wcslen (arg);
1668 /* ISO C says about %ls in fprintf:
1669 "If a precision is specified, no more than that many bytes are
1670 written (including shift sequences, if any), and the array
1671 shall contain a null wide character if, to equal the multibyte
1672 character sequence length given by the precision, the function
1673 would need to access a wide character one past the end of the
1675 So if there is a precision, we must not use wcslen. */
1676 /* This case has already been handled separately in VASNPRINTF. */
1683 # if WIDE_CHAR_VERSION
1684 /* ISO C says about %s in fwprintf:
1685 "If the precision is not specified or is greater than the size
1686 of the converted array, the converted array shall contain a
1687 null wide character."
1688 So if there is a precision, we must not use strlen. */
1689 /* This case has already been handled separately in VASNPRINTF. */
1692 /* ISO C says about %s in fprintf:
1693 "If the precision is not specified or greater than the size of
1694 the array, the array shall contain a null character."
1695 So if there is a precision, we must not use strlen. */
1696 const char *arg = ap->arg[arg_index].a.a_string;
1699 tmp_length = local_strnlen (arg, precision);
1701 tmp_length = strlen (arg);
1708 (unsigned int) (sizeof (void *) * CHAR_BIT
1709 * 0.25 /* binary -> hexadecimal */
1711 + 1 /* turn floor into ceil */
1712 + 2; /* account for leading 0x */
1721 # if ENABLE_UNISTDIO
1722 /* Padding considers the number of characters, therefore the number of
1723 elements after padding may be
1724 > max (tmp_length, width)
1726 <= tmp_length + width. */
1727 tmp_length = xsum (tmp_length, width);
1729 /* Padding considers the number of elements, says POSIX. */
1730 if (tmp_length < width)
1735 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1743 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1744 const FCHAR_T *format, va_list args)
1749 if (PRINTF_PARSE (format, &d, &a) < 0)
1750 /* errno is already set. */
1758 if (PRINTF_FETCHARGS (args, &a) < 0)
1766 size_t buf_neededlength;
1768 TCHAR_T *buf_malloced;
1772 /* Output string accumulator. */
1777 /* Allocate a small buffer that will hold a directive passed to
1778 sprintf or snprintf. */
1780 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1782 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1784 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1785 buf_malloced = NULL;
1790 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1791 if (size_overflow_p (buf_memsize))
1792 goto out_of_memory_1;
1793 buf = (TCHAR_T *) malloc (buf_memsize);
1795 goto out_of_memory_1;
1799 if (resultbuf != NULL)
1802 allocated = *lengthp;
1811 result is either == resultbuf or == NULL or malloc-allocated.
1812 If length > 0, then result != NULL. */
1814 /* Ensures that allocated >= needed. Aborts through a jump to
1815 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1816 #define ENSURE_ALLOCATION(needed) \
1817 if ((needed) > allocated) \
1819 size_t memory_size; \
1822 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1823 if ((needed) > allocated) \
1824 allocated = (needed); \
1825 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1826 if (size_overflow_p (memory_size)) \
1827 goto out_of_memory; \
1828 if (result == resultbuf || result == NULL) \
1829 memory = (DCHAR_T *) malloc (memory_size); \
1831 memory = (DCHAR_T *) realloc (result, memory_size); \
1832 if (memory == NULL) \
1833 goto out_of_memory; \
1834 if (result == resultbuf && length > 0) \
1835 DCHAR_CPY (memory, result, length); \
1839 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1841 if (cp != dp->dir_start)
1843 size_t n = dp->dir_start - cp;
1844 size_t augmented_length = xsum (length, n);
1846 ENSURE_ALLOCATION (augmented_length);
1847 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1848 need that the format string contains only ASCII characters
1849 if FCHAR_T and DCHAR_T are not the same type. */
1850 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1852 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1853 length = augmented_length;
1858 result[length++] = (unsigned char) *cp++;
1865 /* Execute a single directive. */
1866 if (dp->conversion == '%')
1868 size_t augmented_length;
1870 if (!(dp->arg_index == ARG_NONE))
1872 augmented_length = xsum (length, 1);
1873 ENSURE_ALLOCATION (augmented_length);
1874 result[length] = '%';
1875 length = augmented_length;
1879 if (!(dp->arg_index != ARG_NONE))
1882 if (dp->conversion == 'n')
1884 switch (a.arg[dp->arg_index].type)
1886 case TYPE_COUNT_SCHAR_POINTER:
1887 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1889 case TYPE_COUNT_SHORT_POINTER:
1890 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1892 case TYPE_COUNT_INT_POINTER:
1893 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1895 case TYPE_COUNT_LONGINT_POINTER:
1896 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1898 #if HAVE_LONG_LONG_INT
1899 case TYPE_COUNT_LONGLONGINT_POINTER:
1900 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1908 /* The unistdio extensions. */
1909 else if (dp->conversion == 'U')
1911 arg_type type = a.arg[dp->arg_index].type;
1912 int flags = dp->flags;
1920 if (dp->width_start != dp->width_end)
1922 if (dp->width_arg_index != ARG_NONE)
1926 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1928 arg = a.arg[dp->width_arg_index].a.a_int;
1931 /* "A negative field width is taken as a '-' flag
1932 followed by a positive field width." */
1934 width = (unsigned int) (-arg);
1941 const FCHAR_T *digitp = dp->width_start;
1944 width = xsum (xtimes (width, 10), *digitp++ - '0');
1945 while (digitp != dp->width_end);
1952 if (dp->precision_start != dp->precision_end)
1954 if (dp->precision_arg_index != ARG_NONE)
1958 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1960 arg = a.arg[dp->precision_arg_index].a.a_int;
1961 /* "A negative precision is taken as if the precision
1971 const FCHAR_T *digitp = dp->precision_start + 1;
1974 while (digitp != dp->precision_end)
1975 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1982 case TYPE_U8_STRING:
1984 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1985 const uint8_t *arg_end;
1990 /* Use only PRECISION characters, from the left. */
1993 for (; precision > 0; precision--)
1995 int count = u8_strmblen (arg_end);
2000 if (!(result == resultbuf || result == NULL))
2002 if (buf_malloced != NULL)
2003 free (buf_malloced);
2014 /* Use the entire string, and count the number of
2020 int count = u8_strmblen (arg_end);
2025 if (!(result == resultbuf || result == NULL))
2027 if (buf_malloced != NULL)
2028 free (buf_malloced);
2039 /* Use the entire string. */
2040 arg_end = arg + u8_strlen (arg);
2041 /* The number of characters doesn't matter. */
2045 if (has_width && width > characters
2046 && !(dp->flags & FLAG_LEFT))
2048 size_t n = width - characters;
2049 ENSURE_ALLOCATION (xsum (length, n));
2050 DCHAR_SET (result + length, ' ', n);
2054 # if DCHAR_IS_UINT8_T
2056 size_t n = arg_end - arg;
2057 ENSURE_ALLOCATION (xsum (length, n));
2058 DCHAR_CPY (result + length, arg, n);
2063 DCHAR_T *converted = result + length;
2064 size_t converted_len = allocated - length;
2066 /* Convert from UTF-8 to locale encoding. */
2068 u8_conv_to_encoding (locale_charset (),
2069 iconveh_question_mark,
2070 arg, arg_end - arg, NULL,
2071 converted, &converted_len);
2073 /* Convert from UTF-8 to UTF-16/UTF-32. */
2075 U8_TO_DCHAR (arg, arg_end - arg,
2076 converted, &converted_len);
2078 if (converted == NULL)
2080 int saved_errno = errno;
2081 if (!(result == resultbuf || result == NULL))
2083 if (buf_malloced != NULL)
2084 free (buf_malloced);
2086 errno = saved_errno;
2089 if (converted != result + length)
2091 ENSURE_ALLOCATION (xsum (length, converted_len));
2092 DCHAR_CPY (result + length, converted, converted_len);
2095 length += converted_len;
2099 if (has_width && width > characters
2100 && (dp->flags & FLAG_LEFT))
2102 size_t n = width - characters;
2103 ENSURE_ALLOCATION (xsum (length, n));
2104 DCHAR_SET (result + length, ' ', n);
2110 case TYPE_U16_STRING:
2112 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
2113 const uint16_t *arg_end;
2118 /* Use only PRECISION characters, from the left. */
2121 for (; precision > 0; precision--)
2123 int count = u16_strmblen (arg_end);
2128 if (!(result == resultbuf || result == NULL))
2130 if (buf_malloced != NULL)
2131 free (buf_malloced);
2142 /* Use the entire string, and count the number of
2148 int count = u16_strmblen (arg_end);
2153 if (!(result == resultbuf || result == NULL))
2155 if (buf_malloced != NULL)
2156 free (buf_malloced);
2167 /* Use the entire string. */
2168 arg_end = arg + u16_strlen (arg);
2169 /* The number of characters doesn't matter. */
2173 if (has_width && width > characters
2174 && !(dp->flags & FLAG_LEFT))
2176 size_t n = width - characters;
2177 ENSURE_ALLOCATION (xsum (length, n));
2178 DCHAR_SET (result + length, ' ', n);
2182 # if DCHAR_IS_UINT16_T
2184 size_t n = arg_end - arg;
2185 ENSURE_ALLOCATION (xsum (length, n));
2186 DCHAR_CPY (result + length, arg, n);
2191 DCHAR_T *converted = result + length;
2192 size_t converted_len = allocated - length;
2194 /* Convert from UTF-16 to locale encoding. */
2196 u16_conv_to_encoding (locale_charset (),
2197 iconveh_question_mark,
2198 arg, arg_end - arg, NULL,
2199 converted, &converted_len);
2201 /* Convert from UTF-16 to UTF-8/UTF-32. */
2203 U16_TO_DCHAR (arg, arg_end - arg,
2204 converted, &converted_len);
2206 if (converted == NULL)
2208 int saved_errno = errno;
2209 if (!(result == resultbuf || result == NULL))
2211 if (buf_malloced != NULL)
2212 free (buf_malloced);
2214 errno = saved_errno;
2217 if (converted != result + length)
2219 ENSURE_ALLOCATION (xsum (length, converted_len));
2220 DCHAR_CPY (result + length, converted, converted_len);
2223 length += converted_len;
2227 if (has_width && width > characters
2228 && (dp->flags & FLAG_LEFT))
2230 size_t n = width - characters;
2231 ENSURE_ALLOCATION (xsum (length, n));
2232 DCHAR_SET (result + length, ' ', n);
2238 case TYPE_U32_STRING:
2240 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
2241 const uint32_t *arg_end;
2246 /* Use only PRECISION characters, from the left. */
2249 for (; precision > 0; precision--)
2251 int count = u32_strmblen (arg_end);
2256 if (!(result == resultbuf || result == NULL))
2258 if (buf_malloced != NULL)
2259 free (buf_malloced);
2270 /* Use the entire string, and count the number of
2276 int count = u32_strmblen (arg_end);
2281 if (!(result == resultbuf || result == NULL))
2283 if (buf_malloced != NULL)
2284 free (buf_malloced);
2295 /* Use the entire string. */
2296 arg_end = arg + u32_strlen (arg);
2297 /* The number of characters doesn't matter. */
2301 if (has_width && width > characters
2302 && !(dp->flags & FLAG_LEFT))
2304 size_t n = width - characters;
2305 ENSURE_ALLOCATION (xsum (length, n));
2306 DCHAR_SET (result + length, ' ', n);
2310 # if DCHAR_IS_UINT32_T
2312 size_t n = arg_end - arg;
2313 ENSURE_ALLOCATION (xsum (length, n));
2314 DCHAR_CPY (result + length, arg, n);
2319 DCHAR_T *converted = result + length;
2320 size_t converted_len = allocated - length;
2322 /* Convert from UTF-32 to locale encoding. */
2324 u32_conv_to_encoding (locale_charset (),
2325 iconveh_question_mark,
2326 arg, arg_end - arg, NULL,
2327 converted, &converted_len);
2329 /* Convert from UTF-32 to UTF-8/UTF-16. */
2331 U32_TO_DCHAR (arg, arg_end - arg,
2332 converted, &converted_len);
2334 if (converted == NULL)
2336 int saved_errno = errno;
2337 if (!(result == resultbuf || result == NULL))
2339 if (buf_malloced != NULL)
2340 free (buf_malloced);
2342 errno = saved_errno;
2345 if (converted != result + length)
2347 ENSURE_ALLOCATION (xsum (length, converted_len));
2348 DCHAR_CPY (result + length, converted, converted_len);
2351 length += converted_len;
2355 if (has_width && width > characters
2356 && (dp->flags & FLAG_LEFT))
2358 size_t n = width - characters;
2359 ENSURE_ALLOCATION (xsum (length, n));
2360 DCHAR_SET (result + length, ' ', n);
2371 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T
2372 else if (dp->conversion == 's'
2373 # if WIDE_CHAR_VERSION
2374 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2376 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2380 /* The normal handling of the 's' directive below requires
2381 allocating a temporary buffer. The determination of its
2382 length (tmp_length), in the case when a precision is
2383 specified, below requires a conversion between a char[]
2384 string and a wchar_t[] wide string. It could be done, but
2385 we have no guarantee that the implementation of sprintf will
2386 use the exactly same algorithm. Without this guarantee, it
2387 is possible to have buffer overrun bugs. In order to avoid
2388 such bugs, we implement the entire processing of the 's'
2389 directive ourselves. */
2390 int flags = dp->flags;
2398 if (dp->width_start != dp->width_end)
2400 if (dp->width_arg_index != ARG_NONE)
2404 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2406 arg = a.arg[dp->width_arg_index].a.a_int;
2409 /* "A negative field width is taken as a '-' flag
2410 followed by a positive field width." */
2412 width = (unsigned int) (-arg);
2419 const FCHAR_T *digitp = dp->width_start;
2422 width = xsum (xtimes (width, 10), *digitp++ - '0');
2423 while (digitp != dp->width_end);
2430 if (dp->precision_start != dp->precision_end)
2432 if (dp->precision_arg_index != ARG_NONE)
2436 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2438 arg = a.arg[dp->precision_arg_index].a.a_int;
2439 /* "A negative precision is taken as if the precision
2449 const FCHAR_T *digitp = dp->precision_start + 1;
2452 while (digitp != dp->precision_end)
2453 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2458 # if WIDE_CHAR_VERSION
2459 /* %s in vasnwprintf. See the specification of fwprintf. */
2461 const char *arg = a.arg[dp->arg_index].a.a_string;
2462 const char *arg_end;
2467 /* Use only as many bytes as needed to produce PRECISION
2468 wide characters, from the left. */
2471 memset (&state, '\0', sizeof (mbstate_t));
2475 for (; precision > 0; precision--)
2479 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2481 count = mblen (arg_end, MB_CUR_MAX);
2484 /* Found the terminating NUL. */
2488 /* Invalid or incomplete multibyte character. */
2489 if (!(result == resultbuf || result == NULL))
2491 if (buf_malloced != NULL)
2492 free (buf_malloced);
2503 /* Use the entire string, and count the number of wide
2507 memset (&state, '\0', sizeof (mbstate_t));
2515 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2517 count = mblen (arg_end, MB_CUR_MAX);
2520 /* Found the terminating NUL. */
2524 /* Invalid or incomplete multibyte character. */
2525 if (!(result == resultbuf || result == NULL))
2527 if (buf_malloced != NULL)
2528 free (buf_malloced);
2539 /* Use the entire string. */
2540 arg_end = arg + strlen (arg);
2541 /* The number of characters doesn't matter. */
2545 if (has_width && width > characters
2546 && !(dp->flags & FLAG_LEFT))
2548 size_t n = width - characters;
2549 ENSURE_ALLOCATION (xsum (length, n));
2550 DCHAR_SET (result + length, ' ', n);
2554 if (has_precision || has_width)
2556 /* We know the number of wide characters in advance. */
2560 memset (&state, '\0', sizeof (mbstate_t));
2562 ENSURE_ALLOCATION (xsum (length, characters));
2563 for (remaining = characters; remaining > 0; remaining--)
2568 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2570 count = mbtowc (&wc, arg, arg_end - arg);
2573 /* mbrtowc not consistent with mbrlen, or mbtowc
2574 not consistent with mblen. */
2576 result[length++] = wc;
2579 if (!(arg == arg_end))
2586 memset (&state, '\0', sizeof (mbstate_t));
2588 while (arg < arg_end)
2593 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2595 count = mbtowc (&wc, arg, arg_end - arg);
2598 /* mbrtowc not consistent with mbrlen, or mbtowc
2599 not consistent with mblen. */
2601 ENSURE_ALLOCATION (xsum (length, 1));
2602 result[length++] = wc;
2607 if (has_width && width > characters
2608 && (dp->flags & FLAG_LEFT))
2610 size_t n = width - characters;
2611 ENSURE_ALLOCATION (xsum (length, n));
2612 DCHAR_SET (result + length, ' ', n);
2617 /* %ls in vasnprintf. See the specification of fprintf. */
2619 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2620 const wchar_t *arg_end;
2622 # if !DCHAR_IS_TCHAR
2623 /* This code assumes that TCHAR_T is 'char'. */
2624 typedef int TCHAR_T_verify[2 * (sizeof (TCHAR_T) == 1) - 1];
2633 /* Use only as many wide characters as needed to produce
2634 at most PRECISION bytes, from the left. */
2635 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2637 memset (&state, '\0', sizeof (mbstate_t));
2641 while (precision > 0)
2643 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2647 /* Found the terminating null wide character. */
2649 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2650 count = wcrtomb (cbuf, *arg_end, &state);
2652 count = wctomb (cbuf, *arg_end);
2656 /* Cannot convert. */
2657 if (!(result == resultbuf || result == NULL))
2659 if (buf_malloced != NULL)
2660 free (buf_malloced);
2665 if (precision < count)
2668 characters += count;
2678 /* Use the entire string, and count the number of
2680 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2682 memset (&state, '\0', sizeof (mbstate_t));
2688 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2692 /* Found the terminating null wide character. */
2694 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2695 count = wcrtomb (cbuf, *arg_end, &state);
2697 count = wctomb (cbuf, *arg_end);
2701 /* Cannot convert. */
2702 if (!(result == resultbuf || result == NULL))
2704 if (buf_malloced != NULL)
2705 free (buf_malloced);
2711 characters += count;
2717 /* Use the entire string. */
2718 arg_end = arg + local_wcslen (arg);
2719 /* The number of bytes doesn't matter. */
2724 # if !DCHAR_IS_TCHAR
2725 /* Convert the string into a piece of temporary memory. */
2726 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2730 TCHAR_T *tmpptr = tmpsrc;
2732 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2734 memset (&state, '\0', sizeof (mbstate_t));
2736 for (remaining = characters; remaining > 0; )
2738 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2743 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2744 count = wcrtomb (cbuf, *arg, &state);
2746 count = wctomb (cbuf, *arg);
2749 /* Inconsistency. */
2751 memcpy (tmpptr, cbuf, count);
2756 if (!(arg == arg_end))
2760 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2762 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2763 iconveh_question_mark,
2769 int saved_errno = errno;
2771 if (!(result == resultbuf || result == NULL))
2773 if (buf_malloced != NULL)
2774 free (buf_malloced);
2776 errno = saved_errno;
2784 # if ENABLE_UNISTDIO
2785 /* Outside POSIX, it's preferrable to compare the width
2786 against the number of _characters_ of the converted
2788 w = DCHAR_MBSNLEN (result + length, characters);
2790 /* The width is compared against the number of _bytes_
2791 of the converted value, says POSIX. */
2796 /* w doesn't matter. */
2799 if (has_width && width > w
2800 && !(dp->flags & FLAG_LEFT))
2802 size_t n = width - w;
2803 ENSURE_ALLOCATION (xsum (length, n));
2804 DCHAR_SET (result + length, ' ', n);
2809 if (has_precision || has_width)
2811 /* We know the number of bytes in advance. */
2813 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2815 memset (&state, '\0', sizeof (mbstate_t));
2817 ENSURE_ALLOCATION (xsum (length, characters));
2818 for (remaining = characters; remaining > 0; )
2820 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2825 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2826 count = wcrtomb (cbuf, *arg, &state);
2828 count = wctomb (cbuf, *arg);
2831 /* Inconsistency. */
2833 memcpy (result + length, cbuf, count);
2838 if (!(arg == arg_end))
2843 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2845 memset (&state, '\0', sizeof (mbstate_t));
2847 while (arg < arg_end)
2849 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2854 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2855 count = wcrtomb (cbuf, *arg, &state);
2857 count = wctomb (cbuf, *arg);
2861 /* Cannot convert. */
2862 if (!(result == resultbuf || result == NULL))
2864 if (buf_malloced != NULL)
2865 free (buf_malloced);
2870 ENSURE_ALLOCATION (xsum (length, count));
2871 memcpy (result + length, cbuf, count);
2877 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2878 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2880 length += tmpdst_len;
2883 if (has_width && width > w
2884 && (dp->flags & FLAG_LEFT))
2886 size_t n = width - w;
2887 ENSURE_ALLOCATION (xsum (length, n));
2888 DCHAR_SET (result + length, ' ', n);
2895 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2896 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2897 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2899 # if NEED_PRINTF_DOUBLE
2900 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2902 # if NEED_PRINTF_LONG_DOUBLE
2903 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2909 arg_type type = a.arg[dp->arg_index].type;
2910 int flags = dp->flags;
2916 DCHAR_T tmpbuf[700];
2923 if (dp->width_start != dp->width_end)
2925 if (dp->width_arg_index != ARG_NONE)
2929 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2931 arg = a.arg[dp->width_arg_index].a.a_int;
2934 /* "A negative field width is taken as a '-' flag
2935 followed by a positive field width." */
2937 width = (unsigned int) (-arg);
2944 const FCHAR_T *digitp = dp->width_start;
2947 width = xsum (xtimes (width, 10), *digitp++ - '0');
2948 while (digitp != dp->width_end);
2955 if (dp->precision_start != dp->precision_end)
2957 if (dp->precision_arg_index != ARG_NONE)
2961 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2963 arg = a.arg[dp->precision_arg_index].a.a_int;
2964 /* "A negative precision is taken as if the precision
2974 const FCHAR_T *digitp = dp->precision_start + 1;
2977 while (digitp != dp->precision_end)
2978 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2983 /* Allocate a temporary buffer of sufficient size. */
2984 if (type == TYPE_LONGDOUBLE)
2986 (unsigned int) ((LDBL_DIG + 1)
2987 * 0.831 /* decimal -> hexadecimal */
2989 + 1; /* turn floor into ceil */
2992 (unsigned int) ((DBL_DIG + 1)
2993 * 0.831 /* decimal -> hexadecimal */
2995 + 1; /* turn floor into ceil */
2996 if (tmp_length < precision)
2997 tmp_length = precision;
2998 /* Account for sign, decimal point etc. */
2999 tmp_length = xsum (tmp_length, 12);
3001 if (tmp_length < width)
3004 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3006 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3010 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3012 if (size_overflow_p (tmp_memsize))
3013 /* Overflow, would lead to out of memory. */
3015 tmp = (DCHAR_T *) malloc (tmp_memsize);
3017 /* Out of memory. */
3023 if (type == TYPE_LONGDOUBLE)
3025 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
3026 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3030 if (dp->conversion == 'A')
3032 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3036 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3042 DECL_LONG_DOUBLE_ROUNDING
3044 BEGIN_LONG_DOUBLE_ROUNDING ();
3046 if (signbit (arg)) /* arg < 0.0L or negative zero */
3054 else if (flags & FLAG_SHOWSIGN)
3056 else if (flags & FLAG_SPACE)
3059 if (arg > 0.0L && arg + arg == arg)
3061 if (dp->conversion == 'A')
3063 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3067 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3073 long double mantissa;
3076 mantissa = printf_frexpl (arg, &exponent);
3084 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
3086 /* Round the mantissa. */
3087 long double tail = mantissa;
3090 for (q = precision; ; q--)
3092 int digit = (int) tail;
3096 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
3105 for (q = precision; q > 0; q--)
3111 *p++ = dp->conversion - 'A' + 'X';
3116 digit = (int) mantissa;
3119 if ((flags & FLAG_ALT)
3120 || mantissa > 0.0L || precision > 0)
3122 *p++ = decimal_point_char ();
3123 /* This loop terminates because we assume
3124 that FLT_RADIX is a power of 2. */
3125 while (mantissa > 0.0L)
3128 digit = (int) mantissa;
3133 : dp->conversion - 10);
3137 while (precision > 0)
3144 *p++ = dp->conversion - 'A' + 'P';
3145 # if WIDE_CHAR_VERSION
3147 static const wchar_t decimal_format[] =
3148 { '%', '+', 'd', '\0' };
3149 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3154 if (sizeof (DCHAR_T) == 1)
3156 sprintf ((char *) p, "%+d", exponent);
3164 sprintf (expbuf, "%+d", exponent);
3165 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3171 END_LONG_DOUBLE_ROUNDING ();
3179 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
3180 double arg = a.arg[dp->arg_index].a.a_double;
3184 if (dp->conversion == 'A')
3186 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3190 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3197 if (signbit (arg)) /* arg < 0.0 or negative zero */
3205 else if (flags & FLAG_SHOWSIGN)
3207 else if (flags & FLAG_SPACE)
3210 if (arg > 0.0 && arg + arg == arg)
3212 if (dp->conversion == 'A')
3214 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3218 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3227 mantissa = printf_frexp (arg, &exponent);
3235 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
3237 /* Round the mantissa. */
3238 double tail = mantissa;
3241 for (q = precision; ; q--)
3243 int digit = (int) tail;
3247 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
3256 for (q = precision; q > 0; q--)
3262 *p++ = dp->conversion - 'A' + 'X';
3267 digit = (int) mantissa;
3270 if ((flags & FLAG_ALT)
3271 || mantissa > 0.0 || precision > 0)
3273 *p++ = decimal_point_char ();
3274 /* This loop terminates because we assume
3275 that FLT_RADIX is a power of 2. */
3276 while (mantissa > 0.0)
3279 digit = (int) mantissa;
3284 : dp->conversion - 10);
3288 while (precision > 0)
3295 *p++ = dp->conversion - 'A' + 'P';
3296 # if WIDE_CHAR_VERSION
3298 static const wchar_t decimal_format[] =
3299 { '%', '+', 'd', '\0' };
3300 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3305 if (sizeof (DCHAR_T) == 1)
3307 sprintf ((char *) p, "%+d", exponent);
3315 sprintf (expbuf, "%+d", exponent);
3316 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3326 /* The generated string now extends from tmp to p, with the
3327 zero padding insertion point being at pad_ptr. */
3328 if (has_width && p - tmp < width)
3330 size_t pad = width - (p - tmp);
3331 DCHAR_T *end = p + pad;
3333 if (flags & FLAG_LEFT)
3335 /* Pad with spaces on the right. */
3336 for (; pad > 0; pad--)
3339 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3341 /* Pad with zeroes. */
3346 for (; pad > 0; pad--)
3351 /* Pad with spaces on the left. */
3356 for (; pad > 0; pad--)
3364 size_t count = p - tmp;
3366 if (count >= tmp_length)
3367 /* tmp_length was incorrectly calculated - fix the
3371 /* Make room for the result. */
3372 if (count >= allocated - length)
3374 size_t n = xsum (length, count);
3376 ENSURE_ALLOCATION (n);
3379 /* Append the result. */
3380 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3387 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3388 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3389 || dp->conversion == 'e' || dp->conversion == 'E'
3390 || dp->conversion == 'g' || dp->conversion == 'G'
3391 || dp->conversion == 'a' || dp->conversion == 'A')
3393 # if NEED_PRINTF_DOUBLE
3394 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3395 # elif NEED_PRINTF_INFINITE_DOUBLE
3396 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3397 /* The systems (mingw) which produce wrong output
3398 for Inf, -Inf, and NaN also do so for -0.0.
3399 Therefore we treat this case here as well. */
3400 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3402 # if NEED_PRINTF_LONG_DOUBLE
3403 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3404 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3405 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3406 /* Some systems produce wrong output for Inf,
3407 -Inf, and NaN. Some systems in this category
3408 (IRIX 5.3) also do so for -0.0. Therefore we
3409 treat this case here as well. */
3410 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3414 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3415 arg_type type = a.arg[dp->arg_index].type;
3417 int flags = dp->flags;
3423 DCHAR_T tmpbuf[700];
3430 if (dp->width_start != dp->width_end)
3432 if (dp->width_arg_index != ARG_NONE)
3436 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3438 arg = a.arg[dp->width_arg_index].a.a_int;
3441 /* "A negative field width is taken as a '-' flag
3442 followed by a positive field width." */
3444 width = (unsigned int) (-arg);
3451 const FCHAR_T *digitp = dp->width_start;
3454 width = xsum (xtimes (width, 10), *digitp++ - '0');
3455 while (digitp != dp->width_end);
3462 if (dp->precision_start != dp->precision_end)
3464 if (dp->precision_arg_index != ARG_NONE)
3468 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3470 arg = a.arg[dp->precision_arg_index].a.a_int;
3471 /* "A negative precision is taken as if the precision
3481 const FCHAR_T *digitp = dp->precision_start + 1;
3484 while (digitp != dp->precision_end)
3485 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3490 /* POSIX specifies the default precision to be 6 for %f, %F,
3491 %e, %E, but not for %g, %G. Implementations appear to use
3492 the same default precision also for %g, %G. But for %a, %A,
3493 the default precision is 0. */
3495 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3498 /* Allocate a temporary buffer of sufficient size. */
3499 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3500 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3501 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3502 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3503 # elif NEED_PRINTF_LONG_DOUBLE
3504 tmp_length = LDBL_DIG + 1;
3505 # elif NEED_PRINTF_DOUBLE
3506 tmp_length = DBL_DIG + 1;
3510 if (tmp_length < precision)
3511 tmp_length = precision;
3512 # if NEED_PRINTF_LONG_DOUBLE
3513 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3514 if (type == TYPE_LONGDOUBLE)
3516 if (dp->conversion == 'f' || dp->conversion == 'F')
3518 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3519 if (!(isnanl (arg) || arg + arg == arg))
3521 /* arg is finite and nonzero. */
3522 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3523 if (exponent >= 0 && tmp_length < exponent + precision)
3524 tmp_length = exponent + precision;
3528 # if NEED_PRINTF_DOUBLE
3529 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3530 if (type == TYPE_DOUBLE)
3532 if (dp->conversion == 'f' || dp->conversion == 'F')
3534 double arg = a.arg[dp->arg_index].a.a_double;
3535 if (!(isnand (arg) || arg + arg == arg))
3537 /* arg is finite and nonzero. */
3538 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3539 if (exponent >= 0 && tmp_length < exponent + precision)
3540 tmp_length = exponent + precision;
3544 /* Account for sign, decimal point etc. */
3545 tmp_length = xsum (tmp_length, 12);
3547 if (tmp_length < width)
3550 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3552 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3556 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3558 if (size_overflow_p (tmp_memsize))
3559 /* Overflow, would lead to out of memory. */
3561 tmp = (DCHAR_T *) malloc (tmp_memsize);
3563 /* Out of memory. */
3570 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3571 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3572 if (type == TYPE_LONGDOUBLE)
3575 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3579 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3581 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3585 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3591 DECL_LONG_DOUBLE_ROUNDING
3593 BEGIN_LONG_DOUBLE_ROUNDING ();
3595 if (signbit (arg)) /* arg < 0.0L or negative zero */
3603 else if (flags & FLAG_SHOWSIGN)
3605 else if (flags & FLAG_SPACE)
3608 if (arg > 0.0L && arg + arg == arg)
3610 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3612 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3616 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3621 # if NEED_PRINTF_LONG_DOUBLE
3624 if (dp->conversion == 'f' || dp->conversion == 'F')
3630 scale10_round_decimal_long_double (arg, precision);
3633 END_LONG_DOUBLE_ROUNDING ();
3636 ndigits = strlen (digits);
3638 if (ndigits > precision)
3642 *p++ = digits[ndigits];
3644 while (ndigits > precision);
3647 /* Here ndigits <= precision. */
3648 if ((flags & FLAG_ALT) || precision > 0)
3650 *p++ = decimal_point_char ();
3651 for (; precision > ndigits; precision--)
3656 *p++ = digits[ndigits];
3662 else if (dp->conversion == 'e' || dp->conversion == 'E')
3670 if ((flags & FLAG_ALT) || precision > 0)
3672 *p++ = decimal_point_char ();
3673 for (; precision > 0; precision--)
3684 exponent = floorlog10l (arg);
3689 scale10_round_decimal_long_double (arg,
3690 (int)precision - exponent);
3693 END_LONG_DOUBLE_ROUNDING ();
3696 ndigits = strlen (digits);
3698 if (ndigits == precision + 1)
3700 if (ndigits < precision
3701 || ndigits > precision + 2)
3702 /* The exponent was not guessed
3703 precisely enough. */
3706 /* None of two values of exponent is
3707 the right one. Prevent an endless
3711 if (ndigits == precision)
3717 /* Here ndigits = precision+1. */
3718 if (is_borderline (digits, precision))
3720 /* Maybe the exponent guess was too high
3721 and a smaller exponent can be reached
3722 by turning a 10...0 into 9...9x. */
3724 scale10_round_decimal_long_double (arg,
3725 (int)precision - exponent + 1);
3726 if (digits2 == NULL)
3729 END_LONG_DOUBLE_ROUNDING ();
3732 if (strlen (digits2) == precision + 1)
3741 /* Here ndigits = precision+1. */
3743 *p++ = digits[--ndigits];
3744 if ((flags & FLAG_ALT) || precision > 0)
3746 *p++ = decimal_point_char ();
3750 *p++ = digits[ndigits];
3757 *p++ = dp->conversion; /* 'e' or 'E' */
3758 # if WIDE_CHAR_VERSION
3760 static const wchar_t decimal_format[] =
3761 { '%', '+', '.', '2', 'd', '\0' };
3762 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3767 if (sizeof (DCHAR_T) == 1)
3769 sprintf ((char *) p, "%+.2d", exponent);
3777 sprintf (expbuf, "%+.2d", exponent);
3778 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3783 else if (dp->conversion == 'g' || dp->conversion == 'G')
3787 /* precision >= 1. */
3790 /* The exponent is 0, >= -4, < precision.
3791 Use fixed-point notation. */
3793 size_t ndigits = precision;
3794 /* Number of trailing zeroes that have to be
3797 (flags & FLAG_ALT ? 0 : precision - 1);
3801 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3803 *p++ = decimal_point_char ();
3804 while (ndigits > nzeroes)
3820 exponent = floorlog10l (arg);
3825 scale10_round_decimal_long_double (arg,
3826 (int)(precision - 1) - exponent);
3829 END_LONG_DOUBLE_ROUNDING ();
3832 ndigits = strlen (digits);
3834 if (ndigits == precision)
3836 if (ndigits < precision - 1
3837 || ndigits > precision + 1)
3838 /* The exponent was not guessed
3839 precisely enough. */
3842 /* None of two values of exponent is
3843 the right one. Prevent an endless
3847 if (ndigits < precision)
3853 /* Here ndigits = precision. */
3854 if (is_borderline (digits, precision - 1))
3856 /* Maybe the exponent guess was too high
3857 and a smaller exponent can be reached
3858 by turning a 10...0 into 9...9x. */
3860 scale10_round_decimal_long_double (arg,
3861 (int)(precision - 1) - exponent + 1);
3862 if (digits2 == NULL)
3865 END_LONG_DOUBLE_ROUNDING ();
3868 if (strlen (digits2) == precision)
3877 /* Here ndigits = precision. */
3879 /* Determine the number of trailing zeroes
3880 that have to be dropped. */
3882 if ((flags & FLAG_ALT) == 0)
3883 while (nzeroes < ndigits
3884 && digits[nzeroes] == '0')
3887 /* The exponent is now determined. */
3889 && exponent < (long)precision)
3891 /* Fixed-point notation:
3892 max(exponent,0)+1 digits, then the
3893 decimal point, then the remaining
3894 digits without trailing zeroes. */
3897 size_t count = exponent + 1;
3898 /* Note: count <= precision = ndigits. */
3899 for (; count > 0; count--)
3900 *p++ = digits[--ndigits];
3901 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3903 *p++ = decimal_point_char ();
3904 while (ndigits > nzeroes)
3907 *p++ = digits[ndigits];
3913 size_t count = -exponent - 1;
3915 *p++ = decimal_point_char ();
3916 for (; count > 0; count--)
3918 while (ndigits > nzeroes)
3921 *p++ = digits[ndigits];
3927 /* Exponential notation. */
3928 *p++ = digits[--ndigits];
3929 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3931 *p++ = decimal_point_char ();
3932 while (ndigits > nzeroes)
3935 *p++ = digits[ndigits];
3938 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3939 # if WIDE_CHAR_VERSION
3941 static const wchar_t decimal_format[] =
3942 { '%', '+', '.', '2', 'd', '\0' };
3943 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3948 if (sizeof (DCHAR_T) == 1)
3950 sprintf ((char *) p, "%+.2d", exponent);
3958 sprintf (expbuf, "%+.2d", exponent);
3959 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3971 /* arg is finite. */
3977 if (dp->conversion == 'f' || dp->conversion == 'F')
3980 if ((flags & FLAG_ALT) || precision > 0)
3982 *p++ = decimal_point_char ();
3983 for (; precision > 0; precision--)
3987 else if (dp->conversion == 'e' || dp->conversion == 'E')
3990 if ((flags & FLAG_ALT) || precision > 0)
3992 *p++ = decimal_point_char ();
3993 for (; precision > 0; precision--)
3996 *p++ = dp->conversion; /* 'e' or 'E' */
4001 else if (dp->conversion == 'g' || dp->conversion == 'G')
4004 if (flags & FLAG_ALT)
4007 (precision > 0 ? precision - 1 : 0);
4008 *p++ = decimal_point_char ();
4009 for (; ndigits > 0; --ndigits)
4013 else if (dp->conversion == 'a' || dp->conversion == 'A')
4016 *p++ = dp->conversion - 'A' + 'X';
4019 if ((flags & FLAG_ALT) || precision > 0)
4021 *p++ = decimal_point_char ();
4022 for (; precision > 0; precision--)
4025 *p++ = dp->conversion - 'A' + 'P';
4034 END_LONG_DOUBLE_ROUNDING ();
4037 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4041 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4043 double arg = a.arg[dp->arg_index].a.a_double;
4047 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4049 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4053 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4060 if (signbit (arg)) /* arg < 0.0 or negative zero */
4068 else if (flags & FLAG_SHOWSIGN)
4070 else if (flags & FLAG_SPACE)
4073 if (arg > 0.0 && arg + arg == arg)
4075 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4077 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4081 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4086 # if NEED_PRINTF_DOUBLE
4089 if (dp->conversion == 'f' || dp->conversion == 'F')
4095 scale10_round_decimal_double (arg, precision);
4098 ndigits = strlen (digits);
4100 if (ndigits > precision)
4104 *p++ = digits[ndigits];
4106 while (ndigits > precision);
4109 /* Here ndigits <= precision. */
4110 if ((flags & FLAG_ALT) || precision > 0)
4112 *p++ = decimal_point_char ();
4113 for (; precision > ndigits; precision--)
4118 *p++ = digits[ndigits];
4124 else if (dp->conversion == 'e' || dp->conversion == 'E')
4132 if ((flags & FLAG_ALT) || precision > 0)
4134 *p++ = decimal_point_char ();
4135 for (; precision > 0; precision--)
4146 exponent = floorlog10 (arg);
4151 scale10_round_decimal_double (arg,
4152 (int)precision - exponent);
4155 ndigits = strlen (digits);
4157 if (ndigits == precision + 1)
4159 if (ndigits < precision
4160 || ndigits > precision + 2)
4161 /* The exponent was not guessed
4162 precisely enough. */
4165 /* None of two values of exponent is
4166 the right one. Prevent an endless
4170 if (ndigits == precision)
4176 /* Here ndigits = precision+1. */
4177 if (is_borderline (digits, precision))
4179 /* Maybe the exponent guess was too high
4180 and a smaller exponent can be reached
4181 by turning a 10...0 into 9...9x. */
4183 scale10_round_decimal_double (arg,
4184 (int)precision - exponent + 1);
4185 if (digits2 == NULL)
4190 if (strlen (digits2) == precision + 1)
4199 /* Here ndigits = precision+1. */
4201 *p++ = digits[--ndigits];
4202 if ((flags & FLAG_ALT) || precision > 0)
4204 *p++ = decimal_point_char ();
4208 *p++ = digits[ndigits];
4215 *p++ = dp->conversion; /* 'e' or 'E' */
4216 # if WIDE_CHAR_VERSION
4218 static const wchar_t decimal_format[] =
4219 /* Produce the same number of exponent digits
4220 as the native printf implementation. */
4221 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4222 { '%', '+', '.', '3', 'd', '\0' };
4224 { '%', '+', '.', '2', 'd', '\0' };
4226 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4232 static const char decimal_format[] =
4233 /* Produce the same number of exponent digits
4234 as the native printf implementation. */
4235 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4240 if (sizeof (DCHAR_T) == 1)
4242 sprintf ((char *) p, decimal_format, exponent);
4250 sprintf (expbuf, decimal_format, exponent);
4251 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4257 else if (dp->conversion == 'g' || dp->conversion == 'G')
4261 /* precision >= 1. */
4264 /* The exponent is 0, >= -4, < precision.
4265 Use fixed-point notation. */
4267 size_t ndigits = precision;
4268 /* Number of trailing zeroes that have to be
4271 (flags & FLAG_ALT ? 0 : precision - 1);
4275 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4277 *p++ = decimal_point_char ();
4278 while (ndigits > nzeroes)
4294 exponent = floorlog10 (arg);
4299 scale10_round_decimal_double (arg,
4300 (int)(precision - 1) - exponent);
4303 ndigits = strlen (digits);
4305 if (ndigits == precision)
4307 if (ndigits < precision - 1
4308 || ndigits > precision + 1)
4309 /* The exponent was not guessed
4310 precisely enough. */
4313 /* None of two values of exponent is
4314 the right one. Prevent an endless
4318 if (ndigits < precision)
4324 /* Here ndigits = precision. */
4325 if (is_borderline (digits, precision - 1))
4327 /* Maybe the exponent guess was too high
4328 and a smaller exponent can be reached
4329 by turning a 10...0 into 9...9x. */
4331 scale10_round_decimal_double (arg,
4332 (int)(precision - 1) - exponent + 1);
4333 if (digits2 == NULL)
4338 if (strlen (digits2) == precision)
4347 /* Here ndigits = precision. */
4349 /* Determine the number of trailing zeroes
4350 that have to be dropped. */
4352 if ((flags & FLAG_ALT) == 0)
4353 while (nzeroes < ndigits
4354 && digits[nzeroes] == '0')
4357 /* The exponent is now determined. */
4359 && exponent < (long)precision)
4361 /* Fixed-point notation:
4362 max(exponent,0)+1 digits, then the
4363 decimal point, then the remaining
4364 digits without trailing zeroes. */
4367 size_t count = exponent + 1;
4368 /* Note: count <= precision = ndigits. */
4369 for (; count > 0; count--)
4370 *p++ = digits[--ndigits];
4371 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4373 *p++ = decimal_point_char ();
4374 while (ndigits > nzeroes)
4377 *p++ = digits[ndigits];
4383 size_t count = -exponent - 1;
4385 *p++ = decimal_point_char ();
4386 for (; count > 0; count--)
4388 while (ndigits > nzeroes)
4391 *p++ = digits[ndigits];
4397 /* Exponential notation. */
4398 *p++ = digits[--ndigits];
4399 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4401 *p++ = decimal_point_char ();
4402 while (ndigits > nzeroes)
4405 *p++ = digits[ndigits];
4408 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4409 # if WIDE_CHAR_VERSION
4411 static const wchar_t decimal_format[] =
4412 /* Produce the same number of exponent digits
4413 as the native printf implementation. */
4414 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4415 { '%', '+', '.', '3', 'd', '\0' };
4417 { '%', '+', '.', '2', 'd', '\0' };
4419 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4425 static const char decimal_format[] =
4426 /* Produce the same number of exponent digits
4427 as the native printf implementation. */
4428 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4433 if (sizeof (DCHAR_T) == 1)
4435 sprintf ((char *) p, decimal_format, exponent);
4443 sprintf (expbuf, decimal_format, exponent);
4444 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4457 /* arg is finite. */
4463 if (dp->conversion == 'f' || dp->conversion == 'F')
4466 if ((flags & FLAG_ALT) || precision > 0)
4468 *p++ = decimal_point_char ();
4469 for (; precision > 0; precision--)
4473 else if (dp->conversion == 'e' || dp->conversion == 'E')
4476 if ((flags & FLAG_ALT) || precision > 0)
4478 *p++ = decimal_point_char ();
4479 for (; precision > 0; precision--)
4482 *p++ = dp->conversion; /* 'e' or 'E' */
4484 /* Produce the same number of exponent digits as
4485 the native printf implementation. */
4486 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4492 else if (dp->conversion == 'g' || dp->conversion == 'G')
4495 if (flags & FLAG_ALT)
4498 (precision > 0 ? precision - 1 : 0);
4499 *p++ = decimal_point_char ();
4500 for (; ndigits > 0; --ndigits)
4512 /* The generated string now extends from tmp to p, with the
4513 zero padding insertion point being at pad_ptr. */
4514 if (has_width && p - tmp < width)
4516 size_t pad = width - (p - tmp);
4517 DCHAR_T *end = p + pad;
4519 if (flags & FLAG_LEFT)
4521 /* Pad with spaces on the right. */
4522 for (; pad > 0; pad--)
4525 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4527 /* Pad with zeroes. */
4532 for (; pad > 0; pad--)
4537 /* Pad with spaces on the left. */
4542 for (; pad > 0; pad--)
4550 size_t count = p - tmp;
4552 if (count >= tmp_length)
4553 /* tmp_length was incorrectly calculated - fix the
4557 /* Make room for the result. */
4558 if (count >= allocated - length)
4560 size_t n = xsum (length, count);
4562 ENSURE_ALLOCATION (n);
4565 /* Append the result. */
4566 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4575 arg_type type = a.arg[dp->arg_index].type;
4576 int flags = dp->flags;
4577 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4581 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4585 #if NEED_PRINTF_UNBOUNDED_PRECISION
4588 # define prec_ourselves 0
4590 #if NEED_PRINTF_FLAG_LEFTADJUST
4591 # define pad_ourselves 1
4592 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4595 # define pad_ourselves 0
4598 unsigned int prefix_count;
4599 int prefixes[2] IF_LINT (= { 0 });
4602 TCHAR_T tmpbuf[700];
4606 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4609 if (dp->width_start != dp->width_end)
4611 if (dp->width_arg_index != ARG_NONE)
4615 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4617 arg = a.arg[dp->width_arg_index].a.a_int;
4620 /* "A negative field width is taken as a '-' flag
4621 followed by a positive field width." */
4623 width = (unsigned int) (-arg);
4630 const FCHAR_T *digitp = dp->width_start;
4633 width = xsum (xtimes (width, 10), *digitp++ - '0');
4634 while (digitp != dp->width_end);
4640 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4643 if (dp->precision_start != dp->precision_end)
4645 if (dp->precision_arg_index != ARG_NONE)
4649 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4651 arg = a.arg[dp->precision_arg_index].a.a_int;
4652 /* "A negative precision is taken as if the precision
4662 const FCHAR_T *digitp = dp->precision_start + 1;
4665 while (digitp != dp->precision_end)
4666 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4672 /* Decide whether to handle the precision ourselves. */
4673 #if NEED_PRINTF_UNBOUNDED_PRECISION
4674 switch (dp->conversion)
4676 case 'd': case 'i': case 'u':
4678 case 'x': case 'X': case 'p':
4679 prec_ourselves = has_precision && (precision > 0);
4687 /* Decide whether to perform the padding ourselves. */
4688 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4689 switch (dp->conversion)
4691 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4692 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4693 to perform the padding after this conversion. Functions
4694 with unistdio extensions perform the padding based on
4695 character count rather than element count. */
4698 # if NEED_PRINTF_FLAG_ZERO
4699 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4705 pad_ourselves = prec_ourselves;
4711 /* Allocate a temporary buffer of sufficient size for calling
4714 MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
4715 flags, width, has_precision, precision,
4718 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4722 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4724 if (size_overflow_p (tmp_memsize))
4725 /* Overflow, would lead to out of memory. */
4727 tmp = (TCHAR_T *) malloc (tmp_memsize);
4729 /* Out of memory. */
4734 /* Construct the format string for calling snprintf or
4738 #if NEED_PRINTF_FLAG_GROUPING
4739 /* The underlying implementation doesn't support the ' flag.
4740 Produce no grouping characters in this case; this is
4741 acceptable because the grouping is locale dependent. */
4743 if (flags & FLAG_GROUP)
4746 if (flags & FLAG_LEFT)
4748 if (flags & FLAG_SHOWSIGN)
4750 if (flags & FLAG_SPACE)
4752 if (flags & FLAG_ALT)
4756 if (flags & FLAG_ZERO)
4758 if (dp->width_start != dp->width_end)
4760 size_t n = dp->width_end - dp->width_start;
4761 /* The width specification is known to consist only
4762 of standard ASCII characters. */
4763 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4765 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4770 const FCHAR_T *mp = dp->width_start;
4772 *fbp++ = (unsigned char) *mp++;
4777 if (!prec_ourselves)
4779 if (dp->precision_start != dp->precision_end)
4781 size_t n = dp->precision_end - dp->precision_start;
4782 /* The precision specification is known to consist only
4783 of standard ASCII characters. */
4784 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4786 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4791 const FCHAR_T *mp = dp->precision_start;
4793 *fbp++ = (unsigned char) *mp++;
4801 #if HAVE_LONG_LONG_INT
4802 case TYPE_LONGLONGINT:
4803 case TYPE_ULONGLONGINT:
4804 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4817 case TYPE_WIDE_CHAR:
4820 case TYPE_WIDE_STRING:
4824 case TYPE_LONGDOUBLE:
4830 #if NEED_PRINTF_DIRECTIVE_F
4831 if (dp->conversion == 'F')
4835 *fbp = dp->conversion;
4837 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4842 /* On glibc2 systems from glibc >= 2.3 - probably also older
4843 ones - we know that snprintf's returns value conforms to
4844 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4845 Therefore we can avoid using %n in this situation.
4846 On glibc2 systems from 2004-10-18 or newer, the use of %n
4847 in format strings in writable memory may crash the program
4848 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4849 in this situation. */
4850 /* On native Win32 systems (such as mingw), we can avoid using
4852 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4853 snprintf does not write more than the specified number
4854 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4855 '4', '5', '6' into buf, not '4', '5', '\0'.)
4856 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4857 allows us to recognize the case of an insufficient
4858 buffer size: it returns -1 in this case.
4859 On native Win32 systems (such as mingw) where the OS is
4860 Windows Vista, the use of %n in format strings by default
4861 crashes the program. See
4862 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4863 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4864 So we should avoid %n in this situation. */
4871 /* Construct the arguments for calling snprintf or sprintf. */
4873 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4875 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4877 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4879 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4881 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4883 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4887 /* The SNPRINTF result is appended after result[0..length].
4888 The latter is an array of DCHAR_T; SNPRINTF appends an
4889 array of TCHAR_T to it. This is possible because
4890 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4891 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4892 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4893 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4894 where an snprintf() with maxlen==1 acts like sprintf(). */
4895 ENSURE_ALLOCATION (xsum (length,
4896 (2 + TCHARS_PER_DCHAR - 1)
4897 / TCHARS_PER_DCHAR));
4898 /* Prepare checking whether snprintf returns the count
4900 *(TCHAR_T *) (result + length) = '\0';
4909 size_t maxlen = allocated - length;
4910 /* SNPRINTF can fail if its second argument is
4912 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4913 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4914 maxlen = maxlen * TCHARS_PER_DCHAR;
4915 # define SNPRINTF_BUF(arg) \
4916 switch (prefix_count) \
4919 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4924 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4926 prefixes[0], arg, &count); \
4929 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4931 prefixes[0], prefixes[1], arg, \
4938 # define SNPRINTF_BUF(arg) \
4939 switch (prefix_count) \
4942 count = sprintf (tmp, buf, arg); \
4945 count = sprintf (tmp, buf, prefixes[0], arg); \
4948 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4961 int arg = a.arg[dp->arg_index].a.a_schar;
4967 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4973 int arg = a.arg[dp->arg_index].a.a_short;
4979 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4985 int arg = a.arg[dp->arg_index].a.a_int;
4991 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4997 long int arg = a.arg[dp->arg_index].a.a_longint;
5003 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
5007 #if HAVE_LONG_LONG_INT
5008 case TYPE_LONGLONGINT:
5010 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
5014 case TYPE_ULONGLONGINT:
5016 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
5023 double arg = a.arg[dp->arg_index].a.a_double;
5027 case TYPE_LONGDOUBLE:
5029 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5035 int arg = a.arg[dp->arg_index].a.a_char;
5040 case TYPE_WIDE_CHAR:
5042 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5049 const char *arg = a.arg[dp->arg_index].a.a_string;
5054 case TYPE_WIDE_STRING:
5056 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5063 void *arg = a.arg[dp->arg_index].a.a_pointer;
5072 /* Portability: Not all implementations of snprintf()
5073 are ISO C 99 compliant. Determine the number of
5074 bytes that snprintf() has produced or would have
5078 /* Verify that snprintf() has NUL-terminated its
5081 && ((TCHAR_T *) (result + length)) [count] != '\0')
5083 /* Portability hack. */
5084 if (retcount > count)
5089 /* snprintf() doesn't understand the '%n'
5093 /* Don't use the '%n' directive; instead, look
5094 at the snprintf() return value. */
5100 /* Look at the snprintf() return value. */
5103 # if !HAVE_SNPRINTF_RETVAL_C99
5104 /* HP-UX 10.20 snprintf() is doubly deficient:
5105 It doesn't understand the '%n' directive,
5106 *and* it returns -1 (rather than the length
5107 that would have been required) when the
5108 buffer is too small.
5109 But a failure at this point can also come
5110 from other reasons than a too small buffer,
5111 such as an invalid wide string argument to
5112 the %ls directive, or possibly an invalid
5113 floating-point argument. */
5115 MAX_ROOM_NEEDED (&a, dp->arg_index,
5116 dp->conversion, type, flags,
5117 width, has_precision,
5118 precision, pad_ourselves);
5120 if (maxlen < tmp_length)
5122 /* Make more room. But try to do through
5123 this reallocation only once. */
5124 size_t bigger_need =
5127 TCHARS_PER_DCHAR - 1)
5128 / TCHARS_PER_DCHAR);
5129 /* And always grow proportionally.
5130 (There may be several arguments, each
5131 needing a little more room than the
5133 size_t bigger_need2 =
5134 xsum (xtimes (allocated, 2), 12);
5135 if (bigger_need < bigger_need2)
5136 bigger_need = bigger_need2;
5137 ENSURE_ALLOCATION (bigger_need);
5148 /* Attempt to handle failure. */
5151 /* SNPRINTF or sprintf failed. Save and use the errno
5152 that it has set, if any. */
5153 int saved_errno = errno;
5155 if (!(result == resultbuf || result == NULL))
5157 if (buf_malloced != NULL)
5158 free (buf_malloced);
5163 : (dp->conversion == 'c' || dp->conversion == 's'
5170 /* Handle overflow of the allocated buffer.
5171 If such an overflow occurs, a C99 compliant snprintf()
5172 returns a count >= maxlen. However, a non-compliant
5173 snprintf() function returns only count = maxlen - 1. To
5174 cover both cases, test whether count >= maxlen - 1. */
5175 if ((unsigned int) count + 1 >= maxlen)
5177 /* If maxlen already has attained its allowed maximum,
5178 allocating more memory will not increase maxlen.
5179 Instead of looping, bail out. */
5180 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5184 /* Need at least (count + 1) * sizeof (TCHAR_T)
5185 bytes. (The +1 is for the trailing NUL.)
5186 But ask for (count + 2) * sizeof (TCHAR_T)
5187 bytes, so that in the next round, we likely get
5188 maxlen > (unsigned int) count + 1
5189 and so we don't get here again.
5190 And allocate proportionally, to avoid looping
5191 eternally if snprintf() reports a too small
5195 ((unsigned int) count + 2
5196 + TCHARS_PER_DCHAR - 1)
5197 / TCHARS_PER_DCHAR),
5198 xtimes (allocated, 2));
5200 ENSURE_ALLOCATION (n);
5206 #if NEED_PRINTF_UNBOUNDED_PRECISION
5209 /* Handle the precision. */
5212 (TCHAR_T *) (result + length);
5216 size_t prefix_count;
5220 /* Put the additional zeroes after the sign. */
5222 && (*prec_ptr == '-' || *prec_ptr == '+'
5223 || *prec_ptr == ' '))
5225 /* Put the additional zeroes after the 0x prefix if
5226 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5228 && prec_ptr[0] == '0'
5229 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5232 move = count - prefix_count;
5233 if (precision > move)
5235 /* Insert zeroes. */
5236 size_t insert = precision - move;
5242 (count + insert + TCHARS_PER_DCHAR - 1)
5243 / TCHARS_PER_DCHAR);
5244 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5245 ENSURE_ALLOCATION (n);
5246 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5247 prec_ptr = (TCHAR_T *) (result + length);
5250 prec_end = prec_ptr + count;
5251 prec_ptr += prefix_count;
5253 while (prec_end > prec_ptr)
5256 prec_end[insert] = prec_end[0];
5262 while (prec_end > prec_ptr);
5270 if (count >= tmp_length)
5271 /* tmp_length was incorrectly calculated - fix the
5277 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5278 if (dp->conversion == 'c' || dp->conversion == 's')
5280 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5282 The result string is not certainly ASCII. */
5283 const TCHAR_T *tmpsrc;
5286 /* This code assumes that TCHAR_T is 'char'. */
5287 typedef int TCHAR_T_verify
5288 [2 * (sizeof (TCHAR_T) == 1) - 1];
5290 tmpsrc = (TCHAR_T *) (result + length);
5295 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5296 iconveh_question_mark,
5302 int saved_errno = errno;
5303 if (!(result == resultbuf || result == NULL))
5305 if (buf_malloced != NULL)
5306 free (buf_malloced);
5308 errno = saved_errno;
5311 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5312 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5318 /* The result string is ASCII.
5319 Simple 1:1 conversion. */
5321 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5322 no-op conversion, in-place on the array starting
5323 at (result + length). */
5324 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5327 const TCHAR_T *tmpsrc;
5332 if (result == resultbuf)
5334 tmpsrc = (TCHAR_T *) (result + length);
5335 /* ENSURE_ALLOCATION will not move tmpsrc
5336 (because it's part of resultbuf). */
5337 ENSURE_ALLOCATION (xsum (length, count));
5341 /* ENSURE_ALLOCATION will move the array
5342 (because it uses realloc(). */
5343 ENSURE_ALLOCATION (xsum (length, count));
5344 tmpsrc = (TCHAR_T *) (result + length);
5348 ENSURE_ALLOCATION (xsum (length, count));
5350 tmpdst = result + length;
5351 /* Copy backwards, because of overlapping. */
5354 for (n = count; n > 0; n--)
5355 *--tmpdst = (unsigned char) *--tmpsrc;
5360 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5361 /* Make room for the result. */
5362 if (count > allocated - length)
5364 /* Need at least count elements. But allocate
5367 xmax (xsum (length, count), xtimes (allocated, 2));
5369 ENSURE_ALLOCATION (n);
5373 /* Here count <= allocated - length. */
5375 /* Perform padding. */
5376 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5377 if (pad_ourselves && has_width)
5380 # if ENABLE_UNISTDIO
5381 /* Outside POSIX, it's preferrable to compare the width
5382 against the number of _characters_ of the converted
5384 w = DCHAR_MBSNLEN (result + length, count);
5386 /* The width is compared against the number of _bytes_
5387 of the converted value, says POSIX. */
5392 size_t pad = width - w;
5394 /* Make room for the result. */
5395 if (xsum (count, pad) > allocated - length)
5397 /* Need at least count + pad elements. But
5398 allocate proportionally. */
5400 xmax (xsum3 (length, count, pad),
5401 xtimes (allocated, 2));
5405 ENSURE_ALLOCATION (n);
5408 ENSURE_ALLOCATION (n);
5411 /* Here count + pad <= allocated - length. */
5414 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5415 DCHAR_T * const rp = result + length;
5417 DCHAR_T * const rp = tmp;
5419 DCHAR_T *p = rp + count;
5420 DCHAR_T *end = p + pad;
5422 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5423 if (dp->conversion == 'c'
5424 || dp->conversion == 's')
5425 /* No zero-padding for string directives. */
5430 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5431 /* No zero-padding of "inf" and "nan". */
5432 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5433 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5436 /* The generated string now extends from rp to p,
5437 with the zero padding insertion point being at
5440 count = count + pad; /* = end - rp */
5442 if (flags & FLAG_LEFT)
5444 /* Pad with spaces on the right. */
5445 for (; pad > 0; pad--)
5448 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5450 /* Pad with zeroes. */
5455 for (; pad > 0; pad--)
5460 /* Pad with spaces on the left. */
5465 for (; pad > 0; pad--)
5473 /* Here still count <= allocated - length. */
5475 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5476 /* The snprintf() result did fit. */
5478 /* Append the sprintf() result. */
5479 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5486 #if NEED_PRINTF_DIRECTIVE_F
5487 if (dp->conversion == 'F')
5489 /* Convert the %f result to upper case for %F. */
5490 DCHAR_T *rp = result + length;
5492 for (rc = count; rc > 0; rc--, rp++)
5493 if (*rp >= 'a' && *rp <= 'z')
5494 *rp = *rp - 'a' + 'A';
5501 #undef pad_ourselves
5502 #undef prec_ourselves
5507 /* Add the final NUL. */
5508 ENSURE_ALLOCATION (xsum (length, 1));
5509 result[length] = '\0';
5511 if (result != resultbuf && length + 1 < allocated)
5513 /* Shrink the allocated memory if possible. */
5516 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5521 if (buf_malloced != NULL)
5522 free (buf_malloced);
5525 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5526 says that snprintf() fails with errno = EOVERFLOW in this case, but
5527 that's only because snprintf() returns an 'int'. This function does
5528 not have this limitation. */
5533 if (!(result == resultbuf || result == NULL))
5535 if (buf_malloced != NULL)
5536 free (buf_malloced);
5543 if (!(result == resultbuf || result == NULL))
5545 if (buf_malloced != NULL)
5546 free (buf_malloced);
5554 #undef MAX_ROOM_NEEDED
5555 #undef TCHARS_PER_DCHAR
5563 #undef DCHAR_IS_TCHAR