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);
2608 /* Inconsistency. */
2610 ENSURE_ALLOCATION (xsum (length, count));
2611 memcpy (result + length, cbuf, count);
2617 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2618 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2620 length += tmpdst_len;
2623 if (has_width && width > w
2624 && (dp->flags & FLAG_LEFT))
2626 size_t n = width - w;
2627 ENSURE_ALLOCATION (xsum (length, n));
2628 DCHAR_SET (result + length, ' ', n);
2635 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2636 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2637 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2639 # if NEED_PRINTF_DOUBLE
2640 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2642 # if NEED_PRINTF_LONG_DOUBLE
2643 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2649 arg_type type = a.arg[dp->arg_index].type;
2650 int flags = dp->flags;
2656 DCHAR_T tmpbuf[700];
2663 if (dp->width_start != dp->width_end)
2665 if (dp->width_arg_index != ARG_NONE)
2669 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2671 arg = a.arg[dp->width_arg_index].a.a_int;
2674 /* "A negative field width is taken as a '-' flag
2675 followed by a positive field width." */
2677 width = (unsigned int) (-arg);
2684 const FCHAR_T *digitp = dp->width_start;
2687 width = xsum (xtimes (width, 10), *digitp++ - '0');
2688 while (digitp != dp->width_end);
2695 if (dp->precision_start != dp->precision_end)
2697 if (dp->precision_arg_index != ARG_NONE)
2701 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2703 arg = a.arg[dp->precision_arg_index].a.a_int;
2704 /* "A negative precision is taken as if the precision
2714 const FCHAR_T *digitp = dp->precision_start + 1;
2717 while (digitp != dp->precision_end)
2718 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2723 /* Allocate a temporary buffer of sufficient size. */
2724 if (type == TYPE_LONGDOUBLE)
2726 (unsigned int) ((LDBL_DIG + 1)
2727 * 0.831 /* decimal -> hexadecimal */
2729 + 1; /* turn floor into ceil */
2732 (unsigned int) ((DBL_DIG + 1)
2733 * 0.831 /* decimal -> hexadecimal */
2735 + 1; /* turn floor into ceil */
2736 if (tmp_length < precision)
2737 tmp_length = precision;
2738 /* Account for sign, decimal point etc. */
2739 tmp_length = xsum (tmp_length, 12);
2741 if (tmp_length < width)
2744 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2746 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2750 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2752 if (size_overflow_p (tmp_memsize))
2753 /* Overflow, would lead to out of memory. */
2755 tmp = (DCHAR_T *) malloc (tmp_memsize);
2757 /* Out of memory. */
2763 if (type == TYPE_LONGDOUBLE)
2765 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2766 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2770 if (dp->conversion == 'A')
2772 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2776 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2782 DECL_LONG_DOUBLE_ROUNDING
2784 BEGIN_LONG_DOUBLE_ROUNDING ();
2786 if (signbit (arg)) /* arg < 0.0L or negative zero */
2794 else if (flags & FLAG_SHOWSIGN)
2796 else if (flags & FLAG_SPACE)
2799 if (arg > 0.0L && arg + arg == arg)
2801 if (dp->conversion == 'A')
2803 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2807 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2813 long double mantissa;
2816 mantissa = printf_frexpl (arg, &exponent);
2824 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2826 /* Round the mantissa. */
2827 long double tail = mantissa;
2830 for (q = precision; ; q--)
2832 int digit = (int) tail;
2836 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2845 for (q = precision; q > 0; q--)
2851 *p++ = dp->conversion - 'A' + 'X';
2856 digit = (int) mantissa;
2859 if ((flags & FLAG_ALT)
2860 || mantissa > 0.0L || precision > 0)
2862 *p++ = decimal_point_char ();
2863 /* This loop terminates because we assume
2864 that FLT_RADIX is a power of 2. */
2865 while (mantissa > 0.0L)
2868 digit = (int) mantissa;
2873 : dp->conversion - 10);
2877 while (precision > 0)
2884 *p++ = dp->conversion - 'A' + 'P';
2885 # if WIDE_CHAR_VERSION
2887 static const wchar_t decimal_format[] =
2888 { '%', '+', 'd', '\0' };
2889 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2894 if (sizeof (DCHAR_T) == 1)
2896 sprintf ((char *) p, "%+d", exponent);
2904 sprintf (expbuf, "%+d", exponent);
2905 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2911 END_LONG_DOUBLE_ROUNDING ();
2919 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2920 double arg = a.arg[dp->arg_index].a.a_double;
2924 if (dp->conversion == 'A')
2926 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2930 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2937 if (signbit (arg)) /* arg < 0.0 or negative zero */
2945 else if (flags & FLAG_SHOWSIGN)
2947 else if (flags & FLAG_SPACE)
2950 if (arg > 0.0 && arg + arg == arg)
2952 if (dp->conversion == 'A')
2954 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2958 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2967 mantissa = printf_frexp (arg, &exponent);
2975 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2977 /* Round the mantissa. */
2978 double tail = mantissa;
2981 for (q = precision; ; q--)
2983 int digit = (int) tail;
2987 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2996 for (q = precision; q > 0; q--)
3002 *p++ = dp->conversion - 'A' + 'X';
3007 digit = (int) mantissa;
3010 if ((flags & FLAG_ALT)
3011 || mantissa > 0.0 || precision > 0)
3013 *p++ = decimal_point_char ();
3014 /* This loop terminates because we assume
3015 that FLT_RADIX is a power of 2. */
3016 while (mantissa > 0.0)
3019 digit = (int) mantissa;
3024 : dp->conversion - 10);
3028 while (precision > 0)
3035 *p++ = dp->conversion - 'A' + 'P';
3036 # if WIDE_CHAR_VERSION
3038 static const wchar_t decimal_format[] =
3039 { '%', '+', 'd', '\0' };
3040 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3045 if (sizeof (DCHAR_T) == 1)
3047 sprintf ((char *) p, "%+d", exponent);
3055 sprintf (expbuf, "%+d", exponent);
3056 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3066 /* The generated string now extends from tmp to p, with the
3067 zero padding insertion point being at pad_ptr. */
3068 if (has_width && p - tmp < width)
3070 size_t pad = width - (p - tmp);
3071 DCHAR_T *end = p + pad;
3073 if (flags & FLAG_LEFT)
3075 /* Pad with spaces on the right. */
3076 for (; pad > 0; pad--)
3079 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3081 /* Pad with zeroes. */
3086 for (; pad > 0; pad--)
3091 /* Pad with spaces on the left. */
3096 for (; pad > 0; pad--)
3104 size_t count = p - tmp;
3106 if (count >= tmp_length)
3107 /* tmp_length was incorrectly calculated - fix the
3111 /* Make room for the result. */
3112 if (count >= allocated - length)
3114 size_t n = xsum (length, count);
3116 ENSURE_ALLOCATION (n);
3119 /* Append the result. */
3120 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3127 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3128 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3129 || dp->conversion == 'e' || dp->conversion == 'E'
3130 || dp->conversion == 'g' || dp->conversion == 'G'
3131 || dp->conversion == 'a' || dp->conversion == 'A')
3133 # if NEED_PRINTF_DOUBLE
3134 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3135 # elif NEED_PRINTF_INFINITE_DOUBLE
3136 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3137 /* The systems (mingw) which produce wrong output
3138 for Inf, -Inf, and NaN also do so for -0.0.
3139 Therefore we treat this case here as well. */
3140 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3142 # if NEED_PRINTF_LONG_DOUBLE
3143 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3144 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3145 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3146 /* Some systems produce wrong output for Inf,
3147 -Inf, and NaN. Some systems in this category
3148 (IRIX 5.3) also do so for -0.0. Therefore we
3149 treat this case here as well. */
3150 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3154 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3155 arg_type type = a.arg[dp->arg_index].type;
3157 int flags = dp->flags;
3163 DCHAR_T tmpbuf[700];
3170 if (dp->width_start != dp->width_end)
3172 if (dp->width_arg_index != ARG_NONE)
3176 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3178 arg = a.arg[dp->width_arg_index].a.a_int;
3181 /* "A negative field width is taken as a '-' flag
3182 followed by a positive field width." */
3184 width = (unsigned int) (-arg);
3191 const FCHAR_T *digitp = dp->width_start;
3194 width = xsum (xtimes (width, 10), *digitp++ - '0');
3195 while (digitp != dp->width_end);
3202 if (dp->precision_start != dp->precision_end)
3204 if (dp->precision_arg_index != ARG_NONE)
3208 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3210 arg = a.arg[dp->precision_arg_index].a.a_int;
3211 /* "A negative precision is taken as if the precision
3221 const FCHAR_T *digitp = dp->precision_start + 1;
3224 while (digitp != dp->precision_end)
3225 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3230 /* POSIX specifies the default precision to be 6 for %f, %F,
3231 %e, %E, but not for %g, %G. Implementations appear to use
3232 the same default precision also for %g, %G. But for %a, %A,
3233 the default precision is 0. */
3235 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3238 /* Allocate a temporary buffer of sufficient size. */
3239 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3240 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3241 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3242 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3243 # elif NEED_PRINTF_LONG_DOUBLE
3244 tmp_length = LDBL_DIG + 1;
3245 # elif NEED_PRINTF_DOUBLE
3246 tmp_length = DBL_DIG + 1;
3250 if (tmp_length < precision)
3251 tmp_length = precision;
3252 # if NEED_PRINTF_LONG_DOUBLE
3253 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3254 if (type == TYPE_LONGDOUBLE)
3256 if (dp->conversion == 'f' || dp->conversion == 'F')
3258 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3259 if (!(isnanl (arg) || arg + arg == arg))
3261 /* arg is finite and nonzero. */
3262 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3263 if (exponent >= 0 && tmp_length < exponent + precision)
3264 tmp_length = exponent + precision;
3268 # if NEED_PRINTF_DOUBLE
3269 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3270 if (type == TYPE_DOUBLE)
3272 if (dp->conversion == 'f' || dp->conversion == 'F')
3274 double arg = a.arg[dp->arg_index].a.a_double;
3275 if (!(isnand (arg) || arg + arg == arg))
3277 /* arg is finite and nonzero. */
3278 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3279 if (exponent >= 0 && tmp_length < exponent + precision)
3280 tmp_length = exponent + precision;
3284 /* Account for sign, decimal point etc. */
3285 tmp_length = xsum (tmp_length, 12);
3287 if (tmp_length < width)
3290 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3292 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3296 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3298 if (size_overflow_p (tmp_memsize))
3299 /* Overflow, would lead to out of memory. */
3301 tmp = (DCHAR_T *) malloc (tmp_memsize);
3303 /* Out of memory. */
3310 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3311 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3312 if (type == TYPE_LONGDOUBLE)
3315 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3319 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3321 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3325 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3331 DECL_LONG_DOUBLE_ROUNDING
3333 BEGIN_LONG_DOUBLE_ROUNDING ();
3335 if (signbit (arg)) /* arg < 0.0L or negative zero */
3343 else if (flags & FLAG_SHOWSIGN)
3345 else if (flags & FLAG_SPACE)
3348 if (arg > 0.0L && arg + arg == arg)
3350 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3352 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3356 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3361 # if NEED_PRINTF_LONG_DOUBLE
3364 if (dp->conversion == 'f' || dp->conversion == 'F')
3370 scale10_round_decimal_long_double (arg, precision);
3373 END_LONG_DOUBLE_ROUNDING ();
3376 ndigits = strlen (digits);
3378 if (ndigits > precision)
3382 *p++ = digits[ndigits];
3384 while (ndigits > precision);
3387 /* Here ndigits <= precision. */
3388 if ((flags & FLAG_ALT) || precision > 0)
3390 *p++ = decimal_point_char ();
3391 for (; precision > ndigits; precision--)
3396 *p++ = digits[ndigits];
3402 else if (dp->conversion == 'e' || dp->conversion == 'E')
3410 if ((flags & FLAG_ALT) || precision > 0)
3412 *p++ = decimal_point_char ();
3413 for (; precision > 0; precision--)
3424 exponent = floorlog10l (arg);
3429 scale10_round_decimal_long_double (arg,
3430 (int)precision - exponent);
3433 END_LONG_DOUBLE_ROUNDING ();
3436 ndigits = strlen (digits);
3438 if (ndigits == precision + 1)
3440 if (ndigits < precision
3441 || ndigits > precision + 2)
3442 /* The exponent was not guessed
3443 precisely enough. */
3446 /* None of two values of exponent is
3447 the right one. Prevent an endless
3451 if (ndigits == precision)
3457 /* Here ndigits = precision+1. */
3458 if (is_borderline (digits, precision))
3460 /* Maybe the exponent guess was too high
3461 and a smaller exponent can be reached
3462 by turning a 10...0 into 9...9x. */
3464 scale10_round_decimal_long_double (arg,
3465 (int)precision - exponent + 1);
3466 if (digits2 == NULL)
3469 END_LONG_DOUBLE_ROUNDING ();
3472 if (strlen (digits2) == precision + 1)
3481 /* Here ndigits = precision+1. */
3483 *p++ = digits[--ndigits];
3484 if ((flags & FLAG_ALT) || precision > 0)
3486 *p++ = decimal_point_char ();
3490 *p++ = digits[ndigits];
3497 *p++ = dp->conversion; /* 'e' or 'E' */
3498 # if WIDE_CHAR_VERSION
3500 static const wchar_t decimal_format[] =
3501 { '%', '+', '.', '2', 'd', '\0' };
3502 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3507 if (sizeof (DCHAR_T) == 1)
3509 sprintf ((char *) p, "%+.2d", exponent);
3517 sprintf (expbuf, "%+.2d", exponent);
3518 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3523 else if (dp->conversion == 'g' || dp->conversion == 'G')
3527 /* precision >= 1. */
3530 /* The exponent is 0, >= -4, < precision.
3531 Use fixed-point notation. */
3533 size_t ndigits = precision;
3534 /* Number of trailing zeroes that have to be
3537 (flags & FLAG_ALT ? 0 : precision - 1);
3541 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3543 *p++ = decimal_point_char ();
3544 while (ndigits > nzeroes)
3560 exponent = floorlog10l (arg);
3565 scale10_round_decimal_long_double (arg,
3566 (int)(precision - 1) - exponent);
3569 END_LONG_DOUBLE_ROUNDING ();
3572 ndigits = strlen (digits);
3574 if (ndigits == precision)
3576 if (ndigits < precision - 1
3577 || ndigits > precision + 1)
3578 /* The exponent was not guessed
3579 precisely enough. */
3582 /* None of two values of exponent is
3583 the right one. Prevent an endless
3587 if (ndigits < precision)
3593 /* Here ndigits = precision. */
3594 if (is_borderline (digits, precision - 1))
3596 /* Maybe the exponent guess was too high
3597 and a smaller exponent can be reached
3598 by turning a 10...0 into 9...9x. */
3600 scale10_round_decimal_long_double (arg,
3601 (int)(precision - 1) - exponent + 1);
3602 if (digits2 == NULL)
3605 END_LONG_DOUBLE_ROUNDING ();
3608 if (strlen (digits2) == precision)
3617 /* Here ndigits = precision. */
3619 /* Determine the number of trailing zeroes
3620 that have to be dropped. */
3622 if ((flags & FLAG_ALT) == 0)
3623 while (nzeroes < ndigits
3624 && digits[nzeroes] == '0')
3627 /* The exponent is now determined. */
3629 && exponent < (long)precision)
3631 /* Fixed-point notation:
3632 max(exponent,0)+1 digits, then the
3633 decimal point, then the remaining
3634 digits without trailing zeroes. */
3637 size_t count = exponent + 1;
3638 /* Note: count <= precision = ndigits. */
3639 for (; count > 0; count--)
3640 *p++ = digits[--ndigits];
3641 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3643 *p++ = decimal_point_char ();
3644 while (ndigits > nzeroes)
3647 *p++ = digits[ndigits];
3653 size_t count = -exponent - 1;
3655 *p++ = decimal_point_char ();
3656 for (; count > 0; count--)
3658 while (ndigits > nzeroes)
3661 *p++ = digits[ndigits];
3667 /* Exponential notation. */
3668 *p++ = digits[--ndigits];
3669 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3671 *p++ = decimal_point_char ();
3672 while (ndigits > nzeroes)
3675 *p++ = digits[ndigits];
3678 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3679 # if WIDE_CHAR_VERSION
3681 static const wchar_t decimal_format[] =
3682 { '%', '+', '.', '2', 'd', '\0' };
3683 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3688 if (sizeof (DCHAR_T) == 1)
3690 sprintf ((char *) p, "%+.2d", exponent);
3698 sprintf (expbuf, "%+.2d", exponent);
3699 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3711 /* arg is finite. */
3717 if (dp->conversion == 'f' || dp->conversion == 'F')
3720 if ((flags & FLAG_ALT) || precision > 0)
3722 *p++ = decimal_point_char ();
3723 for (; precision > 0; precision--)
3727 else if (dp->conversion == 'e' || dp->conversion == 'E')
3730 if ((flags & FLAG_ALT) || precision > 0)
3732 *p++ = decimal_point_char ();
3733 for (; precision > 0; precision--)
3736 *p++ = dp->conversion; /* 'e' or 'E' */
3741 else if (dp->conversion == 'g' || dp->conversion == 'G')
3744 if (flags & FLAG_ALT)
3747 (precision > 0 ? precision - 1 : 0);
3748 *p++ = decimal_point_char ();
3749 for (; ndigits > 0; --ndigits)
3753 else if (dp->conversion == 'a' || dp->conversion == 'A')
3756 *p++ = dp->conversion - 'A' + 'X';
3759 if ((flags & FLAG_ALT) || precision > 0)
3761 *p++ = decimal_point_char ();
3762 for (; precision > 0; precision--)
3765 *p++ = dp->conversion - 'A' + 'P';
3774 END_LONG_DOUBLE_ROUNDING ();
3777 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3781 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3783 double arg = a.arg[dp->arg_index].a.a_double;
3787 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3789 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3793 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3800 if (signbit (arg)) /* arg < 0.0 or negative zero */
3808 else if (flags & FLAG_SHOWSIGN)
3810 else if (flags & FLAG_SPACE)
3813 if (arg > 0.0 && arg + arg == arg)
3815 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3817 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3821 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3826 # if NEED_PRINTF_DOUBLE
3829 if (dp->conversion == 'f' || dp->conversion == 'F')
3835 scale10_round_decimal_double (arg, precision);
3838 ndigits = strlen (digits);
3840 if (ndigits > precision)
3844 *p++ = digits[ndigits];
3846 while (ndigits > precision);
3849 /* Here ndigits <= precision. */
3850 if ((flags & FLAG_ALT) || precision > 0)
3852 *p++ = decimal_point_char ();
3853 for (; precision > ndigits; precision--)
3858 *p++ = digits[ndigits];
3864 else if (dp->conversion == 'e' || dp->conversion == 'E')
3872 if ((flags & FLAG_ALT) || precision > 0)
3874 *p++ = decimal_point_char ();
3875 for (; precision > 0; precision--)
3886 exponent = floorlog10 (arg);
3891 scale10_round_decimal_double (arg,
3892 (int)precision - exponent);
3895 ndigits = strlen (digits);
3897 if (ndigits == precision + 1)
3899 if (ndigits < precision
3900 || ndigits > precision + 2)
3901 /* The exponent was not guessed
3902 precisely enough. */
3905 /* None of two values of exponent is
3906 the right one. Prevent an endless
3910 if (ndigits == precision)
3916 /* Here ndigits = precision+1. */
3917 if (is_borderline (digits, precision))
3919 /* Maybe the exponent guess was too high
3920 and a smaller exponent can be reached
3921 by turning a 10...0 into 9...9x. */
3923 scale10_round_decimal_double (arg,
3924 (int)precision - exponent + 1);
3925 if (digits2 == NULL)
3930 if (strlen (digits2) == precision + 1)
3939 /* Here ndigits = precision+1. */
3941 *p++ = digits[--ndigits];
3942 if ((flags & FLAG_ALT) || precision > 0)
3944 *p++ = decimal_point_char ();
3948 *p++ = digits[ndigits];
3955 *p++ = dp->conversion; /* 'e' or 'E' */
3956 # if WIDE_CHAR_VERSION
3958 static const wchar_t decimal_format[] =
3959 /* Produce the same number of exponent digits
3960 as the native printf implementation. */
3961 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3962 { '%', '+', '.', '3', 'd', '\0' };
3964 { '%', '+', '.', '2', 'd', '\0' };
3966 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3972 static const char decimal_format[] =
3973 /* Produce the same number of exponent digits
3974 as the native printf implementation. */
3975 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3980 if (sizeof (DCHAR_T) == 1)
3982 sprintf ((char *) p, decimal_format, exponent);
3990 sprintf (expbuf, decimal_format, exponent);
3991 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3997 else if (dp->conversion == 'g' || dp->conversion == 'G')
4001 /* precision >= 1. */
4004 /* The exponent is 0, >= -4, < precision.
4005 Use fixed-point notation. */
4007 size_t ndigits = precision;
4008 /* Number of trailing zeroes that have to be
4011 (flags & FLAG_ALT ? 0 : precision - 1);
4015 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4017 *p++ = decimal_point_char ();
4018 while (ndigits > nzeroes)
4034 exponent = floorlog10 (arg);
4039 scale10_round_decimal_double (arg,
4040 (int)(precision - 1) - exponent);
4043 ndigits = strlen (digits);
4045 if (ndigits == precision)
4047 if (ndigits < precision - 1
4048 || ndigits > precision + 1)
4049 /* The exponent was not guessed
4050 precisely enough. */
4053 /* None of two values of exponent is
4054 the right one. Prevent an endless
4058 if (ndigits < precision)
4064 /* Here ndigits = precision. */
4065 if (is_borderline (digits, precision - 1))
4067 /* Maybe the exponent guess was too high
4068 and a smaller exponent can be reached
4069 by turning a 10...0 into 9...9x. */
4071 scale10_round_decimal_double (arg,
4072 (int)(precision - 1) - exponent + 1);
4073 if (digits2 == NULL)
4078 if (strlen (digits2) == precision)
4087 /* Here ndigits = precision. */
4089 /* Determine the number of trailing zeroes
4090 that have to be dropped. */
4092 if ((flags & FLAG_ALT) == 0)
4093 while (nzeroes < ndigits
4094 && digits[nzeroes] == '0')
4097 /* The exponent is now determined. */
4099 && exponent < (long)precision)
4101 /* Fixed-point notation:
4102 max(exponent,0)+1 digits, then the
4103 decimal point, then the remaining
4104 digits without trailing zeroes. */
4107 size_t count = exponent + 1;
4108 /* Note: count <= precision = ndigits. */
4109 for (; count > 0; count--)
4110 *p++ = digits[--ndigits];
4111 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4113 *p++ = decimal_point_char ();
4114 while (ndigits > nzeroes)
4117 *p++ = digits[ndigits];
4123 size_t count = -exponent - 1;
4125 *p++ = decimal_point_char ();
4126 for (; count > 0; count--)
4128 while (ndigits > nzeroes)
4131 *p++ = digits[ndigits];
4137 /* Exponential notation. */
4138 *p++ = digits[--ndigits];
4139 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4141 *p++ = decimal_point_char ();
4142 while (ndigits > nzeroes)
4145 *p++ = digits[ndigits];
4148 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4149 # if WIDE_CHAR_VERSION
4151 static const wchar_t decimal_format[] =
4152 /* Produce the same number of exponent digits
4153 as the native printf implementation. */
4154 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4155 { '%', '+', '.', '3', 'd', '\0' };
4157 { '%', '+', '.', '2', 'd', '\0' };
4159 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4165 static const char decimal_format[] =
4166 /* Produce the same number of exponent digits
4167 as the native printf implementation. */
4168 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4173 if (sizeof (DCHAR_T) == 1)
4175 sprintf ((char *) p, decimal_format, exponent);
4183 sprintf (expbuf, decimal_format, exponent);
4184 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4197 /* arg is finite. */
4203 if (dp->conversion == 'f' || dp->conversion == 'F')
4206 if ((flags & FLAG_ALT) || precision > 0)
4208 *p++ = decimal_point_char ();
4209 for (; precision > 0; precision--)
4213 else if (dp->conversion == 'e' || dp->conversion == 'E')
4216 if ((flags & FLAG_ALT) || precision > 0)
4218 *p++ = decimal_point_char ();
4219 for (; precision > 0; precision--)
4222 *p++ = dp->conversion; /* 'e' or 'E' */
4224 /* Produce the same number of exponent digits as
4225 the native printf implementation. */
4226 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4232 else if (dp->conversion == 'g' || dp->conversion == 'G')
4235 if (flags & FLAG_ALT)
4238 (precision > 0 ? precision - 1 : 0);
4239 *p++ = decimal_point_char ();
4240 for (; ndigits > 0; --ndigits)
4252 /* The generated string now extends from tmp to p, with the
4253 zero padding insertion point being at pad_ptr. */
4254 if (has_width && p - tmp < width)
4256 size_t pad = width - (p - tmp);
4257 DCHAR_T *end = p + pad;
4259 if (flags & FLAG_LEFT)
4261 /* Pad with spaces on the right. */
4262 for (; pad > 0; pad--)
4265 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4267 /* Pad with zeroes. */
4272 for (; pad > 0; pad--)
4277 /* Pad with spaces on the left. */
4282 for (; pad > 0; pad--)
4290 size_t count = p - tmp;
4292 if (count >= tmp_length)
4293 /* tmp_length was incorrectly calculated - fix the
4297 /* Make room for the result. */
4298 if (count >= allocated - length)
4300 size_t n = xsum (length, count);
4302 ENSURE_ALLOCATION (n);
4305 /* Append the result. */
4306 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4315 arg_type type = a.arg[dp->arg_index].type;
4316 int flags = dp->flags;
4317 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4321 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4325 #if NEED_PRINTF_UNBOUNDED_PRECISION
4328 # define prec_ourselves 0
4330 #if NEED_PRINTF_FLAG_LEFTADJUST
4331 # define pad_ourselves 1
4332 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4335 # define pad_ourselves 0
4338 unsigned int prefix_count;
4339 int prefixes[2] IF_LINT (= { 0 });
4342 TCHAR_T tmpbuf[700];
4346 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4349 if (dp->width_start != dp->width_end)
4351 if (dp->width_arg_index != ARG_NONE)
4355 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4357 arg = a.arg[dp->width_arg_index].a.a_int;
4360 /* "A negative field width is taken as a '-' flag
4361 followed by a positive field width." */
4363 width = (unsigned int) (-arg);
4370 const FCHAR_T *digitp = dp->width_start;
4373 width = xsum (xtimes (width, 10), *digitp++ - '0');
4374 while (digitp != dp->width_end);
4380 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4383 if (dp->precision_start != dp->precision_end)
4385 if (dp->precision_arg_index != ARG_NONE)
4389 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4391 arg = a.arg[dp->precision_arg_index].a.a_int;
4392 /* "A negative precision is taken as if the precision
4402 const FCHAR_T *digitp = dp->precision_start + 1;
4405 while (digitp != dp->precision_end)
4406 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4412 /* Decide whether to handle the precision ourselves. */
4413 #if NEED_PRINTF_UNBOUNDED_PRECISION
4414 switch (dp->conversion)
4416 case 'd': case 'i': case 'u':
4418 case 'x': case 'X': case 'p':
4419 prec_ourselves = has_precision && (precision > 0);
4427 /* Decide whether to perform the padding ourselves. */
4428 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4429 switch (dp->conversion)
4431 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4432 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4433 to perform the padding after this conversion. Functions
4434 with unistdio extensions perform the padding based on
4435 character count rather than element count. */
4438 # if NEED_PRINTF_FLAG_ZERO
4439 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4445 pad_ourselves = prec_ourselves;
4451 /* Allocate a temporary buffer of sufficient size for calling
4454 switch (dp->conversion)
4457 case 'd': case 'i': case 'u':
4458 # if HAVE_LONG_LONG_INT
4459 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4461 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4462 * 0.30103 /* binary -> decimal */
4464 + 1; /* turn floor into ceil */
4467 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4469 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4470 * 0.30103 /* binary -> decimal */
4472 + 1; /* turn floor into ceil */
4475 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4476 * 0.30103 /* binary -> decimal */
4478 + 1; /* turn floor into ceil */
4479 if (tmp_length < precision)
4480 tmp_length = precision;
4481 /* Multiply by 2, as an estimate for FLAG_GROUP. */
4482 tmp_length = xsum (tmp_length, tmp_length);
4483 /* Add 1, to account for a leading sign. */
4484 tmp_length = xsum (tmp_length, 1);
4488 # if HAVE_LONG_LONG_INT
4489 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4491 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4492 * 0.333334 /* binary -> octal */
4494 + 1; /* turn floor into ceil */
4497 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4499 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4500 * 0.333334 /* binary -> octal */
4502 + 1; /* turn floor into ceil */
4505 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4506 * 0.333334 /* binary -> octal */
4508 + 1; /* turn floor into ceil */
4509 if (tmp_length < precision)
4510 tmp_length = precision;
4511 /* Add 1, to account for a leading sign. */
4512 tmp_length = xsum (tmp_length, 1);
4516 # if HAVE_LONG_LONG_INT
4517 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4519 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4520 * 0.25 /* binary -> hexadecimal */
4522 + 1; /* turn floor into ceil */
4525 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4527 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4528 * 0.25 /* binary -> hexadecimal */
4530 + 1; /* turn floor into ceil */
4533 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4534 * 0.25 /* binary -> hexadecimal */
4536 + 1; /* turn floor into ceil */
4537 if (tmp_length < precision)
4538 tmp_length = precision;
4539 /* Add 2, to account for a leading sign or alternate form. */
4540 tmp_length = xsum (tmp_length, 2);
4544 if (type == TYPE_LONGDOUBLE)
4546 (unsigned int) (LDBL_MAX_EXP
4547 * 0.30103 /* binary -> decimal */
4548 * 2 /* estimate for FLAG_GROUP */
4550 + 1 /* turn floor into ceil */
4551 + 10; /* sign, decimal point etc. */
4554 (unsigned int) (DBL_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. */
4560 tmp_length = xsum (tmp_length, precision);
4563 case 'e': case 'E': case 'g': case 'G':
4565 12; /* sign, decimal point, exponent etc. */
4566 tmp_length = xsum (tmp_length, precision);
4570 if (type == TYPE_LONGDOUBLE)
4572 (unsigned int) (LDBL_DIG
4573 * 0.831 /* decimal -> hexadecimal */
4575 + 1; /* turn floor into ceil */
4578 (unsigned int) (DBL_DIG
4579 * 0.831 /* decimal -> hexadecimal */
4581 + 1; /* turn floor into ceil */
4582 if (tmp_length < precision)
4583 tmp_length = precision;
4584 /* Account for sign, decimal point etc. */
4585 tmp_length = xsum (tmp_length, 12);
4589 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
4590 if (type == TYPE_WIDE_CHAR)
4591 tmp_length = MB_CUR_MAX;
4599 if (type == TYPE_WIDE_STRING)
4601 # if WIDE_CHAR_VERSION
4602 /* ISO C says about %ls in fwprintf:
4603 "If the precision is not specified or is greater
4604 than the size of the array, the array shall
4605 contain a null wide character."
4606 So if there is a precision, we must not use
4608 const wchar_t *arg =
4609 a.arg[dp->arg_index].a.a_wide_string;
4612 tmp_length = local_wcsnlen (arg, precision);
4614 tmp_length = local_wcslen (arg);
4616 /* ISO C says about %ls in fprintf:
4617 "If a precision is specified, no more than that
4618 many bytes are written (including shift
4619 sequences, if any), and the array shall contain
4620 a null wide character if, to equal the
4621 multibyte character sequence length given by
4622 the precision, the function would need to
4623 access a wide character one past the end of the
4625 So if there is a precision, we must not use
4627 /* This case has already been handled above. */
4634 # if WIDE_CHAR_VERSION
4635 /* ISO C says about %s in fwprintf:
4636 "If the precision is not specified or is greater
4637 than the size of the converted array, the
4638 converted array shall contain a null wide
4640 So if there is a precision, we must not use
4642 /* This case has already been handled above. */
4645 /* ISO C says about %s in fprintf:
4646 "If the precision is not specified or greater
4647 than the size of the array, the array shall
4648 contain a null character."
4649 So if there is a precision, we must not use
4651 const char *arg = a.arg[dp->arg_index].a.a_string;
4654 tmp_length = local_strnlen (arg, precision);
4656 tmp_length = strlen (arg);
4663 (unsigned int) (sizeof (void *) * CHAR_BIT
4664 * 0.25 /* binary -> hexadecimal */
4666 + 1 /* turn floor into ceil */
4667 + 2; /* account for leading 0x */
4676 # if ENABLE_UNISTDIO
4677 /* Padding considers the number of characters, therefore
4678 the number of elements after padding may be
4679 > max (tmp_length, width)
4681 <= tmp_length + width. */
4682 tmp_length = xsum (tmp_length, width);
4684 /* Padding considers the number of elements,
4686 if (tmp_length < width)
4691 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
4694 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4698 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4700 if (size_overflow_p (tmp_memsize))
4701 /* Overflow, would lead to out of memory. */
4703 tmp = (TCHAR_T *) malloc (tmp_memsize);
4705 /* Out of memory. */
4710 /* Construct the format string for calling snprintf or
4714 #if NEED_PRINTF_FLAG_GROUPING
4715 /* The underlying implementation doesn't support the ' flag.
4716 Produce no grouping characters in this case; this is
4717 acceptable because the grouping is locale dependent. */
4719 if (flags & FLAG_GROUP)
4722 if (flags & FLAG_LEFT)
4724 if (flags & FLAG_SHOWSIGN)
4726 if (flags & FLAG_SPACE)
4728 if (flags & FLAG_ALT)
4732 if (flags & FLAG_ZERO)
4734 if (dp->width_start != dp->width_end)
4736 size_t n = dp->width_end - dp->width_start;
4737 /* The width specification is known to consist only
4738 of standard ASCII characters. */
4739 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4741 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4746 const FCHAR_T *mp = dp->width_start;
4748 *fbp++ = (unsigned char) *mp++;
4753 if (!prec_ourselves)
4755 if (dp->precision_start != dp->precision_end)
4757 size_t n = dp->precision_end - dp->precision_start;
4758 /* The precision specification is known to consist only
4759 of standard ASCII characters. */
4760 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4762 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4767 const FCHAR_T *mp = dp->precision_start;
4769 *fbp++ = (unsigned char) *mp++;
4777 #if HAVE_LONG_LONG_INT
4778 case TYPE_LONGLONGINT:
4779 case TYPE_ULONGLONGINT:
4780 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4793 case TYPE_WIDE_CHAR:
4796 case TYPE_WIDE_STRING:
4800 case TYPE_LONGDOUBLE:
4806 #if NEED_PRINTF_DIRECTIVE_F
4807 if (dp->conversion == 'F')
4811 *fbp = dp->conversion;
4813 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4818 /* On glibc2 systems from glibc >= 2.3 - probably also older
4819 ones - we know that snprintf's returns value conforms to
4820 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4821 Therefore we can avoid using %n in this situation.
4822 On glibc2 systems from 2004-10-18 or newer, the use of %n
4823 in format strings in writable memory may crash the program
4824 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4825 in this situation. */
4826 /* On native Win32 systems (such as mingw), we can avoid using
4828 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4829 snprintf does not write more than the specified number
4830 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4831 '4', '5', '6' into buf, not '4', '5', '\0'.)
4832 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4833 allows us to recognize the case of an insufficient
4834 buffer size: it returns -1 in this case.
4835 On native Win32 systems (such as mingw) where the OS is
4836 Windows Vista, the use of %n in format strings by default
4837 crashes the program. See
4838 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4839 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4840 So we should avoid %n in this situation. */
4847 /* Construct the arguments for calling snprintf or sprintf. */
4849 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4851 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4853 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4855 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4857 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4859 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4863 /* The SNPRINTF result is appended after result[0..length].
4864 The latter is an array of DCHAR_T; SNPRINTF appends an
4865 array of TCHAR_T to it. This is possible because
4866 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4867 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4868 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4869 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4870 where an snprintf() with maxlen==1 acts like sprintf(). */
4871 ENSURE_ALLOCATION (xsum (length,
4872 (2 + TCHARS_PER_DCHAR - 1)
4873 / TCHARS_PER_DCHAR));
4874 /* Prepare checking whether snprintf returns the count
4876 *(TCHAR_T *) (result + length) = '\0';
4885 size_t maxlen = allocated - length;
4886 /* SNPRINTF can fail if its second argument is
4888 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4889 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4890 maxlen = maxlen * TCHARS_PER_DCHAR;
4891 # define SNPRINTF_BUF(arg) \
4892 switch (prefix_count) \
4895 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4900 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4902 prefixes[0], arg, &count); \
4905 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4907 prefixes[0], prefixes[1], arg, \
4914 # define SNPRINTF_BUF(arg) \
4915 switch (prefix_count) \
4918 count = sprintf (tmp, buf, arg); \
4921 count = sprintf (tmp, buf, prefixes[0], arg); \
4924 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4936 int arg = a.arg[dp->arg_index].a.a_schar;
4942 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4948 int arg = a.arg[dp->arg_index].a.a_short;
4954 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4960 int arg = a.arg[dp->arg_index].a.a_int;
4966 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4972 long int arg = a.arg[dp->arg_index].a.a_longint;
4978 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4982 #if HAVE_LONG_LONG_INT
4983 case TYPE_LONGLONGINT:
4985 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4989 case TYPE_ULONGLONGINT:
4991 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4998 double arg = a.arg[dp->arg_index].a.a_double;
5002 case TYPE_LONGDOUBLE:
5004 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5010 int arg = a.arg[dp->arg_index].a.a_char;
5015 case TYPE_WIDE_CHAR:
5017 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5024 const char *arg = a.arg[dp->arg_index].a.a_string;
5029 case TYPE_WIDE_STRING:
5031 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5038 void *arg = a.arg[dp->arg_index].a.a_pointer;
5047 /* Portability: Not all implementations of snprintf()
5048 are ISO C 99 compliant. Determine the number of
5049 bytes that snprintf() has produced or would have
5053 /* Verify that snprintf() has NUL-terminated its
5056 && ((TCHAR_T *) (result + length)) [count] != '\0')
5058 /* Portability hack. */
5059 if (retcount > count)
5064 /* snprintf() doesn't understand the '%n'
5068 /* Don't use the '%n' directive; instead, look
5069 at the snprintf() return value. */
5075 /* Look at the snprintf() return value. */
5078 /* HP-UX 10.20 snprintf() is doubly deficient:
5079 It doesn't understand the '%n' directive,
5080 *and* it returns -1 (rather than the length
5081 that would have been required) when the
5082 buffer is too small. */
5083 size_t bigger_need =
5084 xsum (xtimes (allocated, 2), 12);
5085 ENSURE_ALLOCATION (bigger_need);
5094 /* Attempt to handle failure. */
5097 if (!(result == resultbuf || result == NULL))
5099 if (buf_malloced != NULL)
5100 free (buf_malloced);
5107 /* Handle overflow of the allocated buffer.
5108 If such an overflow occurs, a C99 compliant snprintf()
5109 returns a count >= maxlen. However, a non-compliant
5110 snprintf() function returns only count = maxlen - 1. To
5111 cover both cases, test whether count >= maxlen - 1. */
5112 if ((unsigned int) count + 1 >= maxlen)
5114 /* If maxlen already has attained its allowed maximum,
5115 allocating more memory will not increase maxlen.
5116 Instead of looping, bail out. */
5117 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5121 /* Need at least (count + 1) * sizeof (TCHAR_T)
5122 bytes. (The +1 is for the trailing NUL.)
5123 But ask for (count + 2) * sizeof (TCHAR_T)
5124 bytes, so that in the next round, we likely get
5125 maxlen > (unsigned int) count + 1
5126 and so we don't get here again.
5127 And allocate proportionally, to avoid looping
5128 eternally if snprintf() reports a too small
5132 ((unsigned int) count + 2
5133 + TCHARS_PER_DCHAR - 1)
5134 / TCHARS_PER_DCHAR),
5135 xtimes (allocated, 2));
5137 ENSURE_ALLOCATION (n);
5143 #if NEED_PRINTF_UNBOUNDED_PRECISION
5146 /* Handle the precision. */
5149 (TCHAR_T *) (result + length);
5153 size_t prefix_count;
5157 /* Put the additional zeroes after the sign. */
5159 && (*prec_ptr == '-' || *prec_ptr == '+'
5160 || *prec_ptr == ' '))
5162 /* Put the additional zeroes after the 0x prefix if
5163 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5165 && prec_ptr[0] == '0'
5166 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5169 move = count - prefix_count;
5170 if (precision > move)
5172 /* Insert zeroes. */
5173 size_t insert = precision - move;
5179 (count + insert + TCHARS_PER_DCHAR - 1)
5180 / TCHARS_PER_DCHAR);
5181 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5182 ENSURE_ALLOCATION (n);
5183 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5184 prec_ptr = (TCHAR_T *) (result + length);
5187 prec_end = prec_ptr + count;
5188 prec_ptr += prefix_count;
5190 while (prec_end > prec_ptr)
5193 prec_end[insert] = prec_end[0];
5199 while (prec_end > prec_ptr);
5207 if (count >= tmp_length)
5208 /* tmp_length was incorrectly calculated - fix the
5214 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5215 if (dp->conversion == 'c' || dp->conversion == 's')
5217 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5219 The result string is not certainly ASCII. */
5220 const TCHAR_T *tmpsrc;
5223 /* This code assumes that TCHAR_T is 'char'. */
5224 typedef int TCHAR_T_verify
5225 [2 * (sizeof (TCHAR_T) == 1) - 1];
5227 tmpsrc = (TCHAR_T *) (result + length);
5232 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5233 iconveh_question_mark,
5239 int saved_errno = errno;
5240 if (!(result == resultbuf || result == NULL))
5242 if (buf_malloced != NULL)
5243 free (buf_malloced);
5245 errno = saved_errno;
5248 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5249 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5255 /* The result string is ASCII.
5256 Simple 1:1 conversion. */
5258 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5259 no-op conversion, in-place on the array starting
5260 at (result + length). */
5261 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5264 const TCHAR_T *tmpsrc;
5269 if (result == resultbuf)
5271 tmpsrc = (TCHAR_T *) (result + length);
5272 /* ENSURE_ALLOCATION will not move tmpsrc
5273 (because it's part of resultbuf). */
5274 ENSURE_ALLOCATION (xsum (length, count));
5278 /* ENSURE_ALLOCATION will move the array
5279 (because it uses realloc(). */
5280 ENSURE_ALLOCATION (xsum (length, count));
5281 tmpsrc = (TCHAR_T *) (result + length);
5285 ENSURE_ALLOCATION (xsum (length, count));
5287 tmpdst = result + length;
5288 /* Copy backwards, because of overlapping. */
5291 for (n = count; n > 0; n--)
5292 *--tmpdst = (unsigned char) *--tmpsrc;
5297 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5298 /* Make room for the result. */
5299 if (count > allocated - length)
5301 /* Need at least count elements. But allocate
5304 xmax (xsum (length, count), xtimes (allocated, 2));
5306 ENSURE_ALLOCATION (n);
5310 /* Here count <= allocated - length. */
5312 /* Perform padding. */
5313 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5314 if (pad_ourselves && has_width)
5317 # if ENABLE_UNISTDIO
5318 /* Outside POSIX, it's preferrable to compare the width
5319 against the number of _characters_ of the converted
5321 w = DCHAR_MBSNLEN (result + length, count);
5323 /* The width is compared against the number of _bytes_
5324 of the converted value, says POSIX. */
5329 size_t pad = width - w;
5331 /* Make room for the result. */
5332 if (xsum (count, pad) > allocated - length)
5334 /* Need at least count + pad elements. But
5335 allocate proportionally. */
5337 xmax (xsum3 (length, count, pad),
5338 xtimes (allocated, 2));
5342 ENSURE_ALLOCATION (n);
5345 ENSURE_ALLOCATION (n);
5348 /* Here count + pad <= allocated - length. */
5351 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5352 DCHAR_T * const rp = result + length;
5354 DCHAR_T * const rp = tmp;
5356 DCHAR_T *p = rp + count;
5357 DCHAR_T *end = p + pad;
5359 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5360 if (dp->conversion == 'c'
5361 || dp->conversion == 's')
5362 /* No zero-padding for string directives. */
5367 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5368 /* No zero-padding of "inf" and "nan". */
5369 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5370 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5373 /* The generated string now extends from rp to p,
5374 with the zero padding insertion point being at
5377 count = count + pad; /* = end - rp */
5379 if (flags & FLAG_LEFT)
5381 /* Pad with spaces on the right. */
5382 for (; pad > 0; pad--)
5385 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5387 /* Pad with zeroes. */
5392 for (; pad > 0; pad--)
5397 /* Pad with spaces on the left. */
5402 for (; pad > 0; pad--)
5410 /* Here still count <= allocated - length. */
5412 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5413 /* The snprintf() result did fit. */
5415 /* Append the sprintf() result. */
5416 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5423 #if NEED_PRINTF_DIRECTIVE_F
5424 if (dp->conversion == 'F')
5426 /* Convert the %f result to upper case for %F. */
5427 DCHAR_T *rp = result + length;
5429 for (rc = count; rc > 0; rc--, rp++)
5430 if (*rp >= 'a' && *rp <= 'z')
5431 *rp = *rp - 'a' + 'A';
5442 /* Add the final NUL. */
5443 ENSURE_ALLOCATION (xsum (length, 1));
5444 result[length] = '\0';
5446 if (result != resultbuf && length + 1 < allocated)
5448 /* Shrink the allocated memory if possible. */
5451 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5456 if (buf_malloced != NULL)
5457 free (buf_malloced);
5460 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5461 says that snprintf() fails with errno = EOVERFLOW in this case, but
5462 that's only because snprintf() returns an 'int'. This function does
5463 not have this limitation. */
5468 if (!(result == resultbuf || result == NULL))
5470 if (buf_malloced != NULL)
5471 free (buf_malloced);
5478 if (!(result == resultbuf || result == NULL))
5480 if (buf_malloced != NULL)
5481 free (buf_malloced);
5489 #undef TCHARS_PER_DCHAR
5497 #undef DCHAR_IS_TCHAR