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 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* This file can be parametrized with the following macros:
19 VASNPRINTF The name of the function being defined.
20 FCHAR_T The element type of the format string.
21 DCHAR_T The element type of the destination (result) string.
22 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
23 in the format string are ASCII. MUST be set if
24 FCHAR_T and DCHAR_T are not the same type.
25 DIRECTIVE Structure denoting a format directive.
27 DIRECTIVES Structure denoting the set of format directives of a
28 format string. Depends on FCHAR_T.
29 PRINTF_PARSE Function that parses a format string.
31 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
32 DCHAR_SET memset like function for DCHAR_T[] arrays.
33 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
34 SNPRINTF The system's snprintf (or similar) function.
35 This may be either snprintf or swprintf.
36 TCHAR_T The element type of the argument and result string
37 of the said SNPRINTF function. This may be either
38 char or wchar_t. The code exploits that
39 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
40 alignof (TCHAR_T) <= alignof (DCHAR_T).
41 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
42 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
43 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
44 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
45 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
47 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
48 This must come before <config.h> because <config.h> may include
49 <features.h>, and once <features.h> has been included, it's too late. */
51 # define _GNU_SOURCE 1
63 # if WIDE_CHAR_VERSION
64 # include "vasnwprintf.h"
66 # include "vasnprintf.h"
70 #include <locale.h> /* localeconv() */
71 #include <stdio.h> /* snprintf(), sprintf() */
72 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
73 #include <string.h> /* memcpy(), strlen() */
74 #include <errno.h> /* errno */
75 #include <limits.h> /* CHAR_BIT */
76 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
78 # include <langinfo.h>
81 # if WIDE_CHAR_VERSION
82 # include "wprintf-parse.h"
84 # include "printf-parse.h"
88 /* Checked size_t computations. */
91 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
96 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
98 # include "isnand-nolibm.h"
101 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
103 # include "isnanl-nolibm.h"
107 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
109 # include "isnand-nolibm.h"
110 # include "printf-frexp.h"
113 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
115 # include "isnanl-nolibm.h"
116 # include "printf-frexpl.h"
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 && !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 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T && (WIDE_CHAR_VERSION || DCHAR_IS_TCHAR)
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_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';
1491 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1492 const FCHAR_T *format, va_list args)
1497 if (PRINTF_PARSE (format, &d, &a) < 0)
1498 /* errno is already set. */
1506 if (PRINTF_FETCHARGS (args, &a) < 0)
1514 size_t buf_neededlength;
1516 TCHAR_T *buf_malloced;
1520 /* Output string accumulator. */
1525 /* Allocate a small buffer that will hold a directive passed to
1526 sprintf or snprintf. */
1528 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1530 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1532 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1533 buf_malloced = NULL;
1538 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1539 if (size_overflow_p (buf_memsize))
1540 goto out_of_memory_1;
1541 buf = (TCHAR_T *) malloc (buf_memsize);
1543 goto out_of_memory_1;
1547 if (resultbuf != NULL)
1550 allocated = *lengthp;
1559 result is either == resultbuf or == NULL or malloc-allocated.
1560 If length > 0, then result != NULL. */
1562 /* Ensures that allocated >= needed. Aborts through a jump to
1563 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1564 #define ENSURE_ALLOCATION(needed) \
1565 if ((needed) > allocated) \
1567 size_t memory_size; \
1570 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1571 if ((needed) > allocated) \
1572 allocated = (needed); \
1573 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1574 if (size_overflow_p (memory_size)) \
1575 goto out_of_memory; \
1576 if (result == resultbuf || result == NULL) \
1577 memory = (DCHAR_T *) malloc (memory_size); \
1579 memory = (DCHAR_T *) realloc (result, memory_size); \
1580 if (memory == NULL) \
1581 goto out_of_memory; \
1582 if (result == resultbuf && length > 0) \
1583 DCHAR_CPY (memory, result, length); \
1587 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1589 if (cp != dp->dir_start)
1591 size_t n = dp->dir_start - cp;
1592 size_t augmented_length = xsum (length, n);
1594 ENSURE_ALLOCATION (augmented_length);
1595 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1596 need that the format string contains only ASCII characters
1597 if FCHAR_T and DCHAR_T are not the same type. */
1598 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1600 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1601 length = augmented_length;
1606 result[length++] = (unsigned char) *cp++;
1613 /* Execute a single directive. */
1614 if (dp->conversion == '%')
1616 size_t augmented_length;
1618 if (!(dp->arg_index == ARG_NONE))
1620 augmented_length = xsum (length, 1);
1621 ENSURE_ALLOCATION (augmented_length);
1622 result[length] = '%';
1623 length = augmented_length;
1627 if (!(dp->arg_index != ARG_NONE))
1630 if (dp->conversion == 'n')
1632 switch (a.arg[dp->arg_index].type)
1634 case TYPE_COUNT_SCHAR_POINTER:
1635 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1637 case TYPE_COUNT_SHORT_POINTER:
1638 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1640 case TYPE_COUNT_INT_POINTER:
1641 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1643 case TYPE_COUNT_LONGINT_POINTER:
1644 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1646 #if HAVE_LONG_LONG_INT
1647 case TYPE_COUNT_LONGLONGINT_POINTER:
1648 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1656 /* The unistdio extensions. */
1657 else if (dp->conversion == 'U')
1659 arg_type type = a.arg[dp->arg_index].type;
1660 int flags = dp->flags;
1668 if (dp->width_start != dp->width_end)
1670 if (dp->width_arg_index != ARG_NONE)
1674 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1676 arg = a.arg[dp->width_arg_index].a.a_int;
1679 /* "A negative field width is taken as a '-' flag
1680 followed by a positive field width." */
1682 width = (unsigned int) (-arg);
1689 const FCHAR_T *digitp = dp->width_start;
1692 width = xsum (xtimes (width, 10), *digitp++ - '0');
1693 while (digitp != dp->width_end);
1700 if (dp->precision_start != dp->precision_end)
1702 if (dp->precision_arg_index != ARG_NONE)
1706 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1708 arg = a.arg[dp->precision_arg_index].a.a_int;
1709 /* "A negative precision is taken as if the precision
1719 const FCHAR_T *digitp = dp->precision_start + 1;
1722 while (digitp != dp->precision_end)
1723 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1730 case TYPE_U8_STRING:
1732 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1733 const uint8_t *arg_end;
1738 /* Use only PRECISION characters, from the left. */
1741 for (; precision > 0; precision--)
1743 int count = u8_strmblen (arg_end);
1748 if (!(result == resultbuf || result == NULL))
1750 if (buf_malloced != NULL)
1751 free (buf_malloced);
1762 /* Use the entire string, and count the number of
1768 int count = u8_strmblen (arg_end);
1773 if (!(result == resultbuf || result == NULL))
1775 if (buf_malloced != NULL)
1776 free (buf_malloced);
1787 /* Use the entire string. */
1788 arg_end = arg + u8_strlen (arg);
1789 /* The number of characters doesn't matter. */
1793 if (has_width && width > characters
1794 && !(dp->flags & FLAG_LEFT))
1796 size_t n = width - characters;
1797 ENSURE_ALLOCATION (xsum (length, n));
1798 DCHAR_SET (result + length, ' ', n);
1802 # if DCHAR_IS_UINT8_T
1804 size_t n = arg_end - arg;
1805 ENSURE_ALLOCATION (xsum (length, n));
1806 DCHAR_CPY (result + length, arg, n);
1811 DCHAR_T *converted = result + length;
1812 size_t converted_len = allocated - length;
1814 /* Convert from UTF-8 to locale encoding. */
1816 u8_conv_to_encoding (locale_charset (),
1817 iconveh_question_mark,
1818 arg, arg_end - arg, NULL,
1819 converted, &converted_len);
1821 /* Convert from UTF-8 to UTF-16/UTF-32. */
1823 U8_TO_DCHAR (arg, arg_end - arg,
1824 converted, &converted_len);
1826 if (converted == NULL)
1828 int saved_errno = errno;
1829 if (!(result == resultbuf || result == NULL))
1831 if (buf_malloced != NULL)
1832 free (buf_malloced);
1834 errno = saved_errno;
1837 if (converted != result + length)
1839 ENSURE_ALLOCATION (xsum (length, converted_len));
1840 DCHAR_CPY (result + length, converted, converted_len);
1843 length += converted_len;
1847 if (has_width && width > characters
1848 && (dp->flags & FLAG_LEFT))
1850 size_t n = width - characters;
1851 ENSURE_ALLOCATION (xsum (length, n));
1852 DCHAR_SET (result + length, ' ', n);
1858 case TYPE_U16_STRING:
1860 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1861 const uint16_t *arg_end;
1866 /* Use only PRECISION characters, from the left. */
1869 for (; precision > 0; precision--)
1871 int count = u16_strmblen (arg_end);
1876 if (!(result == resultbuf || result == NULL))
1878 if (buf_malloced != NULL)
1879 free (buf_malloced);
1890 /* Use the entire string, and count the number of
1896 int count = u16_strmblen (arg_end);
1901 if (!(result == resultbuf || result == NULL))
1903 if (buf_malloced != NULL)
1904 free (buf_malloced);
1915 /* Use the entire string. */
1916 arg_end = arg + u16_strlen (arg);
1917 /* The number of characters doesn't matter. */
1921 if (has_width && width > characters
1922 && !(dp->flags & FLAG_LEFT))
1924 size_t n = width - characters;
1925 ENSURE_ALLOCATION (xsum (length, n));
1926 DCHAR_SET (result + length, ' ', n);
1930 # if DCHAR_IS_UINT16_T
1932 size_t n = arg_end - arg;
1933 ENSURE_ALLOCATION (xsum (length, n));
1934 DCHAR_CPY (result + length, arg, n);
1939 DCHAR_T *converted = result + length;
1940 size_t converted_len = allocated - length;
1942 /* Convert from UTF-16 to locale encoding. */
1944 u16_conv_to_encoding (locale_charset (),
1945 iconveh_question_mark,
1946 arg, arg_end - arg, NULL,
1947 converted, &converted_len);
1949 /* Convert from UTF-16 to UTF-8/UTF-32. */
1951 U16_TO_DCHAR (arg, arg_end - arg,
1952 converted, &converted_len);
1954 if (converted == NULL)
1956 int saved_errno = errno;
1957 if (!(result == resultbuf || result == NULL))
1959 if (buf_malloced != NULL)
1960 free (buf_malloced);
1962 errno = saved_errno;
1965 if (converted != result + length)
1967 ENSURE_ALLOCATION (xsum (length, converted_len));
1968 DCHAR_CPY (result + length, converted, converted_len);
1971 length += converted_len;
1975 if (has_width && width > characters
1976 && (dp->flags & FLAG_LEFT))
1978 size_t n = width - characters;
1979 ENSURE_ALLOCATION (xsum (length, n));
1980 DCHAR_SET (result + length, ' ', n);
1986 case TYPE_U32_STRING:
1988 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1989 const uint32_t *arg_end;
1994 /* Use only PRECISION characters, from the left. */
1997 for (; precision > 0; precision--)
1999 int count = u32_strmblen (arg_end);
2004 if (!(result == resultbuf || result == NULL))
2006 if (buf_malloced != NULL)
2007 free (buf_malloced);
2018 /* Use the entire string, and count the number of
2024 int count = u32_strmblen (arg_end);
2029 if (!(result == resultbuf || result == NULL))
2031 if (buf_malloced != NULL)
2032 free (buf_malloced);
2043 /* Use the entire string. */
2044 arg_end = arg + u32_strlen (arg);
2045 /* The number of characters doesn't matter. */
2049 if (has_width && width > characters
2050 && !(dp->flags & FLAG_LEFT))
2052 size_t n = width - characters;
2053 ENSURE_ALLOCATION (xsum (length, n));
2054 DCHAR_SET (result + length, ' ', n);
2058 # if DCHAR_IS_UINT32_T
2060 size_t n = arg_end - arg;
2061 ENSURE_ALLOCATION (xsum (length, n));
2062 DCHAR_CPY (result + length, arg, n);
2067 DCHAR_T *converted = result + length;
2068 size_t converted_len = allocated - length;
2070 /* Convert from UTF-32 to locale encoding. */
2072 u32_conv_to_encoding (locale_charset (),
2073 iconveh_question_mark,
2074 arg, arg_end - arg, NULL,
2075 converted, &converted_len);
2077 /* Convert from UTF-32 to UTF-8/UTF-16. */
2079 U32_TO_DCHAR (arg, arg_end - arg,
2080 converted, &converted_len);
2082 if (converted == NULL)
2084 int saved_errno = errno;
2085 if (!(result == resultbuf || result == NULL))
2087 if (buf_malloced != NULL)
2088 free (buf_malloced);
2090 errno = saved_errno;
2093 if (converted != result + length)
2095 ENSURE_ALLOCATION (xsum (length, converted_len));
2096 DCHAR_CPY (result + length, converted, converted_len);
2099 length += converted_len;
2103 if (has_width && width > characters
2104 && (dp->flags & FLAG_LEFT))
2106 size_t n = width - characters;
2107 ENSURE_ALLOCATION (xsum (length, n));
2108 DCHAR_SET (result + length, ' ', n);
2119 #if (!USE_SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T
2120 else if (dp->conversion == 's'
2121 # if WIDE_CHAR_VERSION
2122 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2124 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2128 /* The normal handling of the 's' directive below requires
2129 allocating a temporary buffer. The determination of its
2130 length (tmp_length), in the case when a precision is
2131 specified, below requires a conversion between a char[]
2132 string and a wchar_t[] wide string. It could be done, but
2133 we have no guarantee that the implementation of sprintf will
2134 use the exactly same algorithm. Without this guarantee, it
2135 is possible to have buffer overrun bugs. In order to avoid
2136 such bugs, we implement the entire processing of the 's'
2137 directive ourselves. */
2138 int flags = dp->flags;
2146 if (dp->width_start != dp->width_end)
2148 if (dp->width_arg_index != ARG_NONE)
2152 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2154 arg = a.arg[dp->width_arg_index].a.a_int;
2157 /* "A negative field width is taken as a '-' flag
2158 followed by a positive field width." */
2160 width = (unsigned int) (-arg);
2167 const FCHAR_T *digitp = dp->width_start;
2170 width = xsum (xtimes (width, 10), *digitp++ - '0');
2171 while (digitp != dp->width_end);
2178 if (dp->precision_start != dp->precision_end)
2180 if (dp->precision_arg_index != ARG_NONE)
2184 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2186 arg = a.arg[dp->precision_arg_index].a.a_int;
2187 /* "A negative precision is taken as if the precision
2197 const FCHAR_T *digitp = dp->precision_start + 1;
2200 while (digitp != dp->precision_end)
2201 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2206 # if WIDE_CHAR_VERSION
2207 /* %s in vasnwprintf. See the specification of fwprintf. */
2209 const char *arg = a.arg[dp->arg_index].a.a_string;
2210 const char *arg_end;
2215 /* Use only as many bytes as needed to produce PRECISION
2216 wide characters, from the left. */
2219 memset (&state, '\0', sizeof (mbstate_t));
2223 for (; precision > 0; precision--)
2227 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2229 count = mblen (arg_end, MB_CUR_MAX);
2232 /* Found the terminating NUL. */
2236 /* Invalid or incomplete multibyte character. */
2237 if (!(result == resultbuf || result == NULL))
2239 if (buf_malloced != NULL)
2240 free (buf_malloced);
2251 /* Use the entire string, and count the number of wide
2255 memset (&state, '\0', sizeof (mbstate_t));
2263 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2265 count = mblen (arg_end, MB_CUR_MAX);
2268 /* Found the terminating NUL. */
2272 /* Invalid or incomplete multibyte character. */
2273 if (!(result == resultbuf || result == NULL))
2275 if (buf_malloced != NULL)
2276 free (buf_malloced);
2287 /* Use the entire string. */
2288 arg_end = arg + strlen (arg);
2289 /* The number of characters doesn't matter. */
2293 if (has_width && width > characters
2294 && !(dp->flags & FLAG_LEFT))
2296 size_t n = width - characters;
2297 ENSURE_ALLOCATION (xsum (length, n));
2298 DCHAR_SET (result + length, ' ', n);
2302 if (has_precision || has_width)
2304 /* We know the number of wide characters in advance. */
2308 memset (&state, '\0', sizeof (mbstate_t));
2310 ENSURE_ALLOCATION (xsum (length, characters));
2311 for (remaining = characters; remaining > 0; remaining--)
2316 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2318 count = mbtowc (&wc, arg, arg_end - arg);
2321 /* mbrtowc not consistent with mbrlen, or mbtowc
2322 not consistent with mblen. */
2324 result[length++] = wc;
2327 if (!(arg == arg_end))
2334 memset (&state, '\0', sizeof (mbstate_t));
2336 while (arg < arg_end)
2341 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2343 count = mbtowc (&wc, arg, arg_end - arg);
2346 /* mbrtowc not consistent with mbrlen, or mbtowc
2347 not consistent with mblen. */
2349 ENSURE_ALLOCATION (xsum (length, 1));
2350 result[length++] = wc;
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);
2365 /* %ls in vasnprintf. See the specification of fprintf. */
2367 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2368 const wchar_t *arg_end;
2370 # if !DCHAR_IS_TCHAR
2371 /* This code assumes that TCHAR_T is 'char'. */
2372 typedef int TCHAR_T_verify[2 * (sizeof (TCHAR_T) == 1) - 1];
2381 /* Use only as many wide characters as needed to produce
2382 at most PRECISION bytes, from the left. */
2383 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2385 memset (&state, '\0', sizeof (mbstate_t));
2389 while (precision > 0)
2391 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2395 /* Found the terminating null wide character. */
2397 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2398 count = wcrtomb (cbuf, *arg_end, &state);
2400 count = wctomb (cbuf, *arg_end);
2404 /* Cannot convert. */
2405 if (!(result == resultbuf || result == NULL))
2407 if (buf_malloced != NULL)
2408 free (buf_malloced);
2413 if (precision < count)
2416 characters += count;
2426 /* Use the entire string, and count the number of
2428 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2430 memset (&state, '\0', sizeof (mbstate_t));
2436 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2440 /* Found the terminating null wide character. */
2442 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2443 count = wcrtomb (cbuf, *arg_end, &state);
2445 count = wctomb (cbuf, *arg_end);
2449 /* Cannot convert. */
2450 if (!(result == resultbuf || result == NULL))
2452 if (buf_malloced != NULL)
2453 free (buf_malloced);
2459 characters += count;
2465 /* Use the entire string. */
2466 arg_end = arg + local_wcslen (arg);
2467 /* The number of bytes doesn't matter. */
2472 # if !DCHAR_IS_TCHAR
2473 /* Convert the string into a piece of temporary memory. */
2474 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2478 TCHAR_T *tmpptr = tmpsrc;
2480 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2482 memset (&state, '\0', sizeof (mbstate_t));
2484 for (remaining = characters; remaining > 0; )
2486 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2491 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2492 count = wcrtomb (cbuf, *arg, &state);
2494 count = wctomb (cbuf, *arg);
2497 /* Inconsistency. */
2499 memcpy (tmpptr, cbuf, count);
2504 if (!(arg == arg_end))
2508 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2510 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2511 iconveh_question_mark,
2517 int saved_errno = errno;
2519 if (!(result == resultbuf || result == NULL))
2521 if (buf_malloced != NULL)
2522 free (buf_malloced);
2524 errno = saved_errno;
2532 # if ENABLE_UNISTDIO
2533 /* Outside POSIX, it's preferrable to compare the width
2534 against the number of _characters_ of the converted
2536 w = DCHAR_MBSNLEN (result + length, characters);
2538 /* The width is compared against the number of _bytes_
2539 of the converted value, says POSIX. */
2544 /* w doesn't matter. */
2547 if (has_width && width > w
2548 && !(dp->flags & FLAG_LEFT))
2550 size_t n = width - w;
2551 ENSURE_ALLOCATION (xsum (length, n));
2552 DCHAR_SET (result + length, ' ', n);
2557 if (has_precision || has_width)
2559 /* We know the number of bytes in advance. */
2561 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2563 memset (&state, '\0', sizeof (mbstate_t));
2565 ENSURE_ALLOCATION (xsum (length, characters));
2566 for (remaining = characters; remaining > 0; )
2568 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2573 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2574 count = wcrtomb (cbuf, *arg, &state);
2576 count = wctomb (cbuf, *arg);
2579 /* Inconsistency. */
2581 memcpy (result + length, cbuf, count);
2586 if (!(arg == arg_end))
2591 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2593 memset (&state, '\0', sizeof (mbstate_t));
2595 while (arg < arg_end)
2597 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2602 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2603 count = wcrtomb (cbuf, *arg, &state);
2605 count = wctomb (cbuf, *arg);
2609 /* Cannot convert. */
2610 if (!(result == resultbuf || result == NULL))
2612 if (buf_malloced != NULL)
2613 free (buf_malloced);
2618 ENSURE_ALLOCATION (xsum (length, count));
2619 memcpy (result + length, cbuf, count);
2625 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2626 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2628 length += tmpdst_len;
2631 if (has_width && width > w
2632 && (dp->flags & FLAG_LEFT))
2634 size_t n = width - w;
2635 ENSURE_ALLOCATION (xsum (length, n));
2636 DCHAR_SET (result + length, ' ', n);
2643 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2644 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2645 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2647 # if NEED_PRINTF_DOUBLE
2648 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2650 # if NEED_PRINTF_LONG_DOUBLE
2651 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2657 arg_type type = a.arg[dp->arg_index].type;
2658 int flags = dp->flags;
2664 DCHAR_T tmpbuf[700];
2671 if (dp->width_start != dp->width_end)
2673 if (dp->width_arg_index != ARG_NONE)
2677 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2679 arg = a.arg[dp->width_arg_index].a.a_int;
2682 /* "A negative field width is taken as a '-' flag
2683 followed by a positive field width." */
2685 width = (unsigned int) (-arg);
2692 const FCHAR_T *digitp = dp->width_start;
2695 width = xsum (xtimes (width, 10), *digitp++ - '0');
2696 while (digitp != dp->width_end);
2703 if (dp->precision_start != dp->precision_end)
2705 if (dp->precision_arg_index != ARG_NONE)
2709 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2711 arg = a.arg[dp->precision_arg_index].a.a_int;
2712 /* "A negative precision is taken as if the precision
2722 const FCHAR_T *digitp = dp->precision_start + 1;
2725 while (digitp != dp->precision_end)
2726 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2731 /* Allocate a temporary buffer of sufficient size. */
2732 if (type == TYPE_LONGDOUBLE)
2734 (unsigned int) ((LDBL_DIG + 1)
2735 * 0.831 /* decimal -> hexadecimal */
2737 + 1; /* turn floor into ceil */
2740 (unsigned int) ((DBL_DIG + 1)
2741 * 0.831 /* decimal -> hexadecimal */
2743 + 1; /* turn floor into ceil */
2744 if (tmp_length < precision)
2745 tmp_length = precision;
2746 /* Account for sign, decimal point etc. */
2747 tmp_length = xsum (tmp_length, 12);
2749 if (tmp_length < width)
2752 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2754 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2758 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2760 if (size_overflow_p (tmp_memsize))
2761 /* Overflow, would lead to out of memory. */
2763 tmp = (DCHAR_T *) malloc (tmp_memsize);
2765 /* Out of memory. */
2771 if (type == TYPE_LONGDOUBLE)
2773 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2774 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2778 if (dp->conversion == 'A')
2780 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2784 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2790 DECL_LONG_DOUBLE_ROUNDING
2792 BEGIN_LONG_DOUBLE_ROUNDING ();
2794 if (signbit (arg)) /* arg < 0.0L or negative zero */
2802 else if (flags & FLAG_SHOWSIGN)
2804 else if (flags & FLAG_SPACE)
2807 if (arg > 0.0L && arg + arg == arg)
2809 if (dp->conversion == 'A')
2811 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2815 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2821 long double mantissa;
2824 mantissa = printf_frexpl (arg, &exponent);
2832 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2834 /* Round the mantissa. */
2835 long double tail = mantissa;
2838 for (q = precision; ; q--)
2840 int digit = (int) tail;
2844 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2853 for (q = precision; q > 0; q--)
2859 *p++ = dp->conversion - 'A' + 'X';
2864 digit = (int) mantissa;
2867 if ((flags & FLAG_ALT)
2868 || mantissa > 0.0L || precision > 0)
2870 *p++ = decimal_point_char ();
2871 /* This loop terminates because we assume
2872 that FLT_RADIX is a power of 2. */
2873 while (mantissa > 0.0L)
2876 digit = (int) mantissa;
2881 : dp->conversion - 10);
2885 while (precision > 0)
2892 *p++ = dp->conversion - 'A' + 'P';
2893 # if WIDE_CHAR_VERSION
2895 static const wchar_t decimal_format[] =
2896 { '%', '+', 'd', '\0' };
2897 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2902 if (sizeof (DCHAR_T) == 1)
2904 sprintf ((char *) p, "%+d", exponent);
2912 sprintf (expbuf, "%+d", exponent);
2913 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2919 END_LONG_DOUBLE_ROUNDING ();
2927 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2928 double arg = a.arg[dp->arg_index].a.a_double;
2932 if (dp->conversion == 'A')
2934 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2938 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2945 if (signbit (arg)) /* arg < 0.0 or negative zero */
2953 else if (flags & FLAG_SHOWSIGN)
2955 else if (flags & FLAG_SPACE)
2958 if (arg > 0.0 && arg + arg == arg)
2960 if (dp->conversion == 'A')
2962 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2966 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2975 mantissa = printf_frexp (arg, &exponent);
2983 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2985 /* Round the mantissa. */
2986 double tail = mantissa;
2989 for (q = precision; ; q--)
2991 int digit = (int) tail;
2995 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
3004 for (q = precision; q > 0; q--)
3010 *p++ = dp->conversion - 'A' + 'X';
3015 digit = (int) mantissa;
3018 if ((flags & FLAG_ALT)
3019 || mantissa > 0.0 || precision > 0)
3021 *p++ = decimal_point_char ();
3022 /* This loop terminates because we assume
3023 that FLT_RADIX is a power of 2. */
3024 while (mantissa > 0.0)
3027 digit = (int) mantissa;
3032 : dp->conversion - 10);
3036 while (precision > 0)
3043 *p++ = dp->conversion - 'A' + 'P';
3044 # if WIDE_CHAR_VERSION
3046 static const wchar_t decimal_format[] =
3047 { '%', '+', 'd', '\0' };
3048 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3053 if (sizeof (DCHAR_T) == 1)
3055 sprintf ((char *) p, "%+d", exponent);
3063 sprintf (expbuf, "%+d", exponent);
3064 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3074 /* The generated string now extends from tmp to p, with the
3075 zero padding insertion point being at pad_ptr. */
3076 if (has_width && p - tmp < width)
3078 size_t pad = width - (p - tmp);
3079 DCHAR_T *end = p + pad;
3081 if (flags & FLAG_LEFT)
3083 /* Pad with spaces on the right. */
3084 for (; pad > 0; pad--)
3087 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3089 /* Pad with zeroes. */
3094 for (; pad > 0; pad--)
3099 /* Pad with spaces on the left. */
3104 for (; pad > 0; pad--)
3112 size_t count = p - tmp;
3114 if (count >= tmp_length)
3115 /* tmp_length was incorrectly calculated - fix the
3119 /* Make room for the result. */
3120 if (count >= allocated - length)
3122 size_t n = xsum (length, count);
3124 ENSURE_ALLOCATION (n);
3127 /* Append the result. */
3128 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3135 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3136 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3137 || dp->conversion == 'e' || dp->conversion == 'E'
3138 || dp->conversion == 'g' || dp->conversion == 'G'
3139 || dp->conversion == 'a' || dp->conversion == 'A')
3141 # if NEED_PRINTF_DOUBLE
3142 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3143 # elif NEED_PRINTF_INFINITE_DOUBLE
3144 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3145 /* The systems (mingw) which produce wrong output
3146 for Inf, -Inf, and NaN also do so for -0.0.
3147 Therefore we treat this case here as well. */
3148 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3150 # if NEED_PRINTF_LONG_DOUBLE
3151 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3152 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3153 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3154 /* Some systems produce wrong output for Inf,
3155 -Inf, and NaN. Some systems in this category
3156 (IRIX 5.3) also do so for -0.0. Therefore we
3157 treat this case here as well. */
3158 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3162 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3163 arg_type type = a.arg[dp->arg_index].type;
3165 int flags = dp->flags;
3171 DCHAR_T tmpbuf[700];
3178 if (dp->width_start != dp->width_end)
3180 if (dp->width_arg_index != ARG_NONE)
3184 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3186 arg = a.arg[dp->width_arg_index].a.a_int;
3189 /* "A negative field width is taken as a '-' flag
3190 followed by a positive field width." */
3192 width = (unsigned int) (-arg);
3199 const FCHAR_T *digitp = dp->width_start;
3202 width = xsum (xtimes (width, 10), *digitp++ - '0');
3203 while (digitp != dp->width_end);
3210 if (dp->precision_start != dp->precision_end)
3212 if (dp->precision_arg_index != ARG_NONE)
3216 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3218 arg = a.arg[dp->precision_arg_index].a.a_int;
3219 /* "A negative precision is taken as if the precision
3229 const FCHAR_T *digitp = dp->precision_start + 1;
3232 while (digitp != dp->precision_end)
3233 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3238 /* POSIX specifies the default precision to be 6 for %f, %F,
3239 %e, %E, but not for %g, %G. Implementations appear to use
3240 the same default precision also for %g, %G. But for %a, %A,
3241 the default precision is 0. */
3243 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3246 /* Allocate a temporary buffer of sufficient size. */
3247 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3248 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3249 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3250 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3251 # elif NEED_PRINTF_LONG_DOUBLE
3252 tmp_length = LDBL_DIG + 1;
3253 # elif NEED_PRINTF_DOUBLE
3254 tmp_length = DBL_DIG + 1;
3258 if (tmp_length < precision)
3259 tmp_length = precision;
3260 # if NEED_PRINTF_LONG_DOUBLE
3261 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3262 if (type == TYPE_LONGDOUBLE)
3264 if (dp->conversion == 'f' || dp->conversion == 'F')
3266 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3267 if (!(isnanl (arg) || arg + arg == arg))
3269 /* arg is finite and nonzero. */
3270 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3271 if (exponent >= 0 && tmp_length < exponent + precision)
3272 tmp_length = exponent + precision;
3276 # if NEED_PRINTF_DOUBLE
3277 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3278 if (type == TYPE_DOUBLE)
3280 if (dp->conversion == 'f' || dp->conversion == 'F')
3282 double arg = a.arg[dp->arg_index].a.a_double;
3283 if (!(isnand (arg) || arg + arg == arg))
3285 /* arg is finite and nonzero. */
3286 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3287 if (exponent >= 0 && tmp_length < exponent + precision)
3288 tmp_length = exponent + precision;
3292 /* Account for sign, decimal point etc. */
3293 tmp_length = xsum (tmp_length, 12);
3295 if (tmp_length < width)
3298 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3300 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3304 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3306 if (size_overflow_p (tmp_memsize))
3307 /* Overflow, would lead to out of memory. */
3309 tmp = (DCHAR_T *) malloc (tmp_memsize);
3311 /* Out of memory. */
3318 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3319 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3320 if (type == TYPE_LONGDOUBLE)
3323 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3327 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3329 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3333 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3339 DECL_LONG_DOUBLE_ROUNDING
3341 BEGIN_LONG_DOUBLE_ROUNDING ();
3343 if (signbit (arg)) /* arg < 0.0L or negative zero */
3351 else if (flags & FLAG_SHOWSIGN)
3353 else if (flags & FLAG_SPACE)
3356 if (arg > 0.0L && arg + arg == arg)
3358 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3360 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3364 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3369 # if NEED_PRINTF_LONG_DOUBLE
3372 if (dp->conversion == 'f' || dp->conversion == 'F')
3378 scale10_round_decimal_long_double (arg, precision);
3381 END_LONG_DOUBLE_ROUNDING ();
3384 ndigits = strlen (digits);
3386 if (ndigits > precision)
3390 *p++ = digits[ndigits];
3392 while (ndigits > precision);
3395 /* Here ndigits <= precision. */
3396 if ((flags & FLAG_ALT) || precision > 0)
3398 *p++ = decimal_point_char ();
3399 for (; precision > ndigits; precision--)
3404 *p++ = digits[ndigits];
3410 else if (dp->conversion == 'e' || dp->conversion == 'E')
3418 if ((flags & FLAG_ALT) || precision > 0)
3420 *p++ = decimal_point_char ();
3421 for (; precision > 0; precision--)
3432 exponent = floorlog10l (arg);
3437 scale10_round_decimal_long_double (arg,
3438 (int)precision - exponent);
3441 END_LONG_DOUBLE_ROUNDING ();
3444 ndigits = strlen (digits);
3446 if (ndigits == precision + 1)
3448 if (ndigits < precision
3449 || ndigits > precision + 2)
3450 /* The exponent was not guessed
3451 precisely enough. */
3454 /* None of two values of exponent is
3455 the right one. Prevent an endless
3459 if (ndigits == precision)
3465 /* Here ndigits = precision+1. */
3466 if (is_borderline (digits, precision))
3468 /* Maybe the exponent guess was too high
3469 and a smaller exponent can be reached
3470 by turning a 10...0 into 9...9x. */
3472 scale10_round_decimal_long_double (arg,
3473 (int)precision - exponent + 1);
3474 if (digits2 == NULL)
3477 END_LONG_DOUBLE_ROUNDING ();
3480 if (strlen (digits2) == precision + 1)
3489 /* Here ndigits = precision+1. */
3491 *p++ = digits[--ndigits];
3492 if ((flags & FLAG_ALT) || precision > 0)
3494 *p++ = decimal_point_char ();
3498 *p++ = digits[ndigits];
3505 *p++ = dp->conversion; /* 'e' or 'E' */
3506 # if WIDE_CHAR_VERSION
3508 static const wchar_t decimal_format[] =
3509 { '%', '+', '.', '2', 'd', '\0' };
3510 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3515 if (sizeof (DCHAR_T) == 1)
3517 sprintf ((char *) p, "%+.2d", exponent);
3525 sprintf (expbuf, "%+.2d", exponent);
3526 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3531 else if (dp->conversion == 'g' || dp->conversion == 'G')
3535 /* precision >= 1. */
3538 /* The exponent is 0, >= -4, < precision.
3539 Use fixed-point notation. */
3541 size_t ndigits = precision;
3542 /* Number of trailing zeroes that have to be
3545 (flags & FLAG_ALT ? 0 : precision - 1);
3549 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3551 *p++ = decimal_point_char ();
3552 while (ndigits > nzeroes)
3568 exponent = floorlog10l (arg);
3573 scale10_round_decimal_long_double (arg,
3574 (int)(precision - 1) - exponent);
3577 END_LONG_DOUBLE_ROUNDING ();
3580 ndigits = strlen (digits);
3582 if (ndigits == precision)
3584 if (ndigits < precision - 1
3585 || ndigits > precision + 1)
3586 /* The exponent was not guessed
3587 precisely enough. */
3590 /* None of two values of exponent is
3591 the right one. Prevent an endless
3595 if (ndigits < precision)
3601 /* Here ndigits = precision. */
3602 if (is_borderline (digits, precision - 1))
3604 /* Maybe the exponent guess was too high
3605 and a smaller exponent can be reached
3606 by turning a 10...0 into 9...9x. */
3608 scale10_round_decimal_long_double (arg,
3609 (int)(precision - 1) - exponent + 1);
3610 if (digits2 == NULL)
3613 END_LONG_DOUBLE_ROUNDING ();
3616 if (strlen (digits2) == precision)
3625 /* Here ndigits = precision. */
3627 /* Determine the number of trailing zeroes
3628 that have to be dropped. */
3630 if ((flags & FLAG_ALT) == 0)
3631 while (nzeroes < ndigits
3632 && digits[nzeroes] == '0')
3635 /* The exponent is now determined. */
3637 && exponent < (long)precision)
3639 /* Fixed-point notation:
3640 max(exponent,0)+1 digits, then the
3641 decimal point, then the remaining
3642 digits without trailing zeroes. */
3645 size_t count = exponent + 1;
3646 /* Note: count <= precision = ndigits. */
3647 for (; count > 0; count--)
3648 *p++ = digits[--ndigits];
3649 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3651 *p++ = decimal_point_char ();
3652 while (ndigits > nzeroes)
3655 *p++ = digits[ndigits];
3661 size_t count = -exponent - 1;
3663 *p++ = decimal_point_char ();
3664 for (; count > 0; count--)
3666 while (ndigits > nzeroes)
3669 *p++ = digits[ndigits];
3675 /* Exponential notation. */
3676 *p++ = digits[--ndigits];
3677 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3679 *p++ = decimal_point_char ();
3680 while (ndigits > nzeroes)
3683 *p++ = digits[ndigits];
3686 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3687 # if WIDE_CHAR_VERSION
3689 static const wchar_t decimal_format[] =
3690 { '%', '+', '.', '2', 'd', '\0' };
3691 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3696 if (sizeof (DCHAR_T) == 1)
3698 sprintf ((char *) p, "%+.2d", exponent);
3706 sprintf (expbuf, "%+.2d", exponent);
3707 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3719 /* arg is finite. */
3725 if (dp->conversion == 'f' || dp->conversion == 'F')
3728 if ((flags & FLAG_ALT) || precision > 0)
3730 *p++ = decimal_point_char ();
3731 for (; precision > 0; precision--)
3735 else if (dp->conversion == 'e' || dp->conversion == 'E')
3738 if ((flags & FLAG_ALT) || precision > 0)
3740 *p++ = decimal_point_char ();
3741 for (; precision > 0; precision--)
3744 *p++ = dp->conversion; /* 'e' or 'E' */
3749 else if (dp->conversion == 'g' || dp->conversion == 'G')
3752 if (flags & FLAG_ALT)
3755 (precision > 0 ? precision - 1 : 0);
3756 *p++ = decimal_point_char ();
3757 for (; ndigits > 0; --ndigits)
3761 else if (dp->conversion == 'a' || dp->conversion == 'A')
3764 *p++ = dp->conversion - 'A' + 'X';
3767 if ((flags & FLAG_ALT) || precision > 0)
3769 *p++ = decimal_point_char ();
3770 for (; precision > 0; precision--)
3773 *p++ = dp->conversion - 'A' + 'P';
3782 END_LONG_DOUBLE_ROUNDING ();
3785 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3789 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3791 double arg = a.arg[dp->arg_index].a.a_double;
3795 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3797 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3801 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3808 if (signbit (arg)) /* arg < 0.0 or negative zero */
3816 else if (flags & FLAG_SHOWSIGN)
3818 else if (flags & FLAG_SPACE)
3821 if (arg > 0.0 && arg + arg == arg)
3823 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3825 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3829 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3834 # if NEED_PRINTF_DOUBLE
3837 if (dp->conversion == 'f' || dp->conversion == 'F')
3843 scale10_round_decimal_double (arg, precision);
3846 ndigits = strlen (digits);
3848 if (ndigits > precision)
3852 *p++ = digits[ndigits];
3854 while (ndigits > precision);
3857 /* Here ndigits <= precision. */
3858 if ((flags & FLAG_ALT) || precision > 0)
3860 *p++ = decimal_point_char ();
3861 for (; precision > ndigits; precision--)
3866 *p++ = digits[ndigits];
3872 else if (dp->conversion == 'e' || dp->conversion == 'E')
3880 if ((flags & FLAG_ALT) || precision > 0)
3882 *p++ = decimal_point_char ();
3883 for (; precision > 0; precision--)
3894 exponent = floorlog10 (arg);
3899 scale10_round_decimal_double (arg,
3900 (int)precision - exponent);
3903 ndigits = strlen (digits);
3905 if (ndigits == precision + 1)
3907 if (ndigits < precision
3908 || ndigits > precision + 2)
3909 /* The exponent was not guessed
3910 precisely enough. */
3913 /* None of two values of exponent is
3914 the right one. Prevent an endless
3918 if (ndigits == precision)
3924 /* Here ndigits = precision+1. */
3925 if (is_borderline (digits, precision))
3927 /* Maybe the exponent guess was too high
3928 and a smaller exponent can be reached
3929 by turning a 10...0 into 9...9x. */
3931 scale10_round_decimal_double (arg,
3932 (int)precision - exponent + 1);
3933 if (digits2 == NULL)
3938 if (strlen (digits2) == precision + 1)
3947 /* Here ndigits = precision+1. */
3949 *p++ = digits[--ndigits];
3950 if ((flags & FLAG_ALT) || precision > 0)
3952 *p++ = decimal_point_char ();
3956 *p++ = digits[ndigits];
3963 *p++ = dp->conversion; /* 'e' or 'E' */
3964 # if WIDE_CHAR_VERSION
3966 static const wchar_t decimal_format[] =
3967 /* Produce the same number of exponent digits
3968 as the native printf implementation. */
3969 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3970 { '%', '+', '.', '3', 'd', '\0' };
3972 { '%', '+', '.', '2', 'd', '\0' };
3974 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3980 static const char decimal_format[] =
3981 /* Produce the same number of exponent digits
3982 as the native printf implementation. */
3983 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3988 if (sizeof (DCHAR_T) == 1)
3990 sprintf ((char *) p, decimal_format, exponent);
3998 sprintf (expbuf, decimal_format, exponent);
3999 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4005 else if (dp->conversion == 'g' || dp->conversion == 'G')
4009 /* precision >= 1. */
4012 /* The exponent is 0, >= -4, < precision.
4013 Use fixed-point notation. */
4015 size_t ndigits = precision;
4016 /* Number of trailing zeroes that have to be
4019 (flags & FLAG_ALT ? 0 : precision - 1);
4023 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4025 *p++ = decimal_point_char ();
4026 while (ndigits > nzeroes)
4042 exponent = floorlog10 (arg);
4047 scale10_round_decimal_double (arg,
4048 (int)(precision - 1) - exponent);
4051 ndigits = strlen (digits);
4053 if (ndigits == precision)
4055 if (ndigits < precision - 1
4056 || ndigits > precision + 1)
4057 /* The exponent was not guessed
4058 precisely enough. */
4061 /* None of two values of exponent is
4062 the right one. Prevent an endless
4066 if (ndigits < precision)
4072 /* Here ndigits = precision. */
4073 if (is_borderline (digits, precision - 1))
4075 /* Maybe the exponent guess was too high
4076 and a smaller exponent can be reached
4077 by turning a 10...0 into 9...9x. */
4079 scale10_round_decimal_double (arg,
4080 (int)(precision - 1) - exponent + 1);
4081 if (digits2 == NULL)
4086 if (strlen (digits2) == precision)
4095 /* Here ndigits = precision. */
4097 /* Determine the number of trailing zeroes
4098 that have to be dropped. */
4100 if ((flags & FLAG_ALT) == 0)
4101 while (nzeroes < ndigits
4102 && digits[nzeroes] == '0')
4105 /* The exponent is now determined. */
4107 && exponent < (long)precision)
4109 /* Fixed-point notation:
4110 max(exponent,0)+1 digits, then the
4111 decimal point, then the remaining
4112 digits without trailing zeroes. */
4115 size_t count = exponent + 1;
4116 /* Note: count <= precision = ndigits. */
4117 for (; count > 0; count--)
4118 *p++ = digits[--ndigits];
4119 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4121 *p++ = decimal_point_char ();
4122 while (ndigits > nzeroes)
4125 *p++ = digits[ndigits];
4131 size_t count = -exponent - 1;
4133 *p++ = decimal_point_char ();
4134 for (; count > 0; count--)
4136 while (ndigits > nzeroes)
4139 *p++ = digits[ndigits];
4145 /* Exponential notation. */
4146 *p++ = digits[--ndigits];
4147 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4149 *p++ = decimal_point_char ();
4150 while (ndigits > nzeroes)
4153 *p++ = digits[ndigits];
4156 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4157 # if WIDE_CHAR_VERSION
4159 static const wchar_t decimal_format[] =
4160 /* Produce the same number of exponent digits
4161 as the native printf implementation. */
4162 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4163 { '%', '+', '.', '3', 'd', '\0' };
4165 { '%', '+', '.', '2', 'd', '\0' };
4167 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4173 static const char decimal_format[] =
4174 /* Produce the same number of exponent digits
4175 as the native printf implementation. */
4176 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4181 if (sizeof (DCHAR_T) == 1)
4183 sprintf ((char *) p, decimal_format, exponent);
4191 sprintf (expbuf, decimal_format, exponent);
4192 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4205 /* arg is finite. */
4211 if (dp->conversion == 'f' || dp->conversion == 'F')
4214 if ((flags & FLAG_ALT) || precision > 0)
4216 *p++ = decimal_point_char ();
4217 for (; precision > 0; precision--)
4221 else if (dp->conversion == 'e' || dp->conversion == 'E')
4224 if ((flags & FLAG_ALT) || precision > 0)
4226 *p++ = decimal_point_char ();
4227 for (; precision > 0; precision--)
4230 *p++ = dp->conversion; /* 'e' or 'E' */
4232 /* Produce the same number of exponent digits as
4233 the native printf implementation. */
4234 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4240 else if (dp->conversion == 'g' || dp->conversion == 'G')
4243 if (flags & FLAG_ALT)
4246 (precision > 0 ? precision - 1 : 0);
4247 *p++ = decimal_point_char ();
4248 for (; ndigits > 0; --ndigits)
4260 /* The generated string now extends from tmp to p, with the
4261 zero padding insertion point being at pad_ptr. */
4262 if (has_width && p - tmp < width)
4264 size_t pad = width - (p - tmp);
4265 DCHAR_T *end = p + pad;
4267 if (flags & FLAG_LEFT)
4269 /* Pad with spaces on the right. */
4270 for (; pad > 0; pad--)
4273 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4275 /* Pad with zeroes. */
4280 for (; pad > 0; pad--)
4285 /* Pad with spaces on the left. */
4290 for (; pad > 0; pad--)
4298 size_t count = p - tmp;
4300 if (count >= tmp_length)
4301 /* tmp_length was incorrectly calculated - fix the
4305 /* Make room for the result. */
4306 if (count >= allocated - length)
4308 size_t n = xsum (length, count);
4310 ENSURE_ALLOCATION (n);
4313 /* Append the result. */
4314 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4323 arg_type type = a.arg[dp->arg_index].type;
4324 int flags = dp->flags;
4325 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4329 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4333 #if NEED_PRINTF_UNBOUNDED_PRECISION
4336 # define prec_ourselves 0
4338 #if NEED_PRINTF_FLAG_LEFTADJUST
4339 # define pad_ourselves 1
4340 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4343 # define pad_ourselves 0
4346 unsigned int prefix_count;
4347 int prefixes[2] IF_LINT (= { 0 });
4350 TCHAR_T tmpbuf[700];
4354 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4357 if (dp->width_start != dp->width_end)
4359 if (dp->width_arg_index != ARG_NONE)
4363 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4365 arg = a.arg[dp->width_arg_index].a.a_int;
4368 /* "A negative field width is taken as a '-' flag
4369 followed by a positive field width." */
4371 width = (unsigned int) (-arg);
4378 const FCHAR_T *digitp = dp->width_start;
4381 width = xsum (xtimes (width, 10), *digitp++ - '0');
4382 while (digitp != dp->width_end);
4388 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4391 if (dp->precision_start != dp->precision_end)
4393 if (dp->precision_arg_index != ARG_NONE)
4397 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4399 arg = a.arg[dp->precision_arg_index].a.a_int;
4400 /* "A negative precision is taken as if the precision
4410 const FCHAR_T *digitp = dp->precision_start + 1;
4413 while (digitp != dp->precision_end)
4414 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4420 /* Decide whether to handle the precision ourselves. */
4421 #if NEED_PRINTF_UNBOUNDED_PRECISION
4422 switch (dp->conversion)
4424 case 'd': case 'i': case 'u':
4426 case 'x': case 'X': case 'p':
4427 prec_ourselves = has_precision && (precision > 0);
4435 /* Decide whether to perform the padding ourselves. */
4436 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4437 switch (dp->conversion)
4439 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4440 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4441 to perform the padding after this conversion. Functions
4442 with unistdio extensions perform the padding based on
4443 character count rather than element count. */
4446 # if NEED_PRINTF_FLAG_ZERO
4447 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4453 pad_ourselves = prec_ourselves;
4459 /* Allocate a temporary buffer of sufficient size for calling
4462 switch (dp->conversion)
4465 case 'd': case 'i': case 'u':
4466 # if HAVE_LONG_LONG_INT
4467 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4469 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4470 * 0.30103 /* binary -> decimal */
4472 + 1; /* turn floor into ceil */
4475 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4477 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4478 * 0.30103 /* binary -> decimal */
4480 + 1; /* turn floor into ceil */
4483 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4484 * 0.30103 /* binary -> decimal */
4486 + 1; /* turn floor into ceil */
4487 if (tmp_length < precision)
4488 tmp_length = precision;
4489 /* Multiply by 2, as an estimate for FLAG_GROUP. */
4490 tmp_length = xsum (tmp_length, tmp_length);
4491 /* Add 1, to account for a leading sign. */
4492 tmp_length = xsum (tmp_length, 1);
4496 # if HAVE_LONG_LONG_INT
4497 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4499 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4500 * 0.333334 /* binary -> octal */
4502 + 1; /* turn floor into ceil */
4505 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4507 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4508 * 0.333334 /* binary -> octal */
4510 + 1; /* turn floor into ceil */
4513 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4514 * 0.333334 /* binary -> octal */
4516 + 1; /* turn floor into ceil */
4517 if (tmp_length < precision)
4518 tmp_length = precision;
4519 /* Add 1, to account for a leading sign. */
4520 tmp_length = xsum (tmp_length, 1);
4524 # if HAVE_LONG_LONG_INT
4525 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4527 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4528 * 0.25 /* binary -> hexadecimal */
4530 + 1; /* turn floor into ceil */
4533 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4535 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4536 * 0.25 /* binary -> hexadecimal */
4538 + 1; /* turn floor into ceil */
4541 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4542 * 0.25 /* binary -> hexadecimal */
4544 + 1; /* turn floor into ceil */
4545 if (tmp_length < precision)
4546 tmp_length = precision;
4547 /* Add 2, to account for a leading sign or alternate form. */
4548 tmp_length = xsum (tmp_length, 2);
4552 if (type == TYPE_LONGDOUBLE)
4554 (unsigned int) (LDBL_MAX_EXP
4555 * 0.30103 /* binary -> decimal */
4556 * 2 /* estimate for FLAG_GROUP */
4558 + 1 /* turn floor into ceil */
4559 + 10; /* sign, decimal point etc. */
4562 (unsigned int) (DBL_MAX_EXP
4563 * 0.30103 /* binary -> decimal */
4564 * 2 /* estimate for FLAG_GROUP */
4566 + 1 /* turn floor into ceil */
4567 + 10; /* sign, decimal point etc. */
4568 tmp_length = xsum (tmp_length, precision);
4571 case 'e': case 'E': case 'g': case 'G':
4573 12; /* sign, decimal point, exponent etc. */
4574 tmp_length = xsum (tmp_length, precision);
4578 if (type == TYPE_LONGDOUBLE)
4580 (unsigned int) (LDBL_DIG
4581 * 0.831 /* decimal -> hexadecimal */
4583 + 1; /* turn floor into ceil */
4586 (unsigned int) (DBL_DIG
4587 * 0.831 /* decimal -> hexadecimal */
4589 + 1; /* turn floor into ceil */
4590 if (tmp_length < precision)
4591 tmp_length = precision;
4592 /* Account for sign, decimal point etc. */
4593 tmp_length = xsum (tmp_length, 12);
4597 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
4598 if (type == TYPE_WIDE_CHAR)
4599 tmp_length = MB_CUR_MAX;
4607 if (type == TYPE_WIDE_STRING)
4609 # if WIDE_CHAR_VERSION
4610 /* ISO C says about %ls in fwprintf:
4611 "If the precision is not specified or is greater
4612 than the size of the array, the array shall
4613 contain a null wide character."
4614 So if there is a precision, we must not use
4616 const wchar_t *arg =
4617 a.arg[dp->arg_index].a.a_wide_string;
4620 tmp_length = local_wcsnlen (arg, precision);
4622 tmp_length = local_wcslen (arg);
4624 /* ISO C says about %ls in fprintf:
4625 "If a precision is specified, no more than that
4626 many bytes are written (including shift
4627 sequences, if any), and the array shall contain
4628 a null wide character if, to equal the
4629 multibyte character sequence length given by
4630 the precision, the function would need to
4631 access a wide character one past the end of the
4633 So if there is a precision, we must not use
4635 /* This case has already been handled above. */
4642 # if WIDE_CHAR_VERSION
4643 /* ISO C says about %s in fwprintf:
4644 "If the precision is not specified or is greater
4645 than the size of the converted array, the
4646 converted array shall contain a null wide
4648 So if there is a precision, we must not use
4650 /* This case has already been handled above. */
4653 /* ISO C says about %s in fprintf:
4654 "If the precision is not specified or greater
4655 than the size of the array, the array shall
4656 contain a null character."
4657 So if there is a precision, we must not use
4659 const char *arg = a.arg[dp->arg_index].a.a_string;
4662 tmp_length = local_strnlen (arg, precision);
4664 tmp_length = strlen (arg);
4671 (unsigned int) (sizeof (void *) * CHAR_BIT
4672 * 0.25 /* binary -> hexadecimal */
4674 + 1 /* turn floor into ceil */
4675 + 2; /* account for leading 0x */
4684 # if ENABLE_UNISTDIO
4685 /* Padding considers the number of characters, therefore
4686 the number of elements after padding may be
4687 > max (tmp_length, width)
4689 <= tmp_length + width. */
4690 tmp_length = xsum (tmp_length, width);
4692 /* Padding considers the number of elements,
4694 if (tmp_length < width)
4699 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
4702 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4706 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4708 if (size_overflow_p (tmp_memsize))
4709 /* Overflow, would lead to out of memory. */
4711 tmp = (TCHAR_T *) malloc (tmp_memsize);
4713 /* Out of memory. */
4718 /* Construct the format string for calling snprintf or
4722 #if NEED_PRINTF_FLAG_GROUPING
4723 /* The underlying implementation doesn't support the ' flag.
4724 Produce no grouping characters in this case; this is
4725 acceptable because the grouping is locale dependent. */
4727 if (flags & FLAG_GROUP)
4730 if (flags & FLAG_LEFT)
4732 if (flags & FLAG_SHOWSIGN)
4734 if (flags & FLAG_SPACE)
4736 if (flags & FLAG_ALT)
4740 if (flags & FLAG_ZERO)
4742 if (dp->width_start != dp->width_end)
4744 size_t n = dp->width_end - dp->width_start;
4745 /* The width specification is known to consist only
4746 of standard ASCII characters. */
4747 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4749 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4754 const FCHAR_T *mp = dp->width_start;
4756 *fbp++ = (unsigned char) *mp++;
4761 if (!prec_ourselves)
4763 if (dp->precision_start != dp->precision_end)
4765 size_t n = dp->precision_end - dp->precision_start;
4766 /* The precision specification is known to consist only
4767 of standard ASCII characters. */
4768 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4770 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4775 const FCHAR_T *mp = dp->precision_start;
4777 *fbp++ = (unsigned char) *mp++;
4785 #if HAVE_LONG_LONG_INT
4786 case TYPE_LONGLONGINT:
4787 case TYPE_ULONGLONGINT:
4788 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4801 case TYPE_WIDE_CHAR:
4804 case TYPE_WIDE_STRING:
4808 case TYPE_LONGDOUBLE:
4814 #if NEED_PRINTF_DIRECTIVE_F
4815 if (dp->conversion == 'F')
4819 *fbp = dp->conversion;
4821 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4826 /* On glibc2 systems from glibc >= 2.3 - probably also older
4827 ones - we know that snprintf's returns value conforms to
4828 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4829 Therefore we can avoid using %n in this situation.
4830 On glibc2 systems from 2004-10-18 or newer, the use of %n
4831 in format strings in writable memory may crash the program
4832 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4833 in this situation. */
4834 /* On native Win32 systems (such as mingw), we can avoid using
4836 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4837 snprintf does not write more than the specified number
4838 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4839 '4', '5', '6' into buf, not '4', '5', '\0'.)
4840 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4841 allows us to recognize the case of an insufficient
4842 buffer size: it returns -1 in this case.
4843 On native Win32 systems (such as mingw) where the OS is
4844 Windows Vista, the use of %n in format strings by default
4845 crashes the program. See
4846 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4847 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4848 So we should avoid %n in this situation. */
4855 /* Construct the arguments for calling snprintf or sprintf. */
4857 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4859 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4861 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4863 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4865 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4867 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4871 /* The SNPRINTF result is appended after result[0..length].
4872 The latter is an array of DCHAR_T; SNPRINTF appends an
4873 array of TCHAR_T to it. This is possible because
4874 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4875 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4876 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4877 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4878 where an snprintf() with maxlen==1 acts like sprintf(). */
4879 ENSURE_ALLOCATION (xsum (length,
4880 (2 + TCHARS_PER_DCHAR - 1)
4881 / TCHARS_PER_DCHAR));
4882 /* Prepare checking whether snprintf returns the count
4884 *(TCHAR_T *) (result + length) = '\0';
4893 size_t maxlen = allocated - length;
4894 /* SNPRINTF can fail if its second argument is
4896 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4897 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4898 maxlen = maxlen * TCHARS_PER_DCHAR;
4899 # define SNPRINTF_BUF(arg) \
4900 switch (prefix_count) \
4903 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4908 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4910 prefixes[0], arg, &count); \
4913 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4915 prefixes[0], prefixes[1], arg, \
4922 # define SNPRINTF_BUF(arg) \
4923 switch (prefix_count) \
4926 count = sprintf (tmp, buf, arg); \
4929 count = sprintf (tmp, buf, prefixes[0], arg); \
4932 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4944 int arg = a.arg[dp->arg_index].a.a_schar;
4950 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4956 int arg = a.arg[dp->arg_index].a.a_short;
4962 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4968 int arg = a.arg[dp->arg_index].a.a_int;
4974 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4980 long int arg = a.arg[dp->arg_index].a.a_longint;
4986 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4990 #if HAVE_LONG_LONG_INT
4991 case TYPE_LONGLONGINT:
4993 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4997 case TYPE_ULONGLONGINT:
4999 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
5006 double arg = a.arg[dp->arg_index].a.a_double;
5010 case TYPE_LONGDOUBLE:
5012 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5018 int arg = a.arg[dp->arg_index].a.a_char;
5023 case TYPE_WIDE_CHAR:
5025 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5032 const char *arg = a.arg[dp->arg_index].a.a_string;
5037 case TYPE_WIDE_STRING:
5039 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5046 void *arg = a.arg[dp->arg_index].a.a_pointer;
5055 /* Portability: Not all implementations of snprintf()
5056 are ISO C 99 compliant. Determine the number of
5057 bytes that snprintf() has produced or would have
5061 /* Verify that snprintf() has NUL-terminated its
5064 && ((TCHAR_T *) (result + length)) [count] != '\0')
5066 /* Portability hack. */
5067 if (retcount > count)
5072 /* snprintf() doesn't understand the '%n'
5076 /* Don't use the '%n' directive; instead, look
5077 at the snprintf() return value. */
5083 /* Look at the snprintf() return value. */
5086 /* HP-UX 10.20 snprintf() is doubly deficient:
5087 It doesn't understand the '%n' directive,
5088 *and* it returns -1 (rather than the length
5089 that would have been required) when the
5090 buffer is too small. */
5091 size_t bigger_need =
5092 xsum (xtimes (allocated, 2), 12);
5093 ENSURE_ALLOCATION (bigger_need);
5102 /* Attempt to handle failure. */
5105 if (!(result == resultbuf || result == NULL))
5107 if (buf_malloced != NULL)
5108 free (buf_malloced);
5115 /* Handle overflow of the allocated buffer.
5116 If such an overflow occurs, a C99 compliant snprintf()
5117 returns a count >= maxlen. However, a non-compliant
5118 snprintf() function returns only count = maxlen - 1. To
5119 cover both cases, test whether count >= maxlen - 1. */
5120 if ((unsigned int) count + 1 >= maxlen)
5122 /* If maxlen already has attained its allowed maximum,
5123 allocating more memory will not increase maxlen.
5124 Instead of looping, bail out. */
5125 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5129 /* Need at least (count + 1) * sizeof (TCHAR_T)
5130 bytes. (The +1 is for the trailing NUL.)
5131 But ask for (count + 2) * sizeof (TCHAR_T)
5132 bytes, so that in the next round, we likely get
5133 maxlen > (unsigned int) count + 1
5134 and so we don't get here again.
5135 And allocate proportionally, to avoid looping
5136 eternally if snprintf() reports a too small
5140 ((unsigned int) count + 2
5141 + TCHARS_PER_DCHAR - 1)
5142 / TCHARS_PER_DCHAR),
5143 xtimes (allocated, 2));
5145 ENSURE_ALLOCATION (n);
5151 #if NEED_PRINTF_UNBOUNDED_PRECISION
5154 /* Handle the precision. */
5157 (TCHAR_T *) (result + length);
5161 size_t prefix_count;
5165 /* Put the additional zeroes after the sign. */
5167 && (*prec_ptr == '-' || *prec_ptr == '+'
5168 || *prec_ptr == ' '))
5170 /* Put the additional zeroes after the 0x prefix if
5171 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5173 && prec_ptr[0] == '0'
5174 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5177 move = count - prefix_count;
5178 if (precision > move)
5180 /* Insert zeroes. */
5181 size_t insert = precision - move;
5187 (count + insert + TCHARS_PER_DCHAR - 1)
5188 / TCHARS_PER_DCHAR);
5189 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5190 ENSURE_ALLOCATION (n);
5191 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5192 prec_ptr = (TCHAR_T *) (result + length);
5195 prec_end = prec_ptr + count;
5196 prec_ptr += prefix_count;
5198 while (prec_end > prec_ptr)
5201 prec_end[insert] = prec_end[0];
5207 while (prec_end > prec_ptr);
5215 if (count >= tmp_length)
5216 /* tmp_length was incorrectly calculated - fix the
5222 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5223 if (dp->conversion == 'c' || dp->conversion == 's')
5225 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5227 The result string is not certainly ASCII. */
5228 const TCHAR_T *tmpsrc;
5231 /* This code assumes that TCHAR_T is 'char'. */
5232 typedef int TCHAR_T_verify
5233 [2 * (sizeof (TCHAR_T) == 1) - 1];
5235 tmpsrc = (TCHAR_T *) (result + length);
5240 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5241 iconveh_question_mark,
5247 int saved_errno = errno;
5248 if (!(result == resultbuf || result == NULL))
5250 if (buf_malloced != NULL)
5251 free (buf_malloced);
5253 errno = saved_errno;
5256 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5257 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5263 /* The result string is ASCII.
5264 Simple 1:1 conversion. */
5266 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5267 no-op conversion, in-place on the array starting
5268 at (result + length). */
5269 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5272 const TCHAR_T *tmpsrc;
5277 if (result == resultbuf)
5279 tmpsrc = (TCHAR_T *) (result + length);
5280 /* ENSURE_ALLOCATION will not move tmpsrc
5281 (because it's part of resultbuf). */
5282 ENSURE_ALLOCATION (xsum (length, count));
5286 /* ENSURE_ALLOCATION will move the array
5287 (because it uses realloc(). */
5288 ENSURE_ALLOCATION (xsum (length, count));
5289 tmpsrc = (TCHAR_T *) (result + length);
5293 ENSURE_ALLOCATION (xsum (length, count));
5295 tmpdst = result + length;
5296 /* Copy backwards, because of overlapping. */
5299 for (n = count; n > 0; n--)
5300 *--tmpdst = (unsigned char) *--tmpsrc;
5305 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5306 /* Make room for the result. */
5307 if (count > allocated - length)
5309 /* Need at least count elements. But allocate
5312 xmax (xsum (length, count), xtimes (allocated, 2));
5314 ENSURE_ALLOCATION (n);
5318 /* Here count <= allocated - length. */
5320 /* Perform padding. */
5321 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5322 if (pad_ourselves && has_width)
5325 # if ENABLE_UNISTDIO
5326 /* Outside POSIX, it's preferrable to compare the width
5327 against the number of _characters_ of the converted
5329 w = DCHAR_MBSNLEN (result + length, count);
5331 /* The width is compared against the number of _bytes_
5332 of the converted value, says POSIX. */
5337 size_t pad = width - w;
5339 /* Make room for the result. */
5340 if (xsum (count, pad) > allocated - length)
5342 /* Need at least count + pad elements. But
5343 allocate proportionally. */
5345 xmax (xsum3 (length, count, pad),
5346 xtimes (allocated, 2));
5350 ENSURE_ALLOCATION (n);
5353 ENSURE_ALLOCATION (n);
5356 /* Here count + pad <= allocated - length. */
5359 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5360 DCHAR_T * const rp = result + length;
5362 DCHAR_T * const rp = tmp;
5364 DCHAR_T *p = rp + count;
5365 DCHAR_T *end = p + pad;
5367 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5368 if (dp->conversion == 'c'
5369 || dp->conversion == 's')
5370 /* No zero-padding for string directives. */
5375 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5376 /* No zero-padding of "inf" and "nan". */
5377 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5378 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5381 /* The generated string now extends from rp to p,
5382 with the zero padding insertion point being at
5385 count = count + pad; /* = end - rp */
5387 if (flags & FLAG_LEFT)
5389 /* Pad with spaces on the right. */
5390 for (; pad > 0; pad--)
5393 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5395 /* Pad with zeroes. */
5400 for (; pad > 0; pad--)
5405 /* Pad with spaces on the left. */
5410 for (; pad > 0; pad--)
5418 /* Here still count <= allocated - length. */
5420 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5421 /* The snprintf() result did fit. */
5423 /* Append the sprintf() result. */
5424 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5431 #if NEED_PRINTF_DIRECTIVE_F
5432 if (dp->conversion == 'F')
5434 /* Convert the %f result to upper case for %F. */
5435 DCHAR_T *rp = result + length;
5437 for (rc = count; rc > 0; rc--, rp++)
5438 if (*rp >= 'a' && *rp <= 'z')
5439 *rp = *rp - 'a' + 'A';
5450 /* Add the final NUL. */
5451 ENSURE_ALLOCATION (xsum (length, 1));
5452 result[length] = '\0';
5454 if (result != resultbuf && length + 1 < allocated)
5456 /* Shrink the allocated memory if possible. */
5459 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5464 if (buf_malloced != NULL)
5465 free (buf_malloced);
5468 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5469 says that snprintf() fails with errno = EOVERFLOW in this case, but
5470 that's only because snprintf() returns an 'int'. This function does
5471 not have this limitation. */
5476 if (!(result == resultbuf || result == NULL))
5478 if (buf_malloced != NULL)
5479 free (buf_malloced);
5486 if (!(result == resultbuf || result == NULL))
5488 if (buf_malloced != NULL)
5489 free (buf_malloced);
5497 #undef TCHARS_PER_DCHAR
5505 #undef DCHAR_IS_TCHAR