1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* vsprintf with automatic memory allocation.
4 Copyright (C) 1999, 2002-2010 Free Software Foundation, Inc.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation,
18 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
20 /* This file can be parametrized with the following macros:
21 VASNPRINTF The name of the function being defined.
22 FCHAR_T The element type of the format string.
23 DCHAR_T The element type of the destination (result) string.
24 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
25 in the format string are ASCII. MUST be set if
26 FCHAR_T and DCHAR_T are not the same type.
27 DIRECTIVE Structure denoting a format directive.
29 DIRECTIVES Structure denoting the set of format directives of a
30 format string. Depends on FCHAR_T.
31 PRINTF_PARSE Function that parses a format string.
33 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
34 DCHAR_SET memset like function for DCHAR_T[] arrays.
35 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
36 SNPRINTF The system's snprintf (or similar) function.
37 This may be either snprintf or swprintf.
38 TCHAR_T The element type of the argument and result string
39 of the said SNPRINTF function. This may be either
40 char or wchar_t. The code exploits that
41 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
42 alignof (TCHAR_T) <= alignof (DCHAR_T).
43 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
44 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
45 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
46 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
47 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
49 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
50 This must come before <config.h> because <config.h> may include
51 <features.h>, and once <features.h> has been included, it's too late. */
53 # define _GNU_SOURCE 1
65 # if WIDE_CHAR_VERSION
66 # include "vasnwprintf.h"
68 # include "vasnprintf.h"
72 #include <locale.h> /* localeconv() */
73 #include <stdio.h> /* snprintf(), sprintf() */
74 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
75 #include <string.h> /* memcpy(), strlen() */
76 #include <errno.h> /* errno */
77 #include <limits.h> /* CHAR_BIT */
78 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
80 # include <langinfo.h>
83 # if WIDE_CHAR_VERSION
84 # include "wprintf-parse.h"
86 # include "printf-parse.h"
90 /* Checked size_t computations. */
95 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
100 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
102 # include "isnand-nolibm.h"
105 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
107 # include "isnanl-nolibm.h"
111 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
113 # include "isnand-nolibm.h"
114 # include "printf-frexp.h"
117 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
119 # include "isnanl-nolibm.h"
120 # include "printf-frexpl.h"
124 /* Default parameters. */
126 # if WIDE_CHAR_VERSION
127 # define VASNPRINTF vasnwprintf
128 # define FCHAR_T wchar_t
129 # define DCHAR_T wchar_t
130 # define TCHAR_T wchar_t
131 # define DCHAR_IS_TCHAR 1
132 # define DIRECTIVE wchar_t_directive
133 # define DIRECTIVES wchar_t_directives
134 # define PRINTF_PARSE wprintf_parse
135 # define DCHAR_CPY wmemcpy
136 # define DCHAR_SET wmemset
138 # define VASNPRINTF vasnprintf
139 # define FCHAR_T char
140 # define DCHAR_T char
141 # define TCHAR_T char
142 # define DCHAR_IS_TCHAR 1
143 # define DIRECTIVE char_directive
144 # define DIRECTIVES char_directives
145 # define PRINTF_PARSE printf_parse
146 # define DCHAR_CPY memcpy
147 # define DCHAR_SET memset
150 #if WIDE_CHAR_VERSION
151 /* TCHAR_T is wchar_t. */
152 # define USE_SNPRINTF 1
153 # if HAVE_DECL__SNWPRINTF
154 /* On Windows, the function swprintf() has a different signature than
155 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
156 instead. The mingw function snwprintf() has fewer bugs than the
157 MSVCRT function _snwprintf(), so prefer that. */
158 # if defined __MINGW32__
159 # define SNPRINTF snwprintf
161 # define SNPRINTF _snwprintf
165 # define SNPRINTF swprintf
168 /* TCHAR_T is char. */
169 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
170 But don't use it on BeOS, since BeOS snprintf produces no output if the
171 size argument is >= 0x3000000.
172 Also don't use it on Linux libc5, since there snprintf with size = 1
173 writes any output without bounds, like sprintf. */
174 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
175 # define USE_SNPRINTF 1
177 # define USE_SNPRINTF 0
179 # if HAVE_DECL__SNPRINTF
180 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
181 function _snprintf(), so prefer that. */
182 # if defined __MINGW32__
183 # define SNPRINTF snprintf
184 /* Here we need to call the native snprintf, not rpl_snprintf. */
187 # define SNPRINTF _snprintf
191 # define SNPRINTF snprintf
192 /* Here we need to call the native snprintf, not rpl_snprintf. */
196 /* Here we need to call the native sprintf, not rpl_sprintf. */
199 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
200 warnings in this file. Use -Dlint to suppress them. */
202 # define IF_LINT(Code) Code
204 # define IF_LINT(Code) /* empty */
207 /* Avoid some warnings from "gcc -Wshadow".
208 This file doesn't use the exp() and remainder() functions. */
212 #define remainder rem
214 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && !WIDE_CHAR_VERSION
215 # if (HAVE_STRNLEN && !defined _AIX)
216 # define local_strnlen strnlen
218 # ifndef local_strnlen_defined
219 # define local_strnlen_defined 1
221 local_strnlen (const char *string, size_t maxlen)
223 const char *end = memchr (string, '\0', maxlen);
224 return end ? (size_t) (end - string) : maxlen;
230 #if (((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && WIDE_CHAR_VERSION) || ((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && !WIDE_CHAR_VERSION && DCHAR_IS_TCHAR)) && HAVE_WCHAR_T
232 # define local_wcslen wcslen
234 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
235 a dependency towards this library, here is a local substitute.
236 Define this substitute only once, even if this file is included
237 twice in the same compilation unit. */
238 # ifndef local_wcslen_defined
239 # define local_wcslen_defined 1
241 local_wcslen (const wchar_t *s)
245 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
253 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
255 # define local_wcsnlen wcsnlen
257 # ifndef local_wcsnlen_defined
258 # define local_wcsnlen_defined 1
260 local_wcsnlen (const wchar_t *s, size_t maxlen)
264 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
272 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
273 /* Determine the decimal-point character according to the current locale. */
274 # ifndef decimal_point_char_defined
275 # define decimal_point_char_defined 1
277 decimal_point_char (void)
280 /* Determine it in a multithread-safe way. We know nl_langinfo is
281 multithread-safe on glibc systems and MacOS X systems, but is not required
282 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
283 localeconv() is rarely multithread-safe. */
284 # if HAVE_NL_LANGINFO && (__GLIBC__ || (defined __APPLE__ && defined __MACH__))
285 point = nl_langinfo (RADIXCHAR);
288 sprintf (pointbuf, "%#.0f", 1.0);
289 point = &pointbuf[1];
291 point = localeconv () -> decimal_point;
293 /* The decimal point is always a single byte: either '.' or ','. */
294 return (point[0] != '\0' ? point[0] : '.');
299 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
301 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
303 is_infinite_or_zero (double x)
305 return isnand (x) || x + x == x;
310 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
312 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
314 is_infinite_or_zerol (long double x)
316 return isnanl (x) || x + x == x;
321 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
323 /* Converting 'long double' to decimal without rare rounding bugs requires
324 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
325 (and slower) algorithms. */
327 typedef unsigned int mp_limb_t;
328 # define GMP_LIMB_BITS 32
329 verify (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS);
331 typedef unsigned long long mp_twolimb_t;
332 # define GMP_TWOLIMB_BITS 64
333 verify (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS);
335 /* Representation of a bignum >= 0. */
339 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
342 /* Compute the product of two bignums >= 0.
343 Return the allocated memory in case of success, NULL in case of memory
344 allocation failure. */
346 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
353 if (src1.nlimbs <= src2.nlimbs)
367 /* Now 0 <= len1 <= len2. */
370 /* src1 or src2 is zero. */
372 dest->limbs = (mp_limb_t *) malloc (1);
376 /* Here 1 <= len1 <= len2. */
382 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
385 for (k = len2; k > 0; )
387 for (i = 0; i < len1; i++)
389 mp_limb_t digit1 = p1[i];
390 mp_twolimb_t carry = 0;
391 for (j = 0; j < len2; j++)
393 mp_limb_t digit2 = p2[j];
394 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
396 dp[i + j] = (mp_limb_t) carry;
397 carry = carry >> GMP_LIMB_BITS;
399 dp[i + len2] = (mp_limb_t) carry;
402 while (dlen > 0 && dp[dlen - 1] == 0)
410 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
411 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
413 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
415 Return the allocated memory in case of success, NULL in case of memory
416 allocation failure. */
418 divide (mpn_t a, mpn_t b, mpn_t *q)
421 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
422 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
423 If m<n, then q:=0 and r:=a.
424 If m>=n=1, perform a single-precision division:
427 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
428 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
429 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
430 Normalise [q[m-1],...,q[0]], yields q.
431 If m>=n>1, perform a multiple-precision division:
432 We have a/b < beta^(m-n+1).
433 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
434 Shift a and b left by s bits, copying them. r:=a.
435 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
436 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
438 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
439 In case of overflow (q* >= beta) set q* := beta-1.
440 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
441 and c3 := b[n-2] * q*.
442 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
443 occurred. Furthermore 0 <= c3 < beta^2.
444 If there was overflow and
445 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
446 the next test can be skipped.}
447 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
448 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
450 Put r := r - b * q* * beta^j. In detail:
451 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
452 hence: u:=0, for i:=0 to n-1 do
454 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
455 u:=u div beta (+ 1, if carry in subtraction)
457 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
459 the carry u does not overflow.}
460 If a negative carry occurs, put q* := q* - 1
461 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
463 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
464 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
466 The room for q[j] can be allocated at the memory location of r[n+j].
467 Finally, round-to-even:
468 Shift r left by 1 bit.
469 If r > b or if r = b and q[0] is odd, q := q+1.
471 const mp_limb_t *a_ptr = a.limbs;
472 size_t a_len = a.nlimbs;
473 const mp_limb_t *b_ptr = b.limbs;
474 size_t b_len = b.nlimbs;
476 mp_limb_t *tmp_roomptr = NULL;
482 /* Allocate room for a_len+2 digits.
483 (Need a_len+1 digits for the real division and 1 more digit for the
484 final rounding of q.) */
485 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
490 while (a_len > 0 && a_ptr[a_len - 1] == 0)
497 /* Division by zero. */
499 if (b_ptr[b_len - 1] == 0)
505 /* Here m = a_len >= 0 and n = b_len > 0. */
509 /* m<n: trivial case. q=0, r := copy of a. */
512 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
513 q_ptr = roomptr + a_len;
518 /* n=1: single precision division.
519 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
523 mp_limb_t den = b_ptr[0];
524 mp_limb_t remainder = 0;
525 const mp_limb_t *sourceptr = a_ptr + a_len;
526 mp_limb_t *destptr = q_ptr + a_len;
528 for (count = a_len; count > 0; count--)
531 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
532 *--destptr = num / den;
533 remainder = num % den;
535 /* Normalise and store r. */
538 r_ptr[0] = remainder;
545 if (q_ptr[q_len - 1] == 0)
551 /* n>1: multiple precision division.
552 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
553 beta^(m-n-1) <= a/b < beta^(m-n+1). */
557 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
585 /* 0 <= s < GMP_LIMB_BITS.
586 Copy b, shifting it left by s bits. */
589 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
590 if (tmp_roomptr == NULL)
596 const mp_limb_t *sourceptr = b_ptr;
597 mp_limb_t *destptr = tmp_roomptr;
598 mp_twolimb_t accu = 0;
600 for (count = b_len; count > 0; count--)
602 accu += (mp_twolimb_t) *sourceptr++ << s;
603 *destptr++ = (mp_limb_t) accu;
604 accu = accu >> GMP_LIMB_BITS;
606 /* accu must be zero, since that was how s was determined. */
612 /* Copy a, shifting it left by s bits, yields r.
614 At the beginning: r = roomptr[0..a_len],
615 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
619 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
624 const mp_limb_t *sourceptr = a_ptr;
625 mp_limb_t *destptr = r_ptr;
626 mp_twolimb_t accu = 0;
628 for (count = a_len; count > 0; count--)
630 accu += (mp_twolimb_t) *sourceptr++ << s;
631 *destptr++ = (mp_limb_t) accu;
632 accu = accu >> GMP_LIMB_BITS;
634 *destptr++ = (mp_limb_t) accu;
636 q_ptr = roomptr + b_len;
637 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
639 size_t j = a_len - b_len; /* m-n */
640 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
641 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
642 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
643 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
644 /* Division loop, traversed m-n+1 times.
645 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
650 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
652 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
654 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
655 | r_ptr[j + b_len - 1];
656 q_star = num / b_msd;
661 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
662 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
663 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
664 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
665 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
667 If yes, jump directly to the subtraction loop.
668 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
669 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
670 if (r_ptr[j + b_len] > b_msd
671 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
672 /* r[j+n] >= b[n-1]+1 or
673 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
678 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
680 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
681 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
682 mp_twolimb_t c3 = /* b[n-2] * q* */
683 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
684 /* While c2 < c3, increase c2 and decrease c3.
685 Consider c3-c2. While it is > 0, decrease it by
686 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
687 this can happen only twice. */
690 q_star = q_star - 1; /* q* := q* - 1 */
691 if (c3 - c2 > b_msdd)
692 q_star = q_star - 1; /* q* := q* - 1 */
698 /* Subtract r := r - b * q* * beta^j. */
701 const mp_limb_t *sourceptr = b_ptr;
702 mp_limb_t *destptr = r_ptr + j;
703 mp_twolimb_t carry = 0;
705 for (count = b_len; count > 0; count--)
707 /* Here 0 <= carry <= q*. */
710 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
711 + (mp_limb_t) ~(*destptr);
712 /* Here 0 <= carry <= beta*q* + beta-1. */
713 *destptr++ = ~(mp_limb_t) carry;
714 carry = carry >> GMP_LIMB_BITS; /* <= q* */
716 cr = (mp_limb_t) carry;
718 /* Subtract cr from r_ptr[j + b_len], then forget about
720 if (cr > r_ptr[j + b_len])
722 /* Subtraction gave a carry. */
723 q_star = q_star - 1; /* q* := q* - 1 */
726 const mp_limb_t *sourceptr = b_ptr;
727 mp_limb_t *destptr = r_ptr + j;
730 for (count = b_len; count > 0; count--)
732 mp_limb_t source1 = *sourceptr++;
733 mp_limb_t source2 = *destptr;
734 *destptr++ = source1 + source2 + carry;
737 ? source1 >= (mp_limb_t) ~source2
738 : source1 > (mp_limb_t) ~source2);
741 /* Forget about the carry and about r[j+n]. */
744 /* q* is determined. Store it as q[j]. */
753 if (q_ptr[q_len - 1] == 0)
755 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
756 b is shifted left by s bits. */
757 /* Shift r right by s bits. */
760 mp_limb_t ptr = r_ptr + r_len;
761 mp_twolimb_t accu = 0;
763 for (count = r_len; count > 0; count--)
765 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
766 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
767 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
772 while (r_len > 0 && r_ptr[r_len - 1] == 0)
775 /* Compare r << 1 with b. */
783 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
784 | (i < r_len ? r_ptr[i] << 1 : 0);
785 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
795 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
800 for (i = 0; i < q_len; i++)
801 if (++(q_ptr[i]) != 0)
806 if (tmp_roomptr != NULL)
813 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
815 Destroys the contents of a.
816 Return the allocated memory - containing the decimal digits in low-to-high
817 order, terminated with a NUL character - in case of success, NULL in case
818 of memory allocation failure. */
820 convert_to_decimal (mpn_t a, size_t extra_zeroes)
822 mp_limb_t *a_ptr = a.limbs;
823 size_t a_len = a.nlimbs;
824 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
825 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
826 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
830 for (; extra_zeroes > 0; extra_zeroes--)
834 /* Divide a by 10^9, in-place. */
835 mp_limb_t remainder = 0;
836 mp_limb_t *ptr = a_ptr + a_len;
838 for (count = a_len; count > 0; count--)
841 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
842 *ptr = num / 1000000000;
843 remainder = num % 1000000000;
845 /* Store the remainder as 9 decimal digits. */
846 for (count = 9; count > 0; count--)
848 *d_ptr++ = '0' + (remainder % 10);
849 remainder = remainder / 10;
852 if (a_ptr[a_len - 1] == 0)
855 /* Remove leading zeroes. */
856 while (d_ptr > c_ptr && d_ptr[-1] == '0')
858 /* But keep at least one zero. */
861 /* Terminate the string. */
867 # if NEED_PRINTF_LONG_DOUBLE
869 /* Assuming x is finite and >= 0:
870 write x as x = 2^e * m, where m is a bignum.
871 Return the allocated memory in case of success, NULL in case of memory
872 allocation failure. */
874 decode_long_double (long double x, int *ep, mpn_t *mp)
881 /* Allocate memory for result. */
882 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
883 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
886 /* Split into exponential part and mantissa. */
887 y = frexpl (x, &exp);
888 if (!(y >= 0.0L && y < 1.0L))
890 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
891 latter is an integer. */
892 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
893 I'm not sure whether it's safe to cast a 'long double' value between
894 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
895 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
897 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
898 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
901 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
904 if (!(y >= 0.0L && y < 1.0L))
906 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
909 if (!(y >= 0.0L && y < 1.0L))
911 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
916 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
919 if (!(y >= 0.0L && y < 1.0L))
921 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
925 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
928 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
931 if (!(y >= 0.0L && y < 1.0L))
933 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
936 if (!(y >= 0.0L && y < 1.0L))
938 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
940 #if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
946 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
949 *ep = exp - LDBL_MANT_BIT;
955 # if NEED_PRINTF_DOUBLE
957 /* Assuming x is finite and >= 0:
958 write x as x = 2^e * m, where m is a bignum.
959 Return the allocated memory in case of success, NULL in case of memory
960 allocation failure. */
962 decode_double (double x, int *ep, mpn_t *mp)
969 /* Allocate memory for result. */
970 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
971 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
974 /* Split into exponential part and mantissa. */
976 if (!(y >= 0.0 && y < 1.0))
978 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
979 latter is an integer. */
980 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
981 I'm not sure whether it's safe to cast a 'double' value between
982 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
983 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
985 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
986 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
989 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
992 if (!(y >= 0.0 && y < 1.0))
994 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
997 if (!(y >= 0.0 && y < 1.0))
999 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1004 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
1007 if (!(y >= 0.0 && y < 1.0))
1009 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
1013 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1016 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1019 if (!(y >= 0.0 && y < 1.0))
1021 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1024 if (!(y >= 0.0 && y < 1.0))
1026 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1031 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1034 *ep = exp - DBL_MANT_BIT;
1040 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1041 Returns the decimal representation of round (x * 10^n).
1042 Return the allocated memory - containing the decimal digits in low-to-high
1043 order, terminated with a NUL character - in case of success, NULL in case
1044 of memory allocation failure. */
1046 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1049 size_t extra_zeroes;
1052 mp_limb_t *pow5_ptr;
1054 unsigned int s_limbs;
1055 unsigned int s_bits;
1063 /* x = 2^e * m, hence
1064 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1065 = round (2^s * 5^n * m). */
1068 /* Factor out a common power of 10 if possible. */
1071 extra_zeroes = (s < n ? s : n);
1075 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1076 Before converting to decimal, we need to compute
1077 z = round (2^s * 5^n * m). */
1078 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1079 sign. 2.322 is slightly larger than log(5)/log(2). */
1080 abs_n = (n >= 0 ? n : -n);
1081 abs_s = (s >= 0 ? s : -s);
1082 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1083 + abs_s / GMP_LIMB_BITS + 1)
1084 * sizeof (mp_limb_t));
1085 if (pow5_ptr == NULL)
1090 /* Initialize with 1. */
1093 /* Multiply with 5^|n|. */
1096 static mp_limb_t const small_pow5[13 + 1] =
1098 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1099 48828125, 244140625, 1220703125
1102 for (n13 = 0; n13 <= abs_n; n13 += 13)
1104 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1106 mp_twolimb_t carry = 0;
1107 for (j = 0; j < pow5_len; j++)
1109 mp_limb_t digit2 = pow5_ptr[j];
1110 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1111 pow5_ptr[j] = (mp_limb_t) carry;
1112 carry = carry >> GMP_LIMB_BITS;
1115 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1118 s_limbs = abs_s / GMP_LIMB_BITS;
1119 s_bits = abs_s % GMP_LIMB_BITS;
1120 if (n >= 0 ? s >= 0 : s <= 0)
1122 /* Multiply with 2^|s|. */
1125 mp_limb_t *ptr = pow5_ptr;
1126 mp_twolimb_t accu = 0;
1128 for (count = pow5_len; count > 0; count--)
1130 accu += (mp_twolimb_t) *ptr << s_bits;
1131 *ptr++ = (mp_limb_t) accu;
1132 accu = accu >> GMP_LIMB_BITS;
1136 *ptr = (mp_limb_t) accu;
1143 for (count = pow5_len; count > 0;)
1146 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1148 for (count = s_limbs; count > 0;)
1151 pow5_ptr[count] = 0;
1153 pow5_len += s_limbs;
1155 pow5.limbs = pow5_ptr;
1156 pow5.nlimbs = pow5_len;
1159 /* Multiply m with pow5. No division needed. */
1160 z_memory = multiply (m, pow5, &z);
1164 /* Divide m by pow5 and round. */
1165 z_memory = divide (m, pow5, &z);
1170 pow5.limbs = pow5_ptr;
1171 pow5.nlimbs = pow5_len;
1175 Multiply m with pow5, then divide by 2^|s|. */
1179 tmp_memory = multiply (m, pow5, &numerator);
1180 if (tmp_memory == NULL)
1186 /* Construct 2^|s|. */
1188 mp_limb_t *ptr = pow5_ptr + pow5_len;
1190 for (i = 0; i < s_limbs; i++)
1192 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1193 denominator.limbs = ptr;
1194 denominator.nlimbs = s_limbs + 1;
1196 z_memory = divide (numerator, denominator, &z);
1202 Multiply m with 2^s, then divide by pow5. */
1205 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1206 * sizeof (mp_limb_t));
1207 if (num_ptr == NULL)
1214 mp_limb_t *destptr = num_ptr;
1217 for (i = 0; i < s_limbs; i++)
1222 const mp_limb_t *sourceptr = m.limbs;
1223 mp_twolimb_t accu = 0;
1225 for (count = m.nlimbs; count > 0; count--)
1227 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1228 *destptr++ = (mp_limb_t) accu;
1229 accu = accu >> GMP_LIMB_BITS;
1232 *destptr++ = (mp_limb_t) accu;
1236 const mp_limb_t *sourceptr = m.limbs;
1238 for (count = m.nlimbs; count > 0; count--)
1239 *destptr++ = *sourceptr++;
1241 numerator.limbs = num_ptr;
1242 numerator.nlimbs = destptr - num_ptr;
1244 z_memory = divide (numerator, pow5, &z);
1251 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1253 if (z_memory == NULL)
1255 digits = convert_to_decimal (z, extra_zeroes);
1260 # if NEED_PRINTF_LONG_DOUBLE
1262 /* Assuming x is finite and >= 0, and n is an integer:
1263 Returns the decimal representation of round (x * 10^n).
1264 Return the allocated memory - containing the decimal digits in low-to-high
1265 order, terminated with a NUL character - in case of success, NULL in case
1266 of memory allocation failure. */
1268 scale10_round_decimal_long_double (long double x, int n)
1272 void *memory = decode_long_double (x, &e, &m);
1273 return scale10_round_decimal_decoded (e, m, memory, n);
1278 # if NEED_PRINTF_DOUBLE
1280 /* Assuming x is finite and >= 0, and n is an integer:
1281 Returns the decimal representation of round (x * 10^n).
1282 Return the allocated memory - containing the decimal digits in low-to-high
1283 order, terminated with a NUL character - in case of success, NULL in case
1284 of memory allocation failure. */
1286 scale10_round_decimal_double (double x, int n)
1290 void *memory = decode_double (x, &e, &m);
1291 return scale10_round_decimal_decoded (e, m, memory, n);
1296 # if NEED_PRINTF_LONG_DOUBLE
1298 /* Assuming x is finite and > 0:
1299 Return an approximation for n with 10^n <= x < 10^(n+1).
1300 The approximation is usually the right n, but may be off by 1 sometimes. */
1302 floorlog10l (long double x)
1309 /* Split into exponential part and mantissa. */
1310 y = frexpl (x, &exp);
1311 if (!(y >= 0.0L && y < 1.0L))
1317 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1319 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1320 exp -= GMP_LIMB_BITS;
1322 if (y < (1.0L / (1 << 16)))
1324 y *= 1.0L * (1 << 16);
1327 if (y < (1.0L / (1 << 8)))
1329 y *= 1.0L * (1 << 8);
1332 if (y < (1.0L / (1 << 4)))
1334 y *= 1.0L * (1 << 4);
1337 if (y < (1.0L / (1 << 2)))
1339 y *= 1.0L * (1 << 2);
1342 if (y < (1.0L / (1 << 1)))
1344 y *= 1.0L * (1 << 1);
1348 if (!(y >= 0.5L && y < 1.0L))
1350 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1353 if (z < 0.70710678118654752444)
1355 z *= 1.4142135623730950488;
1358 if (z < 0.8408964152537145431)
1360 z *= 1.1892071150027210667;
1363 if (z < 0.91700404320467123175)
1365 z *= 1.0905077326652576592;
1368 if (z < 0.9576032806985736469)
1370 z *= 1.0442737824274138403;
1373 /* Now 0.95 <= z <= 1.01. */
1375 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1376 Four terms are enough to get an approximation with error < 10^-7. */
1377 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1378 /* Finally multiply with log(2)/log(10), yields an approximation for
1380 l *= 0.30102999566398119523;
1381 /* Round down to the next integer. */
1382 return (int) l + (l < 0 ? -1 : 0);
1387 # if NEED_PRINTF_DOUBLE
1389 /* Assuming x is finite and > 0:
1390 Return an approximation for n with 10^n <= x < 10^(n+1).
1391 The approximation is usually the right n, but may be off by 1 sometimes. */
1393 floorlog10 (double x)
1400 /* Split into exponential part and mantissa. */
1401 y = frexp (x, &exp);
1402 if (!(y >= 0.0 && y < 1.0))
1408 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1410 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1411 exp -= GMP_LIMB_BITS;
1413 if (y < (1.0 / (1 << 16)))
1415 y *= 1.0 * (1 << 16);
1418 if (y < (1.0 / (1 << 8)))
1420 y *= 1.0 * (1 << 8);
1423 if (y < (1.0 / (1 << 4)))
1425 y *= 1.0 * (1 << 4);
1428 if (y < (1.0 / (1 << 2)))
1430 y *= 1.0 * (1 << 2);
1433 if (y < (1.0 / (1 << 1)))
1435 y *= 1.0 * (1 << 1);
1439 if (!(y >= 0.5 && y < 1.0))
1441 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1444 if (z < 0.70710678118654752444)
1446 z *= 1.4142135623730950488;
1449 if (z < 0.8408964152537145431)
1451 z *= 1.1892071150027210667;
1454 if (z < 0.91700404320467123175)
1456 z *= 1.0905077326652576592;
1459 if (z < 0.9576032806985736469)
1461 z *= 1.0442737824274138403;
1464 /* Now 0.95 <= z <= 1.01. */
1466 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1467 Four terms are enough to get an approximation with error < 10^-7. */
1468 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1469 /* Finally multiply with log(2)/log(10), yields an approximation for
1471 l *= 0.30102999566398119523;
1472 /* Round down to the next integer. */
1473 return (int) l + (l < 0 ? -1 : 0);
1478 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1479 a single '1' digit. */
1481 is_borderline (const char *digits, size_t precision)
1483 for (; precision > 0; precision--, digits++)
1489 return *digits == '\0';
1494 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99
1496 /* Use a different function name, to make it possible that the 'wchar_t'
1497 parametrization and the 'char' parametrization get compiled in the same
1498 translation unit. */
1499 # if WIDE_CHAR_VERSION
1500 # define MAX_ROOM_NEEDED wmax_room_needed
1502 # define MAX_ROOM_NEEDED max_room_needed
1505 /* Returns the number of TCHAR_T units needed as temporary space for the result
1506 of sprintf or SNPRINTF of a single conversion directive. */
1507 static inline size_t
1508 MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
1509 arg_type type, int flags, size_t width, int has_precision,
1510 size_t precision, int pad_ourselves)
1516 case 'd': case 'i': case 'u':
1517 # if HAVE_LONG_LONG_INT
1518 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1520 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1521 * 0.30103 /* binary -> decimal */
1523 + 1; /* turn floor into ceil */
1526 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1528 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1529 * 0.30103 /* binary -> decimal */
1531 + 1; /* turn floor into ceil */
1534 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1535 * 0.30103 /* binary -> decimal */
1537 + 1; /* turn floor into ceil */
1538 if (tmp_length < precision)
1539 tmp_length = precision;
1540 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1541 tmp_length = xsum (tmp_length, tmp_length);
1542 /* Add 1, to account for a leading sign. */
1543 tmp_length = xsum (tmp_length, 1);
1547 # if HAVE_LONG_LONG_INT
1548 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1550 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1551 * 0.333334 /* binary -> octal */
1553 + 1; /* turn floor into ceil */
1556 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1558 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1559 * 0.333334 /* binary -> octal */
1561 + 1; /* turn floor into ceil */
1564 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1565 * 0.333334 /* binary -> octal */
1567 + 1; /* turn floor into ceil */
1568 if (tmp_length < precision)
1569 tmp_length = precision;
1570 /* Add 1, to account for a leading sign. */
1571 tmp_length = xsum (tmp_length, 1);
1575 # if HAVE_LONG_LONG_INT
1576 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1578 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1579 * 0.25 /* binary -> hexadecimal */
1581 + 1; /* turn floor into ceil */
1584 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1586 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1587 * 0.25 /* binary -> hexadecimal */
1589 + 1; /* turn floor into ceil */
1592 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1593 * 0.25 /* binary -> hexadecimal */
1595 + 1; /* turn floor into ceil */
1596 if (tmp_length < precision)
1597 tmp_length = precision;
1598 /* Add 2, to account for a leading sign or alternate form. */
1599 tmp_length = xsum (tmp_length, 2);
1603 if (type == TYPE_LONGDOUBLE)
1605 (unsigned int) (LDBL_MAX_EXP
1606 * 0.30103 /* binary -> decimal */
1607 * 2 /* estimate for FLAG_GROUP */
1609 + 1 /* turn floor into ceil */
1610 + 10; /* sign, decimal point etc. */
1613 (unsigned int) (DBL_MAX_EXP
1614 * 0.30103 /* binary -> decimal */
1615 * 2 /* estimate for FLAG_GROUP */
1617 + 1 /* turn floor into ceil */
1618 + 10; /* sign, decimal point etc. */
1619 tmp_length = xsum (tmp_length, precision);
1622 case 'e': case 'E': case 'g': case 'G':
1624 12; /* sign, decimal point, exponent etc. */
1625 tmp_length = xsum (tmp_length, precision);
1629 if (type == TYPE_LONGDOUBLE)
1631 (unsigned int) (LDBL_DIG
1632 * 0.831 /* decimal -> hexadecimal */
1634 + 1; /* turn floor into ceil */
1637 (unsigned int) (DBL_DIG
1638 * 0.831 /* decimal -> hexadecimal */
1640 + 1; /* turn floor into ceil */
1641 if (tmp_length < precision)
1642 tmp_length = precision;
1643 /* Account for sign, decimal point etc. */
1644 tmp_length = xsum (tmp_length, 12);
1648 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
1649 if (type == TYPE_WIDE_CHAR)
1650 tmp_length = MB_CUR_MAX;
1658 if (type == TYPE_WIDE_STRING)
1660 # if WIDE_CHAR_VERSION
1661 /* ISO C says about %ls in fwprintf:
1662 "If the precision is not specified or is greater than the size
1663 of the array, the array shall contain a null wide character."
1664 So if there is a precision, we must not use wcslen. */
1665 const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
1668 tmp_length = local_wcsnlen (arg, precision);
1670 tmp_length = local_wcslen (arg);
1672 /* ISO C says about %ls in fprintf:
1673 "If a precision is specified, no more than that many bytes are
1674 written (including shift sequences, if any), and the array
1675 shall contain a null wide character if, to equal the multibyte
1676 character sequence length given by the precision, the function
1677 would need to access a wide character one past the end of the
1679 So if there is a precision, we must not use wcslen. */
1680 /* This case has already been handled separately in VASNPRINTF. */
1687 # if WIDE_CHAR_VERSION
1688 /* ISO C says about %s in fwprintf:
1689 "If the precision is not specified or is greater than the size
1690 of the converted array, the converted array shall contain a
1691 null wide character."
1692 So if there is a precision, we must not use strlen. */
1693 /* This case has already been handled separately in VASNPRINTF. */
1696 /* ISO C says about %s in fprintf:
1697 "If the precision is not specified or greater than the size of
1698 the array, the array shall contain a null character."
1699 So if there is a precision, we must not use strlen. */
1700 const char *arg = ap->arg[arg_index].a.a_string;
1703 tmp_length = local_strnlen (arg, precision);
1705 tmp_length = strlen (arg);
1712 (unsigned int) (sizeof (void *) * CHAR_BIT
1713 * 0.25 /* binary -> hexadecimal */
1715 + 1 /* turn floor into ceil */
1716 + 2; /* account for leading 0x */
1725 # if ENABLE_UNISTDIO
1726 /* Padding considers the number of characters, therefore the number of
1727 elements after padding may be
1728 > max (tmp_length, width)
1730 <= tmp_length + width. */
1731 tmp_length = xsum (tmp_length, width);
1733 /* Padding considers the number of elements, says POSIX. */
1734 if (tmp_length < width)
1739 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1747 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1748 const FCHAR_T *format, va_list args)
1753 if (PRINTF_PARSE (format, &d, &a) < 0)
1754 /* errno is already set. */
1762 if (PRINTF_FETCHARGS (args, &a) < 0)
1770 size_t buf_neededlength;
1772 TCHAR_T *buf_malloced;
1776 /* Output string accumulator. */
1781 /* Allocate a small buffer that will hold a directive passed to
1782 sprintf or snprintf. */
1784 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1786 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1788 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1789 buf_malloced = NULL;
1794 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1795 if (size_overflow_p (buf_memsize))
1796 goto out_of_memory_1;
1797 buf = (TCHAR_T *) malloc (buf_memsize);
1799 goto out_of_memory_1;
1803 if (resultbuf != NULL)
1806 allocated = *lengthp;
1815 result is either == resultbuf or == NULL or malloc-allocated.
1816 If length > 0, then result != NULL. */
1818 /* Ensures that allocated >= needed. Aborts through a jump to
1819 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1820 #define ENSURE_ALLOCATION(needed) \
1821 if ((needed) > allocated) \
1823 size_t memory_size; \
1826 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1827 if ((needed) > allocated) \
1828 allocated = (needed); \
1829 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1830 if (size_overflow_p (memory_size)) \
1831 goto out_of_memory; \
1832 if (result == resultbuf || result == NULL) \
1833 memory = (DCHAR_T *) malloc (memory_size); \
1835 memory = (DCHAR_T *) realloc (result, memory_size); \
1836 if (memory == NULL) \
1837 goto out_of_memory; \
1838 if (result == resultbuf && length > 0) \
1839 DCHAR_CPY (memory, result, length); \
1843 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1845 if (cp != dp->dir_start)
1847 size_t n = dp->dir_start - cp;
1848 size_t augmented_length = xsum (length, n);
1850 ENSURE_ALLOCATION (augmented_length);
1851 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1852 need that the format string contains only ASCII characters
1853 if FCHAR_T and DCHAR_T are not the same type. */
1854 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1856 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1857 length = augmented_length;
1862 result[length++] = (unsigned char) *cp++;
1869 /* Execute a single directive. */
1870 if (dp->conversion == '%')
1872 size_t augmented_length;
1874 if (!(dp->arg_index == ARG_NONE))
1876 augmented_length = xsum (length, 1);
1877 ENSURE_ALLOCATION (augmented_length);
1878 result[length] = '%';
1879 length = augmented_length;
1883 if (!(dp->arg_index != ARG_NONE))
1886 if (dp->conversion == 'n')
1888 switch (a.arg[dp->arg_index].type)
1890 case TYPE_COUNT_SCHAR_POINTER:
1891 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1893 case TYPE_COUNT_SHORT_POINTER:
1894 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1896 case TYPE_COUNT_INT_POINTER:
1897 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1899 case TYPE_COUNT_LONGINT_POINTER:
1900 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1902 #if HAVE_LONG_LONG_INT
1903 case TYPE_COUNT_LONGLONGINT_POINTER:
1904 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1912 /* The unistdio extensions. */
1913 else if (dp->conversion == 'U')
1915 arg_type type = a.arg[dp->arg_index].type;
1916 int flags = dp->flags;
1924 if (dp->width_start != dp->width_end)
1926 if (dp->width_arg_index != ARG_NONE)
1930 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1932 arg = a.arg[dp->width_arg_index].a.a_int;
1935 /* "A negative field width is taken as a '-' flag
1936 followed by a positive field width." */
1938 width = (unsigned int) (-arg);
1945 const FCHAR_T *digitp = dp->width_start;
1948 width = xsum (xtimes (width, 10), *digitp++ - '0');
1949 while (digitp != dp->width_end);
1956 if (dp->precision_start != dp->precision_end)
1958 if (dp->precision_arg_index != ARG_NONE)
1962 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1964 arg = a.arg[dp->precision_arg_index].a.a_int;
1965 /* "A negative precision is taken as if the precision
1975 const FCHAR_T *digitp = dp->precision_start + 1;
1978 while (digitp != dp->precision_end)
1979 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1986 case TYPE_U8_STRING:
1988 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1989 const uint8_t *arg_end;
1994 /* Use only PRECISION characters, from the left. */
1997 for (; precision > 0; precision--)
1999 int count = u8_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 = u8_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 + u8_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_UINT8_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-8 to locale encoding. */
2072 u8_conv_to_encoding (locale_charset (),
2073 iconveh_question_mark,
2074 arg, arg_end - arg, NULL,
2075 converted, &converted_len);
2077 /* Convert from UTF-8 to UTF-16/UTF-32. */
2079 U8_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);
2114 case TYPE_U16_STRING:
2116 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
2117 const uint16_t *arg_end;
2122 /* Use only PRECISION characters, from the left. */
2125 for (; precision > 0; precision--)
2127 int count = u16_strmblen (arg_end);
2132 if (!(result == resultbuf || result == NULL))
2134 if (buf_malloced != NULL)
2135 free (buf_malloced);
2146 /* Use the entire string, and count the number of
2152 int count = u16_strmblen (arg_end);
2157 if (!(result == resultbuf || result == NULL))
2159 if (buf_malloced != NULL)
2160 free (buf_malloced);
2171 /* Use the entire string. */
2172 arg_end = arg + u16_strlen (arg);
2173 /* The number of characters doesn't matter. */
2177 if (has_width && width > characters
2178 && !(dp->flags & FLAG_LEFT))
2180 size_t n = width - characters;
2181 ENSURE_ALLOCATION (xsum (length, n));
2182 DCHAR_SET (result + length, ' ', n);
2186 # if DCHAR_IS_UINT16_T
2188 size_t n = arg_end - arg;
2189 ENSURE_ALLOCATION (xsum (length, n));
2190 DCHAR_CPY (result + length, arg, n);
2195 DCHAR_T *converted = result + length;
2196 size_t converted_len = allocated - length;
2198 /* Convert from UTF-16 to locale encoding. */
2200 u16_conv_to_encoding (locale_charset (),
2201 iconveh_question_mark,
2202 arg, arg_end - arg, NULL,
2203 converted, &converted_len);
2205 /* Convert from UTF-16 to UTF-8/UTF-32. */
2207 U16_TO_DCHAR (arg, arg_end - arg,
2208 converted, &converted_len);
2210 if (converted == NULL)
2212 int saved_errno = errno;
2213 if (!(result == resultbuf || result == NULL))
2215 if (buf_malloced != NULL)
2216 free (buf_malloced);
2218 errno = saved_errno;
2221 if (converted != result + length)
2223 ENSURE_ALLOCATION (xsum (length, converted_len));
2224 DCHAR_CPY (result + length, converted, converted_len);
2227 length += converted_len;
2231 if (has_width && width > characters
2232 && (dp->flags & FLAG_LEFT))
2234 size_t n = width - characters;
2235 ENSURE_ALLOCATION (xsum (length, n));
2236 DCHAR_SET (result + length, ' ', n);
2242 case TYPE_U32_STRING:
2244 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
2245 const uint32_t *arg_end;
2250 /* Use only PRECISION characters, from the left. */
2253 for (; precision > 0; precision--)
2255 int count = u32_strmblen (arg_end);
2260 if (!(result == resultbuf || result == NULL))
2262 if (buf_malloced != NULL)
2263 free (buf_malloced);
2274 /* Use the entire string, and count the number of
2280 int count = u32_strmblen (arg_end);
2285 if (!(result == resultbuf || result == NULL))
2287 if (buf_malloced != NULL)
2288 free (buf_malloced);
2299 /* Use the entire string. */
2300 arg_end = arg + u32_strlen (arg);
2301 /* The number of characters doesn't matter. */
2305 if (has_width && width > characters
2306 && !(dp->flags & FLAG_LEFT))
2308 size_t n = width - characters;
2309 ENSURE_ALLOCATION (xsum (length, n));
2310 DCHAR_SET (result + length, ' ', n);
2314 # if DCHAR_IS_UINT32_T
2316 size_t n = arg_end - arg;
2317 ENSURE_ALLOCATION (xsum (length, n));
2318 DCHAR_CPY (result + length, arg, n);
2323 DCHAR_T *converted = result + length;
2324 size_t converted_len = allocated - length;
2326 /* Convert from UTF-32 to locale encoding. */
2328 u32_conv_to_encoding (locale_charset (),
2329 iconveh_question_mark,
2330 arg, arg_end - arg, NULL,
2331 converted, &converted_len);
2333 /* Convert from UTF-32 to UTF-8/UTF-16. */
2335 U32_TO_DCHAR (arg, arg_end - arg,
2336 converted, &converted_len);
2338 if (converted == NULL)
2340 int saved_errno = errno;
2341 if (!(result == resultbuf || result == NULL))
2343 if (buf_malloced != NULL)
2344 free (buf_malloced);
2346 errno = saved_errno;
2349 if (converted != result + length)
2351 ENSURE_ALLOCATION (xsum (length, converted_len));
2352 DCHAR_CPY (result + length, converted, converted_len);
2355 length += converted_len;
2359 if (has_width && width > characters
2360 && (dp->flags & FLAG_LEFT))
2362 size_t n = width - characters;
2363 ENSURE_ALLOCATION (xsum (length, n));
2364 DCHAR_SET (result + length, ' ', n);
2375 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T
2376 else if (dp->conversion == 's'
2377 # if WIDE_CHAR_VERSION
2378 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2380 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2384 /* The normal handling of the 's' directive below requires
2385 allocating a temporary buffer. The determination of its
2386 length (tmp_length), in the case when a precision is
2387 specified, below requires a conversion between a char[]
2388 string and a wchar_t[] wide string. It could be done, but
2389 we have no guarantee that the implementation of sprintf will
2390 use the exactly same algorithm. Without this guarantee, it
2391 is possible to have buffer overrun bugs. In order to avoid
2392 such bugs, we implement the entire processing of the 's'
2393 directive ourselves. */
2394 int flags = dp->flags;
2402 if (dp->width_start != dp->width_end)
2404 if (dp->width_arg_index != ARG_NONE)
2408 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2410 arg = a.arg[dp->width_arg_index].a.a_int;
2413 /* "A negative field width is taken as a '-' flag
2414 followed by a positive field width." */
2416 width = (unsigned int) (-arg);
2423 const FCHAR_T *digitp = dp->width_start;
2426 width = xsum (xtimes (width, 10), *digitp++ - '0');
2427 while (digitp != dp->width_end);
2434 if (dp->precision_start != dp->precision_end)
2436 if (dp->precision_arg_index != ARG_NONE)
2440 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2442 arg = a.arg[dp->precision_arg_index].a.a_int;
2443 /* "A negative precision is taken as if the precision
2453 const FCHAR_T *digitp = dp->precision_start + 1;
2456 while (digitp != dp->precision_end)
2457 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2462 # if WIDE_CHAR_VERSION
2463 /* %s in vasnwprintf. See the specification of fwprintf. */
2465 const char *arg = a.arg[dp->arg_index].a.a_string;
2466 const char *arg_end;
2471 /* Use only as many bytes as needed to produce PRECISION
2472 wide characters, from the left. */
2475 memset (&state, '\0', sizeof (mbstate_t));
2479 for (; precision > 0; precision--)
2483 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2485 count = mblen (arg_end, MB_CUR_MAX);
2488 /* Found the terminating NUL. */
2492 /* Invalid or incomplete multibyte character. */
2493 if (!(result == resultbuf || result == NULL))
2495 if (buf_malloced != NULL)
2496 free (buf_malloced);
2507 /* Use the entire string, and count the number of wide
2511 memset (&state, '\0', sizeof (mbstate_t));
2519 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2521 count = mblen (arg_end, MB_CUR_MAX);
2524 /* Found the terminating NUL. */
2528 /* Invalid or incomplete multibyte character. */
2529 if (!(result == resultbuf || result == NULL))
2531 if (buf_malloced != NULL)
2532 free (buf_malloced);
2543 /* Use the entire string. */
2544 arg_end = arg + strlen (arg);
2545 /* The number of characters doesn't matter. */
2549 if (has_width && width > characters
2550 && !(dp->flags & FLAG_LEFT))
2552 size_t n = width - characters;
2553 ENSURE_ALLOCATION (xsum (length, n));
2554 DCHAR_SET (result + length, ' ', n);
2558 if (has_precision || has_width)
2560 /* We know the number of wide characters in advance. */
2564 memset (&state, '\0', sizeof (mbstate_t));
2566 ENSURE_ALLOCATION (xsum (length, characters));
2567 for (remaining = characters; remaining > 0; remaining--)
2572 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2574 count = mbtowc (&wc, arg, arg_end - arg);
2577 /* mbrtowc not consistent with mbrlen, or mbtowc
2578 not consistent with mblen. */
2580 result[length++] = wc;
2583 if (!(arg == arg_end))
2590 memset (&state, '\0', sizeof (mbstate_t));
2592 while (arg < arg_end)
2597 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2599 count = mbtowc (&wc, arg, arg_end - arg);
2602 /* mbrtowc not consistent with mbrlen, or mbtowc
2603 not consistent with mblen. */
2605 ENSURE_ALLOCATION (xsum (length, 1));
2606 result[length++] = wc;
2611 if (has_width && width > characters
2612 && (dp->flags & FLAG_LEFT))
2614 size_t n = width - characters;
2615 ENSURE_ALLOCATION (xsum (length, n));
2616 DCHAR_SET (result + length, ' ', n);
2621 /* %ls in vasnprintf. See the specification of fprintf. */
2623 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2624 const wchar_t *arg_end;
2626 # if !DCHAR_IS_TCHAR
2627 /* This code assumes that TCHAR_T is 'char'. */
2628 verify (sizeof (TCHAR_T) == 1);
2637 /* Use only as many wide characters as needed to produce
2638 at most PRECISION bytes, from the left. */
2639 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2641 memset (&state, '\0', sizeof (mbstate_t));
2645 while (precision > 0)
2647 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2651 /* Found the terminating null wide character. */
2653 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2654 count = wcrtomb (cbuf, *arg_end, &state);
2656 count = wctomb (cbuf, *arg_end);
2660 /* Cannot convert. */
2661 if (!(result == resultbuf || result == NULL))
2663 if (buf_malloced != NULL)
2664 free (buf_malloced);
2669 if (precision < count)
2672 characters += count;
2682 /* Use the entire string, and count the number of
2684 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2686 memset (&state, '\0', sizeof (mbstate_t));
2692 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2696 /* Found the terminating null wide character. */
2698 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2699 count = wcrtomb (cbuf, *arg_end, &state);
2701 count = wctomb (cbuf, *arg_end);
2705 /* Cannot convert. */
2706 if (!(result == resultbuf || result == NULL))
2708 if (buf_malloced != NULL)
2709 free (buf_malloced);
2715 characters += count;
2721 /* Use the entire string. */
2722 arg_end = arg + local_wcslen (arg);
2723 /* The number of bytes doesn't matter. */
2728 # if !DCHAR_IS_TCHAR
2729 /* Convert the string into a piece of temporary memory. */
2730 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2734 TCHAR_T *tmpptr = tmpsrc;
2736 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2738 memset (&state, '\0', sizeof (mbstate_t));
2740 for (remaining = characters; remaining > 0; )
2742 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2747 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2748 count = wcrtomb (cbuf, *arg, &state);
2750 count = wctomb (cbuf, *arg);
2753 /* Inconsistency. */
2755 memcpy (tmpptr, cbuf, count);
2760 if (!(arg == arg_end))
2764 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2766 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2767 iconveh_question_mark,
2773 int saved_errno = errno;
2775 if (!(result == resultbuf || result == NULL))
2777 if (buf_malloced != NULL)
2778 free (buf_malloced);
2780 errno = saved_errno;
2788 # if ENABLE_UNISTDIO
2789 /* Outside POSIX, it's preferrable to compare the width
2790 against the number of _characters_ of the converted
2792 w = DCHAR_MBSNLEN (result + length, characters);
2794 /* The width is compared against the number of _bytes_
2795 of the converted value, says POSIX. */
2800 /* w doesn't matter. */
2803 if (has_width && width > w
2804 && !(dp->flags & FLAG_LEFT))
2806 size_t n = width - w;
2807 ENSURE_ALLOCATION (xsum (length, n));
2808 DCHAR_SET (result + length, ' ', n);
2813 if (has_precision || has_width)
2815 /* We know the number of bytes in advance. */
2817 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2819 memset (&state, '\0', sizeof (mbstate_t));
2821 ENSURE_ALLOCATION (xsum (length, characters));
2822 for (remaining = characters; remaining > 0; )
2824 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2829 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2830 count = wcrtomb (cbuf, *arg, &state);
2832 count = wctomb (cbuf, *arg);
2835 /* Inconsistency. */
2837 memcpy (result + length, cbuf, count);
2842 if (!(arg == arg_end))
2847 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2849 memset (&state, '\0', sizeof (mbstate_t));
2851 while (arg < arg_end)
2853 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2858 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2859 count = wcrtomb (cbuf, *arg, &state);
2861 count = wctomb (cbuf, *arg);
2865 /* Cannot convert. */
2866 if (!(result == resultbuf || result == NULL))
2868 if (buf_malloced != NULL)
2869 free (buf_malloced);
2874 ENSURE_ALLOCATION (xsum (length, count));
2875 memcpy (result + length, cbuf, count);
2881 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2882 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2884 length += tmpdst_len;
2887 if (has_width && width > w
2888 && (dp->flags & FLAG_LEFT))
2890 size_t n = width - w;
2891 ENSURE_ALLOCATION (xsum (length, n));
2892 DCHAR_SET (result + length, ' ', n);
2899 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2900 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2901 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2903 # if NEED_PRINTF_DOUBLE
2904 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2906 # if NEED_PRINTF_LONG_DOUBLE
2907 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2913 arg_type type = a.arg[dp->arg_index].type;
2914 int flags = dp->flags;
2920 DCHAR_T tmpbuf[700];
2927 if (dp->width_start != dp->width_end)
2929 if (dp->width_arg_index != ARG_NONE)
2933 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2935 arg = a.arg[dp->width_arg_index].a.a_int;
2938 /* "A negative field width is taken as a '-' flag
2939 followed by a positive field width." */
2941 width = (unsigned int) (-arg);
2948 const FCHAR_T *digitp = dp->width_start;
2951 width = xsum (xtimes (width, 10), *digitp++ - '0');
2952 while (digitp != dp->width_end);
2959 if (dp->precision_start != dp->precision_end)
2961 if (dp->precision_arg_index != ARG_NONE)
2965 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2967 arg = a.arg[dp->precision_arg_index].a.a_int;
2968 /* "A negative precision is taken as if the precision
2978 const FCHAR_T *digitp = dp->precision_start + 1;
2981 while (digitp != dp->precision_end)
2982 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2987 /* Allocate a temporary buffer of sufficient size. */
2988 if (type == TYPE_LONGDOUBLE)
2990 (unsigned int) ((LDBL_DIG + 1)
2991 * 0.831 /* decimal -> hexadecimal */
2993 + 1; /* turn floor into ceil */
2996 (unsigned int) ((DBL_DIG + 1)
2997 * 0.831 /* decimal -> hexadecimal */
2999 + 1; /* turn floor into ceil */
3000 if (tmp_length < precision)
3001 tmp_length = precision;
3002 /* Account for sign, decimal point etc. */
3003 tmp_length = xsum (tmp_length, 12);
3005 if (tmp_length < width)
3008 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3010 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3014 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3016 if (size_overflow_p (tmp_memsize))
3017 /* Overflow, would lead to out of memory. */
3019 tmp = (DCHAR_T *) malloc (tmp_memsize);
3021 /* Out of memory. */
3027 if (type == TYPE_LONGDOUBLE)
3029 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
3030 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3034 if (dp->conversion == 'A')
3036 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3040 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3046 DECL_LONG_DOUBLE_ROUNDING
3048 BEGIN_LONG_DOUBLE_ROUNDING ();
3050 if (signbit (arg)) /* arg < 0.0L or negative zero */
3058 else if (flags & FLAG_SHOWSIGN)
3060 else if (flags & FLAG_SPACE)
3063 if (arg > 0.0L && arg + arg == arg)
3065 if (dp->conversion == 'A')
3067 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3071 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3077 long double mantissa;
3080 mantissa = printf_frexpl (arg, &exponent);
3088 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
3090 /* Round the mantissa. */
3091 long double tail = mantissa;
3094 for (q = precision; ; q--)
3096 int digit = (int) tail;
3100 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
3109 for (q = precision; q > 0; q--)
3115 *p++ = dp->conversion - 'A' + 'X';
3120 digit = (int) mantissa;
3123 if ((flags & FLAG_ALT)
3124 || mantissa > 0.0L || precision > 0)
3126 *p++ = decimal_point_char ();
3127 /* This loop terminates because we assume
3128 that FLT_RADIX is a power of 2. */
3129 while (mantissa > 0.0L)
3132 digit = (int) mantissa;
3137 : dp->conversion - 10);
3141 while (precision > 0)
3148 *p++ = dp->conversion - 'A' + 'P';
3149 # if WIDE_CHAR_VERSION
3151 static const wchar_t decimal_format[] =
3152 { '%', '+', 'd', '\0' };
3153 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3158 if (sizeof (DCHAR_T) == 1)
3160 sprintf ((char *) p, "%+d", exponent);
3168 sprintf (expbuf, "%+d", exponent);
3169 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3175 END_LONG_DOUBLE_ROUNDING ();
3183 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
3184 double arg = a.arg[dp->arg_index].a.a_double;
3188 if (dp->conversion == 'A')
3190 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3194 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3201 if (signbit (arg)) /* arg < 0.0 or negative zero */
3209 else if (flags & FLAG_SHOWSIGN)
3211 else if (flags & FLAG_SPACE)
3214 if (arg > 0.0 && arg + arg == arg)
3216 if (dp->conversion == 'A')
3218 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3222 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3231 mantissa = printf_frexp (arg, &exponent);
3239 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
3241 /* Round the mantissa. */
3242 double tail = mantissa;
3245 for (q = precision; ; q--)
3247 int digit = (int) tail;
3251 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
3260 for (q = precision; q > 0; q--)
3266 *p++ = dp->conversion - 'A' + 'X';
3271 digit = (int) mantissa;
3274 if ((flags & FLAG_ALT)
3275 || mantissa > 0.0 || precision > 0)
3277 *p++ = decimal_point_char ();
3278 /* This loop terminates because we assume
3279 that FLT_RADIX is a power of 2. */
3280 while (mantissa > 0.0)
3283 digit = (int) mantissa;
3288 : dp->conversion - 10);
3292 while (precision > 0)
3299 *p++ = dp->conversion - 'A' + 'P';
3300 # if WIDE_CHAR_VERSION
3302 static const wchar_t decimal_format[] =
3303 { '%', '+', 'd', '\0' };
3304 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3309 if (sizeof (DCHAR_T) == 1)
3311 sprintf ((char *) p, "%+d", exponent);
3319 sprintf (expbuf, "%+d", exponent);
3320 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3330 /* The generated string now extends from tmp to p, with the
3331 zero padding insertion point being at pad_ptr. */
3332 if (has_width && p - tmp < width)
3334 size_t pad = width - (p - tmp);
3335 DCHAR_T *end = p + pad;
3337 if (flags & FLAG_LEFT)
3339 /* Pad with spaces on the right. */
3340 for (; pad > 0; pad--)
3343 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3345 /* Pad with zeroes. */
3350 for (; pad > 0; pad--)
3355 /* Pad with spaces on the left. */
3360 for (; pad > 0; pad--)
3368 size_t count = p - tmp;
3370 if (count >= tmp_length)
3371 /* tmp_length was incorrectly calculated - fix the
3375 /* Make room for the result. */
3376 if (count >= allocated - length)
3378 size_t n = xsum (length, count);
3380 ENSURE_ALLOCATION (n);
3383 /* Append the result. */
3384 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3391 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3392 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3393 || dp->conversion == 'e' || dp->conversion == 'E'
3394 || dp->conversion == 'g' || dp->conversion == 'G'
3395 || dp->conversion == 'a' || dp->conversion == 'A')
3397 # if NEED_PRINTF_DOUBLE
3398 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3399 # elif NEED_PRINTF_INFINITE_DOUBLE
3400 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3401 /* The systems (mingw) which produce wrong output
3402 for Inf, -Inf, and NaN also do so for -0.0.
3403 Therefore we treat this case here as well. */
3404 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3406 # if NEED_PRINTF_LONG_DOUBLE
3407 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3408 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3409 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3410 /* Some systems produce wrong output for Inf,
3411 -Inf, and NaN. Some systems in this category
3412 (IRIX 5.3) also do so for -0.0. Therefore we
3413 treat this case here as well. */
3414 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3418 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3419 arg_type type = a.arg[dp->arg_index].type;
3421 int flags = dp->flags;
3427 DCHAR_T tmpbuf[700];
3434 if (dp->width_start != dp->width_end)
3436 if (dp->width_arg_index != ARG_NONE)
3440 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3442 arg = a.arg[dp->width_arg_index].a.a_int;
3445 /* "A negative field width is taken as a '-' flag
3446 followed by a positive field width." */
3448 width = (unsigned int) (-arg);
3455 const FCHAR_T *digitp = dp->width_start;
3458 width = xsum (xtimes (width, 10), *digitp++ - '0');
3459 while (digitp != dp->width_end);
3466 if (dp->precision_start != dp->precision_end)
3468 if (dp->precision_arg_index != ARG_NONE)
3472 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3474 arg = a.arg[dp->precision_arg_index].a.a_int;
3475 /* "A negative precision is taken as if the precision
3485 const FCHAR_T *digitp = dp->precision_start + 1;
3488 while (digitp != dp->precision_end)
3489 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3494 /* POSIX specifies the default precision to be 6 for %f, %F,
3495 %e, %E, but not for %g, %G. Implementations appear to use
3496 the same default precision also for %g, %G. But for %a, %A,
3497 the default precision is 0. */
3499 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3502 /* Allocate a temporary buffer of sufficient size. */
3503 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3504 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3505 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3506 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3507 # elif NEED_PRINTF_LONG_DOUBLE
3508 tmp_length = LDBL_DIG + 1;
3509 # elif NEED_PRINTF_DOUBLE
3510 tmp_length = DBL_DIG + 1;
3514 if (tmp_length < precision)
3515 tmp_length = precision;
3516 # if NEED_PRINTF_LONG_DOUBLE
3517 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3518 if (type == TYPE_LONGDOUBLE)
3520 if (dp->conversion == 'f' || dp->conversion == 'F')
3522 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3523 if (!(isnanl (arg) || arg + arg == arg))
3525 /* arg is finite and nonzero. */
3526 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3527 if (exponent >= 0 && tmp_length < exponent + precision)
3528 tmp_length = exponent + precision;
3532 # if NEED_PRINTF_DOUBLE
3533 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3534 if (type == TYPE_DOUBLE)
3536 if (dp->conversion == 'f' || dp->conversion == 'F')
3538 double arg = a.arg[dp->arg_index].a.a_double;
3539 if (!(isnand (arg) || arg + arg == arg))
3541 /* arg is finite and nonzero. */
3542 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3543 if (exponent >= 0 && tmp_length < exponent + precision)
3544 tmp_length = exponent + precision;
3548 /* Account for sign, decimal point etc. */
3549 tmp_length = xsum (tmp_length, 12);
3551 if (tmp_length < width)
3554 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3556 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3560 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3562 if (size_overflow_p (tmp_memsize))
3563 /* Overflow, would lead to out of memory. */
3565 tmp = (DCHAR_T *) malloc (tmp_memsize);
3567 /* Out of memory. */
3574 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3575 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3576 if (type == TYPE_LONGDOUBLE)
3579 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3583 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3585 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3589 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3595 DECL_LONG_DOUBLE_ROUNDING
3597 BEGIN_LONG_DOUBLE_ROUNDING ();
3599 if (signbit (arg)) /* arg < 0.0L or negative zero */
3607 else if (flags & FLAG_SHOWSIGN)
3609 else if (flags & FLAG_SPACE)
3612 if (arg > 0.0L && arg + arg == arg)
3614 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3616 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3620 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3625 # if NEED_PRINTF_LONG_DOUBLE
3628 if (dp->conversion == 'f' || dp->conversion == 'F')
3634 scale10_round_decimal_long_double (arg, precision);
3637 END_LONG_DOUBLE_ROUNDING ();
3640 ndigits = strlen (digits);
3642 if (ndigits > precision)
3646 *p++ = digits[ndigits];
3648 while (ndigits > precision);
3651 /* Here ndigits <= precision. */
3652 if ((flags & FLAG_ALT) || precision > 0)
3654 *p++ = decimal_point_char ();
3655 for (; precision > ndigits; precision--)
3660 *p++ = digits[ndigits];
3666 else if (dp->conversion == 'e' || dp->conversion == 'E')
3674 if ((flags & FLAG_ALT) || precision > 0)
3676 *p++ = decimal_point_char ();
3677 for (; precision > 0; precision--)
3688 exponent = floorlog10l (arg);
3693 scale10_round_decimal_long_double (arg,
3694 (int)precision - exponent);
3697 END_LONG_DOUBLE_ROUNDING ();
3700 ndigits = strlen (digits);
3702 if (ndigits == precision + 1)
3704 if (ndigits < precision
3705 || ndigits > precision + 2)
3706 /* The exponent was not guessed
3707 precisely enough. */
3710 /* None of two values of exponent is
3711 the right one. Prevent an endless
3715 if (ndigits == precision)
3721 /* Here ndigits = precision+1. */
3722 if (is_borderline (digits, precision))
3724 /* Maybe the exponent guess was too high
3725 and a smaller exponent can be reached
3726 by turning a 10...0 into 9...9x. */
3728 scale10_round_decimal_long_double (arg,
3729 (int)precision - exponent + 1);
3730 if (digits2 == NULL)
3733 END_LONG_DOUBLE_ROUNDING ();
3736 if (strlen (digits2) == precision + 1)
3745 /* Here ndigits = precision+1. */
3747 *p++ = digits[--ndigits];
3748 if ((flags & FLAG_ALT) || precision > 0)
3750 *p++ = decimal_point_char ();
3754 *p++ = digits[ndigits];
3761 *p++ = dp->conversion; /* 'e' or 'E' */
3762 # if WIDE_CHAR_VERSION
3764 static const wchar_t decimal_format[] =
3765 { '%', '+', '.', '2', 'd', '\0' };
3766 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3771 if (sizeof (DCHAR_T) == 1)
3773 sprintf ((char *) p, "%+.2d", exponent);
3781 sprintf (expbuf, "%+.2d", exponent);
3782 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3787 else if (dp->conversion == 'g' || dp->conversion == 'G')
3791 /* precision >= 1. */
3794 /* The exponent is 0, >= -4, < precision.
3795 Use fixed-point notation. */
3797 size_t ndigits = precision;
3798 /* Number of trailing zeroes that have to be
3801 (flags & FLAG_ALT ? 0 : precision - 1);
3805 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3807 *p++ = decimal_point_char ();
3808 while (ndigits > nzeroes)
3824 exponent = floorlog10l (arg);
3829 scale10_round_decimal_long_double (arg,
3830 (int)(precision - 1) - exponent);
3833 END_LONG_DOUBLE_ROUNDING ();
3836 ndigits = strlen (digits);
3838 if (ndigits == precision)
3840 if (ndigits < precision - 1
3841 || ndigits > precision + 1)
3842 /* The exponent was not guessed
3843 precisely enough. */
3846 /* None of two values of exponent is
3847 the right one. Prevent an endless
3851 if (ndigits < precision)
3857 /* Here ndigits = precision. */
3858 if (is_borderline (digits, precision - 1))
3860 /* Maybe the exponent guess was too high
3861 and a smaller exponent can be reached
3862 by turning a 10...0 into 9...9x. */
3864 scale10_round_decimal_long_double (arg,
3865 (int)(precision - 1) - exponent + 1);
3866 if (digits2 == NULL)
3869 END_LONG_DOUBLE_ROUNDING ();
3872 if (strlen (digits2) == precision)
3881 /* Here ndigits = precision. */
3883 /* Determine the number of trailing zeroes
3884 that have to be dropped. */
3886 if ((flags & FLAG_ALT) == 0)
3887 while (nzeroes < ndigits
3888 && digits[nzeroes] == '0')
3891 /* The exponent is now determined. */
3893 && exponent < (long)precision)
3895 /* Fixed-point notation:
3896 max(exponent,0)+1 digits, then the
3897 decimal point, then the remaining
3898 digits without trailing zeroes. */
3901 size_t count = exponent + 1;
3902 /* Note: count <= precision = ndigits. */
3903 for (; count > 0; count--)
3904 *p++ = digits[--ndigits];
3905 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3907 *p++ = decimal_point_char ();
3908 while (ndigits > nzeroes)
3911 *p++ = digits[ndigits];
3917 size_t count = -exponent - 1;
3919 *p++ = decimal_point_char ();
3920 for (; count > 0; count--)
3922 while (ndigits > nzeroes)
3925 *p++ = digits[ndigits];
3931 /* Exponential notation. */
3932 *p++ = digits[--ndigits];
3933 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3935 *p++ = decimal_point_char ();
3936 while (ndigits > nzeroes)
3939 *p++ = digits[ndigits];
3942 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3943 # if WIDE_CHAR_VERSION
3945 static const wchar_t decimal_format[] =
3946 { '%', '+', '.', '2', 'd', '\0' };
3947 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3952 if (sizeof (DCHAR_T) == 1)
3954 sprintf ((char *) p, "%+.2d", exponent);
3962 sprintf (expbuf, "%+.2d", exponent);
3963 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3975 /* arg is finite. */
3981 if (dp->conversion == 'f' || dp->conversion == 'F')
3984 if ((flags & FLAG_ALT) || precision > 0)
3986 *p++ = decimal_point_char ();
3987 for (; precision > 0; precision--)
3991 else if (dp->conversion == 'e' || dp->conversion == 'E')
3994 if ((flags & FLAG_ALT) || precision > 0)
3996 *p++ = decimal_point_char ();
3997 for (; precision > 0; precision--)
4000 *p++ = dp->conversion; /* 'e' or 'E' */
4005 else if (dp->conversion == 'g' || dp->conversion == 'G')
4008 if (flags & FLAG_ALT)
4011 (precision > 0 ? precision - 1 : 0);
4012 *p++ = decimal_point_char ();
4013 for (; ndigits > 0; --ndigits)
4017 else if (dp->conversion == 'a' || dp->conversion == 'A')
4020 *p++ = dp->conversion - 'A' + 'X';
4023 if ((flags & FLAG_ALT) || precision > 0)
4025 *p++ = decimal_point_char ();
4026 for (; precision > 0; precision--)
4029 *p++ = dp->conversion - 'A' + 'P';
4038 END_LONG_DOUBLE_ROUNDING ();
4041 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4045 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4047 double arg = a.arg[dp->arg_index].a.a_double;
4051 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4053 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4057 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4064 if (signbit (arg)) /* arg < 0.0 or negative zero */
4072 else if (flags & FLAG_SHOWSIGN)
4074 else if (flags & FLAG_SPACE)
4077 if (arg > 0.0 && arg + arg == arg)
4079 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4081 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4085 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4090 # if NEED_PRINTF_DOUBLE
4093 if (dp->conversion == 'f' || dp->conversion == 'F')
4099 scale10_round_decimal_double (arg, precision);
4102 ndigits = strlen (digits);
4104 if (ndigits > precision)
4108 *p++ = digits[ndigits];
4110 while (ndigits > precision);
4113 /* Here ndigits <= precision. */
4114 if ((flags & FLAG_ALT) || precision > 0)
4116 *p++ = decimal_point_char ();
4117 for (; precision > ndigits; precision--)
4122 *p++ = digits[ndigits];
4128 else if (dp->conversion == 'e' || dp->conversion == 'E')
4136 if ((flags & FLAG_ALT) || precision > 0)
4138 *p++ = decimal_point_char ();
4139 for (; precision > 0; precision--)
4150 exponent = floorlog10 (arg);
4155 scale10_round_decimal_double (arg,
4156 (int)precision - exponent);
4159 ndigits = strlen (digits);
4161 if (ndigits == precision + 1)
4163 if (ndigits < precision
4164 || ndigits > precision + 2)
4165 /* The exponent was not guessed
4166 precisely enough. */
4169 /* None of two values of exponent is
4170 the right one. Prevent an endless
4174 if (ndigits == precision)
4180 /* Here ndigits = precision+1. */
4181 if (is_borderline (digits, precision))
4183 /* Maybe the exponent guess was too high
4184 and a smaller exponent can be reached
4185 by turning a 10...0 into 9...9x. */
4187 scale10_round_decimal_double (arg,
4188 (int)precision - exponent + 1);
4189 if (digits2 == NULL)
4194 if (strlen (digits2) == precision + 1)
4203 /* Here ndigits = precision+1. */
4205 *p++ = digits[--ndigits];
4206 if ((flags & FLAG_ALT) || precision > 0)
4208 *p++ = decimal_point_char ();
4212 *p++ = digits[ndigits];
4219 *p++ = dp->conversion; /* 'e' or 'E' */
4220 # if WIDE_CHAR_VERSION
4222 static const wchar_t decimal_format[] =
4223 /* Produce the same number of exponent digits
4224 as the native printf implementation. */
4225 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4226 { '%', '+', '.', '3', 'd', '\0' };
4228 { '%', '+', '.', '2', 'd', '\0' };
4230 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4236 static const char decimal_format[] =
4237 /* Produce the same number of exponent digits
4238 as the native printf implementation. */
4239 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4244 if (sizeof (DCHAR_T) == 1)
4246 sprintf ((char *) p, decimal_format, exponent);
4254 sprintf (expbuf, decimal_format, exponent);
4255 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4261 else if (dp->conversion == 'g' || dp->conversion == 'G')
4265 /* precision >= 1. */
4268 /* The exponent is 0, >= -4, < precision.
4269 Use fixed-point notation. */
4271 size_t ndigits = precision;
4272 /* Number of trailing zeroes that have to be
4275 (flags & FLAG_ALT ? 0 : precision - 1);
4279 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4281 *p++ = decimal_point_char ();
4282 while (ndigits > nzeroes)
4298 exponent = floorlog10 (arg);
4303 scale10_round_decimal_double (arg,
4304 (int)(precision - 1) - exponent);
4307 ndigits = strlen (digits);
4309 if (ndigits == precision)
4311 if (ndigits < precision - 1
4312 || ndigits > precision + 1)
4313 /* The exponent was not guessed
4314 precisely enough. */
4317 /* None of two values of exponent is
4318 the right one. Prevent an endless
4322 if (ndigits < precision)
4328 /* Here ndigits = precision. */
4329 if (is_borderline (digits, precision - 1))
4331 /* Maybe the exponent guess was too high
4332 and a smaller exponent can be reached
4333 by turning a 10...0 into 9...9x. */
4335 scale10_round_decimal_double (arg,
4336 (int)(precision - 1) - exponent + 1);
4337 if (digits2 == NULL)
4342 if (strlen (digits2) == precision)
4351 /* Here ndigits = precision. */
4353 /* Determine the number of trailing zeroes
4354 that have to be dropped. */
4356 if ((flags & FLAG_ALT) == 0)
4357 while (nzeroes < ndigits
4358 && digits[nzeroes] == '0')
4361 /* The exponent is now determined. */
4363 && exponent < (long)precision)
4365 /* Fixed-point notation:
4366 max(exponent,0)+1 digits, then the
4367 decimal point, then the remaining
4368 digits without trailing zeroes. */
4371 size_t count = exponent + 1;
4372 /* Note: count <= precision = ndigits. */
4373 for (; count > 0; count--)
4374 *p++ = digits[--ndigits];
4375 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4377 *p++ = decimal_point_char ();
4378 while (ndigits > nzeroes)
4381 *p++ = digits[ndigits];
4387 size_t count = -exponent - 1;
4389 *p++ = decimal_point_char ();
4390 for (; count > 0; count--)
4392 while (ndigits > nzeroes)
4395 *p++ = digits[ndigits];
4401 /* Exponential notation. */
4402 *p++ = digits[--ndigits];
4403 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4405 *p++ = decimal_point_char ();
4406 while (ndigits > nzeroes)
4409 *p++ = digits[ndigits];
4412 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4413 # if WIDE_CHAR_VERSION
4415 static const wchar_t decimal_format[] =
4416 /* Produce the same number of exponent digits
4417 as the native printf implementation. */
4418 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4419 { '%', '+', '.', '3', 'd', '\0' };
4421 { '%', '+', '.', '2', 'd', '\0' };
4423 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4429 static const char decimal_format[] =
4430 /* Produce the same number of exponent digits
4431 as the native printf implementation. */
4432 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4437 if (sizeof (DCHAR_T) == 1)
4439 sprintf ((char *) p, decimal_format, exponent);
4447 sprintf (expbuf, decimal_format, exponent);
4448 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4461 /* arg is finite. */
4467 if (dp->conversion == 'f' || dp->conversion == 'F')
4470 if ((flags & FLAG_ALT) || precision > 0)
4472 *p++ = decimal_point_char ();
4473 for (; precision > 0; precision--)
4477 else if (dp->conversion == 'e' || dp->conversion == 'E')
4480 if ((flags & FLAG_ALT) || precision > 0)
4482 *p++ = decimal_point_char ();
4483 for (; precision > 0; precision--)
4486 *p++ = dp->conversion; /* 'e' or 'E' */
4488 /* Produce the same number of exponent digits as
4489 the native printf implementation. */
4490 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4496 else if (dp->conversion == 'g' || dp->conversion == 'G')
4499 if (flags & FLAG_ALT)
4502 (precision > 0 ? precision - 1 : 0);
4503 *p++ = decimal_point_char ();
4504 for (; ndigits > 0; --ndigits)
4516 /* The generated string now extends from tmp to p, with the
4517 zero padding insertion point being at pad_ptr. */
4518 if (has_width && p - tmp < width)
4520 size_t pad = width - (p - tmp);
4521 DCHAR_T *end = p + pad;
4523 if (flags & FLAG_LEFT)
4525 /* Pad with spaces on the right. */
4526 for (; pad > 0; pad--)
4529 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4531 /* Pad with zeroes. */
4536 for (; pad > 0; pad--)
4541 /* Pad with spaces on the left. */
4546 for (; pad > 0; pad--)
4554 size_t count = p - tmp;
4556 if (count >= tmp_length)
4557 /* tmp_length was incorrectly calculated - fix the
4561 /* Make room for the result. */
4562 if (count >= allocated - length)
4564 size_t n = xsum (length, count);
4566 ENSURE_ALLOCATION (n);
4569 /* Append the result. */
4570 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4579 arg_type type = a.arg[dp->arg_index].type;
4580 int flags = dp->flags;
4581 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4585 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4589 #if NEED_PRINTF_UNBOUNDED_PRECISION
4592 # define prec_ourselves 0
4594 #if NEED_PRINTF_FLAG_LEFTADJUST
4595 # define pad_ourselves 1
4596 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4599 # define pad_ourselves 0
4602 unsigned int prefix_count;
4603 int prefixes[2] IF_LINT (= { 0 });
4607 TCHAR_T tmpbuf[700];
4611 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4614 if (dp->width_start != dp->width_end)
4616 if (dp->width_arg_index != ARG_NONE)
4620 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4622 arg = a.arg[dp->width_arg_index].a.a_int;
4625 /* "A negative field width is taken as a '-' flag
4626 followed by a positive field width." */
4628 width = (unsigned int) (-arg);
4635 const FCHAR_T *digitp = dp->width_start;
4638 width = xsum (xtimes (width, 10), *digitp++ - '0');
4639 while (digitp != dp->width_end);
4645 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4648 if (dp->precision_start != dp->precision_end)
4650 if (dp->precision_arg_index != ARG_NONE)
4654 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4656 arg = a.arg[dp->precision_arg_index].a.a_int;
4657 /* "A negative precision is taken as if the precision
4667 const FCHAR_T *digitp = dp->precision_start + 1;
4670 while (digitp != dp->precision_end)
4671 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4677 /* Decide whether to handle the precision ourselves. */
4678 #if NEED_PRINTF_UNBOUNDED_PRECISION
4679 switch (dp->conversion)
4681 case 'd': case 'i': case 'u':
4683 case 'x': case 'X': case 'p':
4684 prec_ourselves = has_precision && (precision > 0);
4692 /* Decide whether to perform the padding ourselves. */
4693 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4694 switch (dp->conversion)
4696 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4697 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4698 to perform the padding after this conversion. Functions
4699 with unistdio extensions perform the padding based on
4700 character count rather than element count. */
4703 # if NEED_PRINTF_FLAG_ZERO
4704 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4710 pad_ourselves = prec_ourselves;
4716 /* Allocate a temporary buffer of sufficient size for calling
4719 MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
4720 flags, width, has_precision, precision,
4723 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4727 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4729 if (size_overflow_p (tmp_memsize))
4730 /* Overflow, would lead to out of memory. */
4732 tmp = (TCHAR_T *) malloc (tmp_memsize);
4734 /* Out of memory. */
4739 /* Construct the format string for calling snprintf or
4743 #if NEED_PRINTF_FLAG_GROUPING
4744 /* The underlying implementation doesn't support the ' flag.
4745 Produce no grouping characters in this case; this is
4746 acceptable because the grouping is locale dependent. */
4748 if (flags & FLAG_GROUP)
4751 if (flags & FLAG_LEFT)
4753 if (flags & FLAG_SHOWSIGN)
4755 if (flags & FLAG_SPACE)
4757 if (flags & FLAG_ALT)
4761 if (flags & FLAG_ZERO)
4763 if (dp->width_start != dp->width_end)
4765 size_t n = dp->width_end - dp->width_start;
4766 /* The width specification is known to consist only
4767 of standard ASCII characters. */
4768 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4770 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4775 const FCHAR_T *mp = dp->width_start;
4777 *fbp++ = (unsigned char) *mp++;
4782 if (!prec_ourselves)
4784 if (dp->precision_start != dp->precision_end)
4786 size_t n = dp->precision_end - dp->precision_start;
4787 /* The precision specification is known to consist only
4788 of standard ASCII characters. */
4789 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4791 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4796 const FCHAR_T *mp = dp->precision_start;
4798 *fbp++ = (unsigned char) *mp++;
4806 #if HAVE_LONG_LONG_INT
4807 case TYPE_LONGLONGINT:
4808 case TYPE_ULONGLONGINT:
4809 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4822 case TYPE_WIDE_CHAR:
4825 case TYPE_WIDE_STRING:
4829 case TYPE_LONGDOUBLE:
4835 #if NEED_PRINTF_DIRECTIVE_F
4836 if (dp->conversion == 'F')
4840 *fbp = dp->conversion;
4842 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4847 /* On glibc2 systems from glibc >= 2.3 - probably also older
4848 ones - we know that snprintf's returns value conforms to
4849 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4850 Therefore we can avoid using %n in this situation.
4851 On glibc2 systems from 2004-10-18 or newer, the use of %n
4852 in format strings in writable memory may crash the program
4853 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4854 in this situation. */
4855 /* On native Win32 systems (such as mingw), we can avoid using
4857 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4858 snprintf does not write more than the specified number
4859 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4860 '4', '5', '6' into buf, not '4', '5', '\0'.)
4861 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4862 allows us to recognize the case of an insufficient
4863 buffer size: it returns -1 in this case.
4864 On native Win32 systems (such as mingw) where the OS is
4865 Windows Vista, the use of %n in format strings by default
4866 crashes the program. See
4867 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4868 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4869 So we should avoid %n in this situation. */
4876 /* Construct the arguments for calling snprintf or sprintf. */
4878 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4880 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4882 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4884 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4886 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4888 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4892 /* The SNPRINTF result is appended after result[0..length].
4893 The latter is an array of DCHAR_T; SNPRINTF appends an
4894 array of TCHAR_T to it. This is possible because
4895 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4896 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4897 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4898 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4899 where an snprintf() with maxlen==1 acts like sprintf(). */
4900 ENSURE_ALLOCATION (xsum (length,
4901 (2 + TCHARS_PER_DCHAR - 1)
4902 / TCHARS_PER_DCHAR));
4903 /* Prepare checking whether snprintf returns the count
4905 *(TCHAR_T *) (result + length) = '\0';
4916 size_t maxlen = allocated - length;
4917 /* SNPRINTF can fail if its second argument is
4919 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4920 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4921 maxlen = maxlen * TCHARS_PER_DCHAR;
4922 # define SNPRINTF_BUF(arg) \
4923 switch (prefix_count) \
4926 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4931 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4933 prefixes[0], arg, &count); \
4936 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4938 prefixes[0], prefixes[1], arg, \
4945 # define SNPRINTF_BUF(arg) \
4946 switch (prefix_count) \
4949 count = sprintf (tmp, buf, arg); \
4952 count = sprintf (tmp, buf, prefixes[0], arg); \
4955 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4968 int arg = a.arg[dp->arg_index].a.a_schar;
4974 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4980 int arg = a.arg[dp->arg_index].a.a_short;
4986 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4992 int arg = a.arg[dp->arg_index].a.a_int;
4998 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
5004 long int arg = a.arg[dp->arg_index].a.a_longint;
5010 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
5014 #if HAVE_LONG_LONG_INT
5015 case TYPE_LONGLONGINT:
5017 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
5021 case TYPE_ULONGLONGINT:
5023 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
5030 double arg = a.arg[dp->arg_index].a.a_double;
5034 case TYPE_LONGDOUBLE:
5036 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5042 int arg = a.arg[dp->arg_index].a.a_char;
5047 case TYPE_WIDE_CHAR:
5049 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5056 const char *arg = a.arg[dp->arg_index].a.a_string;
5061 case TYPE_WIDE_STRING:
5063 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5070 void *arg = a.arg[dp->arg_index].a.a_pointer;
5079 /* Portability: Not all implementations of snprintf()
5080 are ISO C 99 compliant. Determine the number of
5081 bytes that snprintf() has produced or would have
5085 /* Verify that snprintf() has NUL-terminated its
5088 && ((TCHAR_T *) (result + length)) [count] != '\0')
5090 /* Portability hack. */
5091 if (retcount > count)
5096 /* snprintf() doesn't understand the '%n'
5100 /* Don't use the '%n' directive; instead, look
5101 at the snprintf() return value. */
5107 /* Look at the snprintf() return value. */
5110 # if !HAVE_SNPRINTF_RETVAL_C99
5111 /* HP-UX 10.20 snprintf() is doubly deficient:
5112 It doesn't understand the '%n' directive,
5113 *and* it returns -1 (rather than the length
5114 that would have been required) when the
5115 buffer is too small.
5116 But a failure at this point can also come
5117 from other reasons than a too small buffer,
5118 such as an invalid wide string argument to
5119 the %ls directive, or possibly an invalid
5120 floating-point argument. */
5122 MAX_ROOM_NEEDED (&a, dp->arg_index,
5123 dp->conversion, type, flags,
5124 width, has_precision,
5125 precision, pad_ourselves);
5127 if (maxlen < tmp_length)
5129 /* Make more room. But try to do through
5130 this reallocation only once. */
5131 size_t bigger_need =
5134 TCHARS_PER_DCHAR - 1)
5135 / TCHARS_PER_DCHAR);
5136 /* And always grow proportionally.
5137 (There may be several arguments, each
5138 needing a little more room than the
5140 size_t bigger_need2 =
5141 xsum (xtimes (allocated, 2), 12);
5142 if (bigger_need < bigger_need2)
5143 bigger_need = bigger_need2;
5144 ENSURE_ALLOCATION (bigger_need);
5155 /* Attempt to handle failure. */
5158 /* SNPRINTF or sprintf failed. Save and use the errno
5159 that it has set, if any. */
5160 int saved_errno = errno;
5162 if (!(result == resultbuf || result == NULL))
5164 if (buf_malloced != NULL)
5165 free (buf_malloced);
5170 : (dp->conversion == 'c' || dp->conversion == 's'
5177 /* Handle overflow of the allocated buffer.
5178 If such an overflow occurs, a C99 compliant snprintf()
5179 returns a count >= maxlen. However, a non-compliant
5180 snprintf() function returns only count = maxlen - 1. To
5181 cover both cases, test whether count >= maxlen - 1. */
5182 if ((unsigned int) count + 1 >= maxlen)
5184 /* If maxlen already has attained its allowed maximum,
5185 allocating more memory will not increase maxlen.
5186 Instead of looping, bail out. */
5187 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5191 /* Need at least (count + 1) * sizeof (TCHAR_T)
5192 bytes. (The +1 is for the trailing NUL.)
5193 But ask for (count + 2) * sizeof (TCHAR_T)
5194 bytes, so that in the next round, we likely get
5195 maxlen > (unsigned int) count + 1
5196 and so we don't get here again.
5197 And allocate proportionally, to avoid looping
5198 eternally if snprintf() reports a too small
5202 ((unsigned int) count + 2
5203 + TCHARS_PER_DCHAR - 1)
5204 / TCHARS_PER_DCHAR),
5205 xtimes (allocated, 2));
5207 ENSURE_ALLOCATION (n);
5213 #if NEED_PRINTF_UNBOUNDED_PRECISION
5216 /* Handle the precision. */
5219 (TCHAR_T *) (result + length);
5223 size_t prefix_count;
5227 /* Put the additional zeroes after the sign. */
5229 && (*prec_ptr == '-' || *prec_ptr == '+'
5230 || *prec_ptr == ' '))
5232 /* Put the additional zeroes after the 0x prefix if
5233 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5235 && prec_ptr[0] == '0'
5236 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5239 move = count - prefix_count;
5240 if (precision > move)
5242 /* Insert zeroes. */
5243 size_t insert = precision - move;
5249 (count + insert + TCHARS_PER_DCHAR - 1)
5250 / TCHARS_PER_DCHAR);
5251 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5252 ENSURE_ALLOCATION (n);
5253 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5254 prec_ptr = (TCHAR_T *) (result + length);
5257 prec_end = prec_ptr + count;
5258 prec_ptr += prefix_count;
5260 while (prec_end > prec_ptr)
5263 prec_end[insert] = prec_end[0];
5269 while (prec_end > prec_ptr);
5277 if (count >= tmp_length)
5278 /* tmp_length was incorrectly calculated - fix the
5284 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5285 if (dp->conversion == 'c' || dp->conversion == 's')
5287 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5289 The result string is not certainly ASCII. */
5290 const TCHAR_T *tmpsrc;
5293 /* This code assumes that TCHAR_T is 'char'. */
5294 verify (sizeof (TCHAR_T) == 1);
5296 tmpsrc = (TCHAR_T *) (result + length);
5301 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5302 iconveh_question_mark,
5308 int saved_errno = errno;
5309 if (!(result == resultbuf || result == NULL))
5311 if (buf_malloced != NULL)
5312 free (buf_malloced);
5314 errno = saved_errno;
5317 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5318 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5324 /* The result string is ASCII.
5325 Simple 1:1 conversion. */
5327 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5328 no-op conversion, in-place on the array starting
5329 at (result + length). */
5330 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5333 const TCHAR_T *tmpsrc;
5338 if (result == resultbuf)
5340 tmpsrc = (TCHAR_T *) (result + length);
5341 /* ENSURE_ALLOCATION will not move tmpsrc
5342 (because it's part of resultbuf). */
5343 ENSURE_ALLOCATION (xsum (length, count));
5347 /* ENSURE_ALLOCATION will move the array
5348 (because it uses realloc(). */
5349 ENSURE_ALLOCATION (xsum (length, count));
5350 tmpsrc = (TCHAR_T *) (result + length);
5354 ENSURE_ALLOCATION (xsum (length, count));
5356 tmpdst = result + length;
5357 /* Copy backwards, because of overlapping. */
5360 for (n = count; n > 0; n--)
5361 *--tmpdst = (unsigned char) *--tmpsrc;
5366 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5367 /* Make room for the result. */
5368 if (count > allocated - length)
5370 /* Need at least count elements. But allocate
5373 xmax (xsum (length, count), xtimes (allocated, 2));
5375 ENSURE_ALLOCATION (n);
5379 /* Here count <= allocated - length. */
5381 /* Perform padding. */
5382 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5383 if (pad_ourselves && has_width)
5386 # if ENABLE_UNISTDIO
5387 /* Outside POSIX, it's preferrable to compare the width
5388 against the number of _characters_ of the converted
5390 w = DCHAR_MBSNLEN (result + length, count);
5392 /* The width is compared against the number of _bytes_
5393 of the converted value, says POSIX. */
5398 size_t pad = width - w;
5400 /* Make room for the result. */
5401 if (xsum (count, pad) > allocated - length)
5403 /* Need at least count + pad elements. But
5404 allocate proportionally. */
5406 xmax (xsum3 (length, count, pad),
5407 xtimes (allocated, 2));
5411 ENSURE_ALLOCATION (n);
5414 ENSURE_ALLOCATION (n);
5417 /* Here count + pad <= allocated - length. */
5420 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5421 DCHAR_T * const rp = result + length;
5423 DCHAR_T * const rp = tmp;
5425 DCHAR_T *p = rp + count;
5426 DCHAR_T *end = p + pad;
5428 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5429 if (dp->conversion == 'c'
5430 || dp->conversion == 's')
5431 /* No zero-padding for string directives. */
5436 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5437 /* No zero-padding of "inf" and "nan". */
5438 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5439 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5442 /* The generated string now extends from rp to p,
5443 with the zero padding insertion point being at
5446 count = count + pad; /* = end - rp */
5448 if (flags & FLAG_LEFT)
5450 /* Pad with spaces on the right. */
5451 for (; pad > 0; pad--)
5454 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5456 /* Pad with zeroes. */
5461 for (; pad > 0; pad--)
5466 /* Pad with spaces on the left. */
5471 for (; pad > 0; pad--)
5479 /* Here still count <= allocated - length. */
5481 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5482 /* The snprintf() result did fit. */
5484 /* Append the sprintf() result. */
5485 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5492 #if NEED_PRINTF_DIRECTIVE_F
5493 if (dp->conversion == 'F')
5495 /* Convert the %f result to upper case for %F. */
5496 DCHAR_T *rp = result + length;
5498 for (rc = count; rc > 0; rc--, rp++)
5499 if (*rp >= 'a' && *rp <= 'z')
5500 *rp = *rp - 'a' + 'A';
5508 #undef pad_ourselves
5509 #undef prec_ourselves
5514 /* Add the final NUL. */
5515 ENSURE_ALLOCATION (xsum (length, 1));
5516 result[length] = '\0';
5518 if (result != resultbuf && length + 1 < allocated)
5520 /* Shrink the allocated memory if possible. */
5523 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5528 if (buf_malloced != NULL)
5529 free (buf_malloced);
5532 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5533 says that snprintf() fails with errno = EOVERFLOW in this case, but
5534 that's only because snprintf() returns an 'int'. This function does
5535 not have this limitation. */
5540 if (!(result == resultbuf || result == NULL))
5542 if (buf_malloced != NULL)
5543 free (buf_malloced);
5550 if (!(result == resultbuf || result == NULL))
5552 if (buf_malloced != NULL)
5553 free (buf_malloced);
5561 #undef MAX_ROOM_NEEDED
5562 #undef TCHARS_PER_DCHAR
5570 #undef DCHAR_IS_TCHAR