1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2011 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* This file can be parametrized with the following macros:
19 VASNPRINTF The name of the function being defined.
20 FCHAR_T The element type of the format string.
21 DCHAR_T The element type of the destination (result) string.
22 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
23 in the format string are ASCII. MUST be set if
24 FCHAR_T and DCHAR_T are not the same type.
25 DIRECTIVE Structure denoting a format directive.
27 DIRECTIVES Structure denoting the set of format directives of a
28 format string. Depends on FCHAR_T.
29 PRINTF_PARSE Function that parses a format string.
31 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
32 DCHAR_SET memset like function for DCHAR_T[] arrays.
33 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
34 SNPRINTF The system's snprintf (or similar) function.
35 This may be either snprintf or swprintf.
36 TCHAR_T The element type of the argument and result string
37 of the said SNPRINTF function. This may be either
38 char or wchar_t. The code exploits that
39 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
40 alignof (TCHAR_T) <= alignof (DCHAR_T).
41 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
42 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
43 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
44 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
45 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
47 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
48 This must come before <config.h> because <config.h> may include
49 <features.h>, and once <features.h> has been included, it's too late. */
51 # define _GNU_SOURCE 1
63 # if WIDE_CHAR_VERSION
64 # include "vasnwprintf.h"
66 # include "vasnprintf.h"
70 #include <locale.h> /* localeconv() */
71 #include <stdio.h> /* snprintf(), sprintf() */
72 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
73 #include <string.h> /* memcpy(), strlen() */
74 #include <errno.h> /* errno */
75 #include <limits.h> /* CHAR_BIT */
76 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
78 # include <langinfo.h>
81 # if WIDE_CHAR_VERSION
82 # include "wprintf-parse.h"
84 # include "printf-parse.h"
88 /* Checked size_t computations. */
93 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
98 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
100 # include "isnand-nolibm.h"
103 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
105 # include "isnanl-nolibm.h"
109 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
111 # include "isnand-nolibm.h"
112 # include "printf-frexp.h"
115 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
117 # include "isnanl-nolibm.h"
118 # include "printf-frexpl.h"
122 /* Default parameters. */
124 # if WIDE_CHAR_VERSION
125 # define VASNPRINTF vasnwprintf
126 # define FCHAR_T wchar_t
127 # define DCHAR_T wchar_t
128 # define TCHAR_T wchar_t
129 # define DCHAR_IS_TCHAR 1
130 # define DIRECTIVE wchar_t_directive
131 # define DIRECTIVES wchar_t_directives
132 # define PRINTF_PARSE wprintf_parse
133 # define DCHAR_CPY wmemcpy
134 # define DCHAR_SET wmemset
136 # define VASNPRINTF vasnprintf
137 # define FCHAR_T char
138 # define DCHAR_T char
139 # define TCHAR_T char
140 # define DCHAR_IS_TCHAR 1
141 # define DIRECTIVE char_directive
142 # define DIRECTIVES char_directives
143 # define PRINTF_PARSE printf_parse
144 # define DCHAR_CPY memcpy
145 # define DCHAR_SET memset
148 #if WIDE_CHAR_VERSION
149 /* TCHAR_T is wchar_t. */
150 # define USE_SNPRINTF 1
151 # if HAVE_DECL__SNWPRINTF
152 /* On Windows, the function swprintf() has a different signature than
153 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
154 instead. The mingw function snwprintf() has fewer bugs than the
155 MSVCRT function _snwprintf(), so prefer that. */
156 # if defined __MINGW32__
157 # define SNPRINTF snwprintf
159 # define SNPRINTF _snwprintf
163 # define SNPRINTF swprintf
166 /* TCHAR_T is char. */
167 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
168 But don't use it on BeOS, since BeOS snprintf produces no output if the
169 size argument is >= 0x3000000.
170 Also don't use it on Linux libc5, since there snprintf with size = 1
171 writes any output without bounds, like sprintf. */
172 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
173 # define USE_SNPRINTF 1
175 # define USE_SNPRINTF 0
177 # if HAVE_DECL__SNPRINTF
178 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
179 function _snprintf(), so prefer that. */
180 # if defined __MINGW32__
181 # define SNPRINTF snprintf
182 /* Here we need to call the native snprintf, not rpl_snprintf. */
185 # define SNPRINTF _snprintf
189 # define SNPRINTF snprintf
190 /* Here we need to call the native snprintf, not rpl_snprintf. */
194 /* Here we need to call the native sprintf, not rpl_sprintf. */
197 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
198 warnings in this file. Use -Dlint to suppress them. */
200 # define IF_LINT(Code) Code
202 # define IF_LINT(Code) /* empty */
205 /* Avoid some warnings from "gcc -Wshadow".
206 This file doesn't use the exp() and remainder() functions. */
210 #define remainder rem
212 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && !WIDE_CHAR_VERSION
213 # if (HAVE_STRNLEN && !defined _AIX)
214 # define local_strnlen strnlen
216 # ifndef local_strnlen_defined
217 # define local_strnlen_defined 1
219 local_strnlen (const char *string, size_t maxlen)
221 const char *end = memchr (string, '\0', maxlen);
222 return end ? (size_t) (end - string) : maxlen;
228 #if (((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && WIDE_CHAR_VERSION) || ((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && !WIDE_CHAR_VERSION && DCHAR_IS_TCHAR)) && HAVE_WCHAR_T
230 # define local_wcslen wcslen
232 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
233 a dependency towards this library, here is a local substitute.
234 Define this substitute only once, even if this file is included
235 twice in the same compilation unit. */
236 # ifndef local_wcslen_defined
237 # define local_wcslen_defined 1
239 local_wcslen (const wchar_t *s)
243 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
251 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
253 # define local_wcsnlen wcsnlen
255 # ifndef local_wcsnlen_defined
256 # define local_wcsnlen_defined 1
258 local_wcsnlen (const wchar_t *s, size_t maxlen)
262 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
270 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
271 /* Determine the decimal-point character according to the current locale. */
272 # ifndef decimal_point_char_defined
273 # define decimal_point_char_defined 1
275 decimal_point_char (void)
278 /* Determine it in a multithread-safe way. We know nl_langinfo is
279 multithread-safe on glibc systems and MacOS X systems, but is not required
280 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
281 localeconv() is rarely multithread-safe. */
282 # if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
283 point = nl_langinfo (RADIXCHAR);
286 sprintf (pointbuf, "%#.0f", 1.0);
287 point = &pointbuf[1];
289 point = localeconv () -> decimal_point;
291 /* The decimal point is always a single byte: either '.' or ','. */
292 return (point[0] != '\0' ? point[0] : '.');
297 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
299 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
301 is_infinite_or_zero (double x)
303 return isnand (x) || x + x == x;
308 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
310 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
312 is_infinite_or_zerol (long double x)
314 return isnanl (x) || x + x == x;
319 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
321 /* Converting 'long double' to decimal without rare rounding bugs requires
322 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
323 (and slower) algorithms. */
325 typedef unsigned int mp_limb_t;
326 # define GMP_LIMB_BITS 32
327 verify (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS);
329 typedef unsigned long long mp_twolimb_t;
330 # define GMP_TWOLIMB_BITS 64
331 verify (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS);
333 /* Representation of a bignum >= 0. */
337 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
340 /* Compute the product of two bignums >= 0.
341 Return the allocated memory in case of success, NULL in case of memory
342 allocation failure. */
344 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
351 if (src1.nlimbs <= src2.nlimbs)
365 /* Now 0 <= len1 <= len2. */
368 /* src1 or src2 is zero. */
370 dest->limbs = (mp_limb_t *) malloc (1);
374 /* Here 1 <= len1 <= len2. */
380 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
383 for (k = len2; k > 0; )
385 for (i = 0; i < len1; i++)
387 mp_limb_t digit1 = p1[i];
388 mp_twolimb_t carry = 0;
389 for (j = 0; j < len2; j++)
391 mp_limb_t digit2 = p2[j];
392 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
394 dp[i + j] = (mp_limb_t) carry;
395 carry = carry >> GMP_LIMB_BITS;
397 dp[i + len2] = (mp_limb_t) carry;
400 while (dlen > 0 && dp[dlen - 1] == 0)
408 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
409 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
411 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
413 Return the allocated memory in case of success, NULL in case of memory
414 allocation failure. */
416 divide (mpn_t a, mpn_t b, mpn_t *q)
419 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
420 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
421 If m<n, then q:=0 and r:=a.
422 If m>=n=1, perform a single-precision division:
425 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
426 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
427 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
428 Normalise [q[m-1],...,q[0]], yields q.
429 If m>=n>1, perform a multiple-precision division:
430 We have a/b < beta^(m-n+1).
431 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
432 Shift a and b left by s bits, copying them. r:=a.
433 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
434 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
436 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
437 In case of overflow (q* >= beta) set q* := beta-1.
438 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
439 and c3 := b[n-2] * q*.
440 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
441 occurred. Furthermore 0 <= c3 < beta^2.
442 If there was overflow and
443 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
444 the next test can be skipped.}
445 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
446 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
448 Put r := r - b * q* * beta^j. In detail:
449 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
450 hence: u:=0, for i:=0 to n-1 do
452 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
453 u:=u div beta (+ 1, if carry in subtraction)
455 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
457 the carry u does not overflow.}
458 If a negative carry occurs, put q* := q* - 1
459 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
461 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
462 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
464 The room for q[j] can be allocated at the memory location of r[n+j].
465 Finally, round-to-even:
466 Shift r left by 1 bit.
467 If r > b or if r = b and q[0] is odd, q := q+1.
469 const mp_limb_t *a_ptr = a.limbs;
470 size_t a_len = a.nlimbs;
471 const mp_limb_t *b_ptr = b.limbs;
472 size_t b_len = b.nlimbs;
474 mp_limb_t *tmp_roomptr = NULL;
480 /* Allocate room for a_len+2 digits.
481 (Need a_len+1 digits for the real division and 1 more digit for the
482 final rounding of q.) */
483 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
488 while (a_len > 0 && a_ptr[a_len - 1] == 0)
495 /* Division by zero. */
497 if (b_ptr[b_len - 1] == 0)
503 /* Here m = a_len >= 0 and n = b_len > 0. */
507 /* m<n: trivial case. q=0, r := copy of a. */
510 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
511 q_ptr = roomptr + a_len;
516 /* n=1: single precision division.
517 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
521 mp_limb_t den = b_ptr[0];
522 mp_limb_t remainder = 0;
523 const mp_limb_t *sourceptr = a_ptr + a_len;
524 mp_limb_t *destptr = q_ptr + a_len;
526 for (count = a_len; count > 0; count--)
529 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
530 *--destptr = num / den;
531 remainder = num % den;
533 /* Normalise and store r. */
536 r_ptr[0] = remainder;
543 if (q_ptr[q_len - 1] == 0)
549 /* n>1: multiple precision division.
550 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
551 beta^(m-n-1) <= a/b < beta^(m-n+1). */
555 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
583 /* 0 <= s < GMP_LIMB_BITS.
584 Copy b, shifting it left by s bits. */
587 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
588 if (tmp_roomptr == NULL)
594 const mp_limb_t *sourceptr = b_ptr;
595 mp_limb_t *destptr = tmp_roomptr;
596 mp_twolimb_t accu = 0;
598 for (count = b_len; count > 0; count--)
600 accu += (mp_twolimb_t) *sourceptr++ << s;
601 *destptr++ = (mp_limb_t) accu;
602 accu = accu >> GMP_LIMB_BITS;
604 /* accu must be zero, since that was how s was determined. */
610 /* Copy a, shifting it left by s bits, yields r.
612 At the beginning: r = roomptr[0..a_len],
613 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
617 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
622 const mp_limb_t *sourceptr = a_ptr;
623 mp_limb_t *destptr = r_ptr;
624 mp_twolimb_t accu = 0;
626 for (count = a_len; count > 0; count--)
628 accu += (mp_twolimb_t) *sourceptr++ << s;
629 *destptr++ = (mp_limb_t) accu;
630 accu = accu >> GMP_LIMB_BITS;
632 *destptr++ = (mp_limb_t) accu;
634 q_ptr = roomptr + b_len;
635 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
637 size_t j = a_len - b_len; /* m-n */
638 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
639 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
640 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
641 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
642 /* Division loop, traversed m-n+1 times.
643 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
648 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
650 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
652 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
653 | r_ptr[j + b_len - 1];
654 q_star = num / b_msd;
659 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
660 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
661 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
662 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
663 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
665 If yes, jump directly to the subtraction loop.
666 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
667 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
668 if (r_ptr[j + b_len] > b_msd
669 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
670 /* r[j+n] >= b[n-1]+1 or
671 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
676 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
678 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
679 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
680 mp_twolimb_t c3 = /* b[n-2] * q* */
681 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
682 /* While c2 < c3, increase c2 and decrease c3.
683 Consider c3-c2. While it is > 0, decrease it by
684 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
685 this can happen only twice. */
688 q_star = q_star - 1; /* q* := q* - 1 */
689 if (c3 - c2 > b_msdd)
690 q_star = q_star - 1; /* q* := q* - 1 */
696 /* Subtract r := r - b * q* * beta^j. */
699 const mp_limb_t *sourceptr = b_ptr;
700 mp_limb_t *destptr = r_ptr + j;
701 mp_twolimb_t carry = 0;
703 for (count = b_len; count > 0; count--)
705 /* Here 0 <= carry <= q*. */
708 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
709 + (mp_limb_t) ~(*destptr);
710 /* Here 0 <= carry <= beta*q* + beta-1. */
711 *destptr++ = ~(mp_limb_t) carry;
712 carry = carry >> GMP_LIMB_BITS; /* <= q* */
714 cr = (mp_limb_t) carry;
716 /* Subtract cr from r_ptr[j + b_len], then forget about
718 if (cr > r_ptr[j + b_len])
720 /* Subtraction gave a carry. */
721 q_star = q_star - 1; /* q* := q* - 1 */
724 const mp_limb_t *sourceptr = b_ptr;
725 mp_limb_t *destptr = r_ptr + j;
728 for (count = b_len; count > 0; count--)
730 mp_limb_t source1 = *sourceptr++;
731 mp_limb_t source2 = *destptr;
732 *destptr++ = source1 + source2 + carry;
735 ? source1 >= (mp_limb_t) ~source2
736 : source1 > (mp_limb_t) ~source2);
739 /* Forget about the carry and about r[j+n]. */
742 /* q* is determined. Store it as q[j]. */
751 if (q_ptr[q_len - 1] == 0)
753 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
754 b is shifted left by s bits. */
755 /* Shift r right by s bits. */
758 mp_limb_t ptr = r_ptr + r_len;
759 mp_twolimb_t accu = 0;
761 for (count = r_len; count > 0; count--)
763 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
764 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
765 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
770 while (r_len > 0 && r_ptr[r_len - 1] == 0)
773 /* Compare r << 1 with b. */
781 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
782 | (i < r_len ? r_ptr[i] << 1 : 0);
783 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
793 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
798 for (i = 0; i < q_len; i++)
799 if (++(q_ptr[i]) != 0)
804 if (tmp_roomptr != NULL)
811 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
813 Destroys the contents of a.
814 Return the allocated memory - containing the decimal digits in low-to-high
815 order, terminated with a NUL character - in case of success, NULL in case
816 of memory allocation failure. */
818 convert_to_decimal (mpn_t a, size_t extra_zeroes)
820 mp_limb_t *a_ptr = a.limbs;
821 size_t a_len = a.nlimbs;
822 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
823 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
824 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
828 for (; extra_zeroes > 0; extra_zeroes--)
832 /* Divide a by 10^9, in-place. */
833 mp_limb_t remainder = 0;
834 mp_limb_t *ptr = a_ptr + a_len;
836 for (count = a_len; count > 0; count--)
839 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
840 *ptr = num / 1000000000;
841 remainder = num % 1000000000;
843 /* Store the remainder as 9 decimal digits. */
844 for (count = 9; count > 0; count--)
846 *d_ptr++ = '0' + (remainder % 10);
847 remainder = remainder / 10;
850 if (a_ptr[a_len - 1] == 0)
853 /* Remove leading zeroes. */
854 while (d_ptr > c_ptr && d_ptr[-1] == '0')
856 /* But keep at least one zero. */
859 /* Terminate the string. */
865 # if NEED_PRINTF_LONG_DOUBLE
867 /* Assuming x is finite and >= 0:
868 write x as x = 2^e * m, where m is a bignum.
869 Return the allocated memory in case of success, NULL in case of memory
870 allocation failure. */
872 decode_long_double (long double x, int *ep, mpn_t *mp)
879 /* Allocate memory for result. */
880 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
881 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
884 /* Split into exponential part and mantissa. */
885 y = frexpl (x, &exp);
886 if (!(y >= 0.0L && y < 1.0L))
888 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
889 latter is an integer. */
890 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
891 I'm not sure whether it's safe to cast a 'long double' value between
892 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
893 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
895 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
896 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
899 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
902 if (!(y >= 0.0L && y < 1.0L))
904 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
907 if (!(y >= 0.0L && y < 1.0L))
909 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
914 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
917 if (!(y >= 0.0L && y < 1.0L))
919 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
923 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
926 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
929 if (!(y >= 0.0L && y < 1.0L))
931 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
934 if (!(y >= 0.0L && y < 1.0L))
936 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
938 # if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
944 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
947 *ep = exp - LDBL_MANT_BIT;
953 # if NEED_PRINTF_DOUBLE
955 /* Assuming x is finite and >= 0:
956 write x as x = 2^e * m, where m is a bignum.
957 Return the allocated memory in case of success, NULL in case of memory
958 allocation failure. */
960 decode_double (double x, int *ep, mpn_t *mp)
967 /* Allocate memory for result. */
968 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
969 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
972 /* Split into exponential part and mantissa. */
974 if (!(y >= 0.0 && y < 1.0))
976 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
977 latter is an integer. */
978 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
979 I'm not sure whether it's safe to cast a 'double' value between
980 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
981 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
983 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
984 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
987 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
990 if (!(y >= 0.0 && y < 1.0))
992 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
995 if (!(y >= 0.0 && y < 1.0))
997 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1002 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
1005 if (!(y >= 0.0 && y < 1.0))
1007 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
1011 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1014 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1017 if (!(y >= 0.0 && y < 1.0))
1019 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1022 if (!(y >= 0.0 && y < 1.0))
1024 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1029 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1032 *ep = exp - DBL_MANT_BIT;
1038 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1039 Returns the decimal representation of round (x * 10^n).
1040 Return the allocated memory - containing the decimal digits in low-to-high
1041 order, terminated with a NUL character - in case of success, NULL in case
1042 of memory allocation failure. */
1044 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1047 size_t extra_zeroes;
1050 mp_limb_t *pow5_ptr;
1052 unsigned int s_limbs;
1053 unsigned int s_bits;
1061 /* x = 2^e * m, hence
1062 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1063 = round (2^s * 5^n * m). */
1066 /* Factor out a common power of 10 if possible. */
1069 extra_zeroes = (s < n ? s : n);
1073 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1074 Before converting to decimal, we need to compute
1075 z = round (2^s * 5^n * m). */
1076 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1077 sign. 2.322 is slightly larger than log(5)/log(2). */
1078 abs_n = (n >= 0 ? n : -n);
1079 abs_s = (s >= 0 ? s : -s);
1080 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1081 + abs_s / GMP_LIMB_BITS + 1)
1082 * sizeof (mp_limb_t));
1083 if (pow5_ptr == NULL)
1088 /* Initialize with 1. */
1091 /* Multiply with 5^|n|. */
1094 static mp_limb_t const small_pow5[13 + 1] =
1096 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1097 48828125, 244140625, 1220703125
1100 for (n13 = 0; n13 <= abs_n; n13 += 13)
1102 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1104 mp_twolimb_t carry = 0;
1105 for (j = 0; j < pow5_len; j++)
1107 mp_limb_t digit2 = pow5_ptr[j];
1108 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1109 pow5_ptr[j] = (mp_limb_t) carry;
1110 carry = carry >> GMP_LIMB_BITS;
1113 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1116 s_limbs = abs_s / GMP_LIMB_BITS;
1117 s_bits = abs_s % GMP_LIMB_BITS;
1118 if (n >= 0 ? s >= 0 : s <= 0)
1120 /* Multiply with 2^|s|. */
1123 mp_limb_t *ptr = pow5_ptr;
1124 mp_twolimb_t accu = 0;
1126 for (count = pow5_len; count > 0; count--)
1128 accu += (mp_twolimb_t) *ptr << s_bits;
1129 *ptr++ = (mp_limb_t) accu;
1130 accu = accu >> GMP_LIMB_BITS;
1134 *ptr = (mp_limb_t) accu;
1141 for (count = pow5_len; count > 0;)
1144 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1146 for (count = s_limbs; count > 0;)
1149 pow5_ptr[count] = 0;
1151 pow5_len += s_limbs;
1153 pow5.limbs = pow5_ptr;
1154 pow5.nlimbs = pow5_len;
1157 /* Multiply m with pow5. No division needed. */
1158 z_memory = multiply (m, pow5, &z);
1162 /* Divide m by pow5 and round. */
1163 z_memory = divide (m, pow5, &z);
1168 pow5.limbs = pow5_ptr;
1169 pow5.nlimbs = pow5_len;
1173 Multiply m with pow5, then divide by 2^|s|. */
1177 tmp_memory = multiply (m, pow5, &numerator);
1178 if (tmp_memory == NULL)
1184 /* Construct 2^|s|. */
1186 mp_limb_t *ptr = pow5_ptr + pow5_len;
1188 for (i = 0; i < s_limbs; i++)
1190 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1191 denominator.limbs = ptr;
1192 denominator.nlimbs = s_limbs + 1;
1194 z_memory = divide (numerator, denominator, &z);
1200 Multiply m with 2^s, then divide by pow5. */
1203 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1204 * sizeof (mp_limb_t));
1205 if (num_ptr == NULL)
1212 mp_limb_t *destptr = num_ptr;
1215 for (i = 0; i < s_limbs; i++)
1220 const mp_limb_t *sourceptr = m.limbs;
1221 mp_twolimb_t accu = 0;
1223 for (count = m.nlimbs; count > 0; count--)
1225 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1226 *destptr++ = (mp_limb_t) accu;
1227 accu = accu >> GMP_LIMB_BITS;
1230 *destptr++ = (mp_limb_t) accu;
1234 const mp_limb_t *sourceptr = m.limbs;
1236 for (count = m.nlimbs; count > 0; count--)
1237 *destptr++ = *sourceptr++;
1239 numerator.limbs = num_ptr;
1240 numerator.nlimbs = destptr - num_ptr;
1242 z_memory = divide (numerator, pow5, &z);
1249 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1251 if (z_memory == NULL)
1253 digits = convert_to_decimal (z, extra_zeroes);
1258 # if NEED_PRINTF_LONG_DOUBLE
1260 /* Assuming x is finite and >= 0, and n is an integer:
1261 Returns the decimal representation of round (x * 10^n).
1262 Return the allocated memory - containing the decimal digits in low-to-high
1263 order, terminated with a NUL character - in case of success, NULL in case
1264 of memory allocation failure. */
1266 scale10_round_decimal_long_double (long double x, int n)
1270 void *memory = decode_long_double (x, &e, &m);
1271 return scale10_round_decimal_decoded (e, m, memory, n);
1276 # if NEED_PRINTF_DOUBLE
1278 /* Assuming x is finite and >= 0, and n is an integer:
1279 Returns the decimal representation of round (x * 10^n).
1280 Return the allocated memory - containing the decimal digits in low-to-high
1281 order, terminated with a NUL character - in case of success, NULL in case
1282 of memory allocation failure. */
1284 scale10_round_decimal_double (double x, int n)
1288 void *memory = decode_double (x, &e, &m);
1289 return scale10_round_decimal_decoded (e, m, memory, n);
1294 # if NEED_PRINTF_LONG_DOUBLE
1296 /* Assuming x is finite and > 0:
1297 Return an approximation for n with 10^n <= x < 10^(n+1).
1298 The approximation is usually the right n, but may be off by 1 sometimes. */
1300 floorlog10l (long double x)
1307 /* Split into exponential part and mantissa. */
1308 y = frexpl (x, &exp);
1309 if (!(y >= 0.0L && y < 1.0L))
1315 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1317 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1318 exp -= GMP_LIMB_BITS;
1320 if (y < (1.0L / (1 << 16)))
1322 y *= 1.0L * (1 << 16);
1325 if (y < (1.0L / (1 << 8)))
1327 y *= 1.0L * (1 << 8);
1330 if (y < (1.0L / (1 << 4)))
1332 y *= 1.0L * (1 << 4);
1335 if (y < (1.0L / (1 << 2)))
1337 y *= 1.0L * (1 << 2);
1340 if (y < (1.0L / (1 << 1)))
1342 y *= 1.0L * (1 << 1);
1346 if (!(y >= 0.5L && y < 1.0L))
1348 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1351 if (z < 0.70710678118654752444)
1353 z *= 1.4142135623730950488;
1356 if (z < 0.8408964152537145431)
1358 z *= 1.1892071150027210667;
1361 if (z < 0.91700404320467123175)
1363 z *= 1.0905077326652576592;
1366 if (z < 0.9576032806985736469)
1368 z *= 1.0442737824274138403;
1371 /* Now 0.95 <= z <= 1.01. */
1373 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1374 Four terms are enough to get an approximation with error < 10^-7. */
1375 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1376 /* Finally multiply with log(2)/log(10), yields an approximation for
1378 l *= 0.30102999566398119523;
1379 /* Round down to the next integer. */
1380 return (int) l + (l < 0 ? -1 : 0);
1385 # if NEED_PRINTF_DOUBLE
1387 /* Assuming x is finite and > 0:
1388 Return an approximation for n with 10^n <= x < 10^(n+1).
1389 The approximation is usually the right n, but may be off by 1 sometimes. */
1391 floorlog10 (double x)
1398 /* Split into exponential part and mantissa. */
1399 y = frexp (x, &exp);
1400 if (!(y >= 0.0 && y < 1.0))
1406 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1408 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1409 exp -= GMP_LIMB_BITS;
1411 if (y < (1.0 / (1 << 16)))
1413 y *= 1.0 * (1 << 16);
1416 if (y < (1.0 / (1 << 8)))
1418 y *= 1.0 * (1 << 8);
1421 if (y < (1.0 / (1 << 4)))
1423 y *= 1.0 * (1 << 4);
1426 if (y < (1.0 / (1 << 2)))
1428 y *= 1.0 * (1 << 2);
1431 if (y < (1.0 / (1 << 1)))
1433 y *= 1.0 * (1 << 1);
1437 if (!(y >= 0.5 && y < 1.0))
1439 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1442 if (z < 0.70710678118654752444)
1444 z *= 1.4142135623730950488;
1447 if (z < 0.8408964152537145431)
1449 z *= 1.1892071150027210667;
1452 if (z < 0.91700404320467123175)
1454 z *= 1.0905077326652576592;
1457 if (z < 0.9576032806985736469)
1459 z *= 1.0442737824274138403;
1462 /* Now 0.95 <= z <= 1.01. */
1464 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1465 Four terms are enough to get an approximation with error < 10^-7. */
1466 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1467 /* Finally multiply with log(2)/log(10), yields an approximation for
1469 l *= 0.30102999566398119523;
1470 /* Round down to the next integer. */
1471 return (int) l + (l < 0 ? -1 : 0);
1476 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1477 a single '1' digit. */
1479 is_borderline (const char *digits, size_t precision)
1481 for (; precision > 0; precision--, digits++)
1487 return *digits == '\0';
1492 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99
1494 /* Use a different function name, to make it possible that the 'wchar_t'
1495 parametrization and the 'char' parametrization get compiled in the same
1496 translation unit. */
1497 # if WIDE_CHAR_VERSION
1498 # define MAX_ROOM_NEEDED wmax_room_needed
1500 # define MAX_ROOM_NEEDED max_room_needed
1503 /* Returns the number of TCHAR_T units needed as temporary space for the result
1504 of sprintf or SNPRINTF of a single conversion directive. */
1505 static inline size_t
1506 MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
1507 arg_type type, int flags, size_t width, int has_precision,
1508 size_t precision, int pad_ourselves)
1514 case 'd': case 'i': case 'u':
1515 # if HAVE_LONG_LONG_INT
1516 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1518 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1519 * 0.30103 /* binary -> decimal */
1521 + 1; /* turn floor into ceil */
1524 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1526 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1527 * 0.30103 /* binary -> decimal */
1529 + 1; /* turn floor into ceil */
1532 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1533 * 0.30103 /* binary -> decimal */
1535 + 1; /* turn floor into ceil */
1536 if (tmp_length < precision)
1537 tmp_length = precision;
1538 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1539 tmp_length = xsum (tmp_length, tmp_length);
1540 /* Add 1, to account for a leading sign. */
1541 tmp_length = xsum (tmp_length, 1);
1545 # if HAVE_LONG_LONG_INT
1546 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1548 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1549 * 0.333334 /* binary -> octal */
1551 + 1; /* turn floor into ceil */
1554 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1556 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1557 * 0.333334 /* binary -> octal */
1559 + 1; /* turn floor into ceil */
1562 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1563 * 0.333334 /* binary -> octal */
1565 + 1; /* turn floor into ceil */
1566 if (tmp_length < precision)
1567 tmp_length = precision;
1568 /* Add 1, to account for a leading sign. */
1569 tmp_length = xsum (tmp_length, 1);
1573 # if HAVE_LONG_LONG_INT
1574 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1576 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1577 * 0.25 /* binary -> hexadecimal */
1579 + 1; /* turn floor into ceil */
1582 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1584 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1585 * 0.25 /* binary -> hexadecimal */
1587 + 1; /* turn floor into ceil */
1590 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1591 * 0.25 /* binary -> hexadecimal */
1593 + 1; /* turn floor into ceil */
1594 if (tmp_length < precision)
1595 tmp_length = precision;
1596 /* Add 2, to account for a leading sign or alternate form. */
1597 tmp_length = xsum (tmp_length, 2);
1601 if (type == TYPE_LONGDOUBLE)
1603 (unsigned int) (LDBL_MAX_EXP
1604 * 0.30103 /* binary -> decimal */
1605 * 2 /* estimate for FLAG_GROUP */
1607 + 1 /* turn floor into ceil */
1608 + 10; /* sign, decimal point etc. */
1611 (unsigned int) (DBL_MAX_EXP
1612 * 0.30103 /* binary -> decimal */
1613 * 2 /* estimate for FLAG_GROUP */
1615 + 1 /* turn floor into ceil */
1616 + 10; /* sign, decimal point etc. */
1617 tmp_length = xsum (tmp_length, precision);
1620 case 'e': case 'E': case 'g': case 'G':
1622 12; /* sign, decimal point, exponent etc. */
1623 tmp_length = xsum (tmp_length, precision);
1627 if (type == TYPE_LONGDOUBLE)
1629 (unsigned int) (LDBL_DIG
1630 * 0.831 /* decimal -> hexadecimal */
1632 + 1; /* turn floor into ceil */
1635 (unsigned int) (DBL_DIG
1636 * 0.831 /* decimal -> hexadecimal */
1638 + 1; /* turn floor into ceil */
1639 if (tmp_length < precision)
1640 tmp_length = precision;
1641 /* Account for sign, decimal point etc. */
1642 tmp_length = xsum (tmp_length, 12);
1646 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
1647 if (type == TYPE_WIDE_CHAR)
1648 tmp_length = MB_CUR_MAX;
1656 if (type == TYPE_WIDE_STRING)
1658 # if WIDE_CHAR_VERSION
1659 /* ISO C says about %ls in fwprintf:
1660 "If the precision is not specified or is greater than the size
1661 of the array, the array shall contain a null wide character."
1662 So if there is a precision, we must not use wcslen. */
1663 const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
1666 tmp_length = local_wcsnlen (arg, precision);
1668 tmp_length = local_wcslen (arg);
1670 /* ISO C says about %ls in fprintf:
1671 "If a precision is specified, no more than that many bytes are
1672 written (including shift sequences, if any), and the array
1673 shall contain a null wide character if, to equal the multibyte
1674 character sequence length given by the precision, the function
1675 would need to access a wide character one past the end of the
1677 So if there is a precision, we must not use wcslen. */
1678 /* This case has already been handled separately in VASNPRINTF. */
1685 # if WIDE_CHAR_VERSION
1686 /* ISO C says about %s in fwprintf:
1687 "If the precision is not specified or is greater than the size
1688 of the converted array, the converted array shall contain a
1689 null wide character."
1690 So if there is a precision, we must not use strlen. */
1691 /* This case has already been handled separately in VASNPRINTF. */
1694 /* ISO C says about %s in fprintf:
1695 "If the precision is not specified or greater than the size of
1696 the array, the array shall contain a null character."
1697 So if there is a precision, we must not use strlen. */
1698 const char *arg = ap->arg[arg_index].a.a_string;
1701 tmp_length = local_strnlen (arg, precision);
1703 tmp_length = strlen (arg);
1710 (unsigned int) (sizeof (void *) * CHAR_BIT
1711 * 0.25 /* binary -> hexadecimal */
1713 + 1 /* turn floor into ceil */
1714 + 2; /* account for leading 0x */
1723 # if ENABLE_UNISTDIO
1724 /* Padding considers the number of characters, therefore the number of
1725 elements after padding may be
1726 > max (tmp_length, width)
1728 <= tmp_length + width. */
1729 tmp_length = xsum (tmp_length, width);
1731 /* Padding considers the number of elements, says POSIX. */
1732 if (tmp_length < width)
1737 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1745 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1746 const FCHAR_T *format, va_list args)
1751 if (PRINTF_PARSE (format, &d, &a) < 0)
1752 /* errno is already set. */
1756 if (d.dir != d.direct_alloc_dir) \
1758 if (a.arg != a.direct_alloc_arg) \
1761 if (PRINTF_FETCHARGS (args, &a) < 0)
1769 size_t buf_neededlength;
1771 TCHAR_T *buf_malloced;
1775 /* Output string accumulator. */
1780 /* Allocate a small buffer that will hold a directive passed to
1781 sprintf or snprintf. */
1783 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1785 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1787 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1788 buf_malloced = NULL;
1793 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1794 if (size_overflow_p (buf_memsize))
1795 goto out_of_memory_1;
1796 buf = (TCHAR_T *) malloc (buf_memsize);
1798 goto out_of_memory_1;
1802 if (resultbuf != NULL)
1805 allocated = *lengthp;
1814 result is either == resultbuf or == NULL or malloc-allocated.
1815 If length > 0, then result != NULL. */
1817 /* Ensures that allocated >= needed. Aborts through a jump to
1818 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1819 #define ENSURE_ALLOCATION(needed) \
1820 if ((needed) > allocated) \
1822 size_t memory_size; \
1825 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1826 if ((needed) > allocated) \
1827 allocated = (needed); \
1828 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1829 if (size_overflow_p (memory_size)) \
1830 goto out_of_memory; \
1831 if (result == resultbuf || result == NULL) \
1832 memory = (DCHAR_T *) malloc (memory_size); \
1834 memory = (DCHAR_T *) realloc (result, memory_size); \
1835 if (memory == NULL) \
1836 goto out_of_memory; \
1837 if (result == resultbuf && length > 0) \
1838 DCHAR_CPY (memory, result, length); \
1842 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1844 if (cp != dp->dir_start)
1846 size_t n = dp->dir_start - cp;
1847 size_t augmented_length = xsum (length, n);
1849 ENSURE_ALLOCATION (augmented_length);
1850 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1851 need that the format string contains only ASCII characters
1852 if FCHAR_T and DCHAR_T are not the same type. */
1853 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1855 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1856 length = augmented_length;
1861 result[length++] = (unsigned char) *cp++;
1868 /* Execute a single directive. */
1869 if (dp->conversion == '%')
1871 size_t augmented_length;
1873 if (!(dp->arg_index == ARG_NONE))
1875 augmented_length = xsum (length, 1);
1876 ENSURE_ALLOCATION (augmented_length);
1877 result[length] = '%';
1878 length = augmented_length;
1882 if (!(dp->arg_index != ARG_NONE))
1885 if (dp->conversion == 'n')
1887 switch (a.arg[dp->arg_index].type)
1889 case TYPE_COUNT_SCHAR_POINTER:
1890 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1892 case TYPE_COUNT_SHORT_POINTER:
1893 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1895 case TYPE_COUNT_INT_POINTER:
1896 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1898 case TYPE_COUNT_LONGINT_POINTER:
1899 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1901 #if HAVE_LONG_LONG_INT
1902 case TYPE_COUNT_LONGLONGINT_POINTER:
1903 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1911 /* The unistdio extensions. */
1912 else if (dp->conversion == 'U')
1914 arg_type type = a.arg[dp->arg_index].type;
1915 int flags = dp->flags;
1923 if (dp->width_start != dp->width_end)
1925 if (dp->width_arg_index != ARG_NONE)
1929 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1931 arg = a.arg[dp->width_arg_index].a.a_int;
1934 /* "A negative field width is taken as a '-' flag
1935 followed by a positive field width." */
1937 width = (unsigned int) (-arg);
1944 const FCHAR_T *digitp = dp->width_start;
1947 width = xsum (xtimes (width, 10), *digitp++ - '0');
1948 while (digitp != dp->width_end);
1955 if (dp->precision_start != dp->precision_end)
1957 if (dp->precision_arg_index != ARG_NONE)
1961 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1963 arg = a.arg[dp->precision_arg_index].a.a_int;
1964 /* "A negative precision is taken as if the precision
1974 const FCHAR_T *digitp = dp->precision_start + 1;
1977 while (digitp != dp->precision_end)
1978 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1985 case TYPE_U8_STRING:
1987 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1988 const uint8_t *arg_end;
1993 /* Use only PRECISION characters, from the left. */
1996 for (; precision > 0; precision--)
1998 int count = u8_strmblen (arg_end);
2003 if (!(result == resultbuf || result == NULL))
2005 if (buf_malloced != NULL)
2006 free (buf_malloced);
2017 /* Use the entire string, and count the number of
2023 int count = u8_strmblen (arg_end);
2028 if (!(result == resultbuf || result == NULL))
2030 if (buf_malloced != NULL)
2031 free (buf_malloced);
2042 /* Use the entire string. */
2043 arg_end = arg + u8_strlen (arg);
2044 /* The number of characters doesn't matter. */
2048 if (has_width && width > characters
2049 && !(dp->flags & FLAG_LEFT))
2051 size_t n = width - characters;
2052 ENSURE_ALLOCATION (xsum (length, n));
2053 DCHAR_SET (result + length, ' ', n);
2057 # if DCHAR_IS_UINT8_T
2059 size_t n = arg_end - arg;
2060 ENSURE_ALLOCATION (xsum (length, n));
2061 DCHAR_CPY (result + length, arg, n);
2066 DCHAR_T *converted = result + length;
2067 size_t converted_len = allocated - length;
2069 /* Convert from UTF-8 to locale encoding. */
2071 u8_conv_to_encoding (locale_charset (),
2072 iconveh_question_mark,
2073 arg, arg_end - arg, NULL,
2074 converted, &converted_len);
2076 /* Convert from UTF-8 to UTF-16/UTF-32. */
2078 U8_TO_DCHAR (arg, arg_end - arg,
2079 converted, &converted_len);
2081 if (converted == NULL)
2083 int saved_errno = errno;
2084 if (!(result == resultbuf || result == NULL))
2086 if (buf_malloced != NULL)
2087 free (buf_malloced);
2089 errno = saved_errno;
2092 if (converted != result + length)
2094 ENSURE_ALLOCATION (xsum (length, converted_len));
2095 DCHAR_CPY (result + length, converted, converted_len);
2098 length += converted_len;
2102 if (has_width && width > characters
2103 && (dp->flags & FLAG_LEFT))
2105 size_t n = width - characters;
2106 ENSURE_ALLOCATION (xsum (length, n));
2107 DCHAR_SET (result + length, ' ', n);
2113 case TYPE_U16_STRING:
2115 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
2116 const uint16_t *arg_end;
2121 /* Use only PRECISION characters, from the left. */
2124 for (; precision > 0; precision--)
2126 int count = u16_strmblen (arg_end);
2131 if (!(result == resultbuf || result == NULL))
2133 if (buf_malloced != NULL)
2134 free (buf_malloced);
2145 /* Use the entire string, and count the number of
2151 int count = u16_strmblen (arg_end);
2156 if (!(result == resultbuf || result == NULL))
2158 if (buf_malloced != NULL)
2159 free (buf_malloced);
2170 /* Use the entire string. */
2171 arg_end = arg + u16_strlen (arg);
2172 /* The number of characters doesn't matter. */
2176 if (has_width && width > characters
2177 && !(dp->flags & FLAG_LEFT))
2179 size_t n = width - characters;
2180 ENSURE_ALLOCATION (xsum (length, n));
2181 DCHAR_SET (result + length, ' ', n);
2185 # if DCHAR_IS_UINT16_T
2187 size_t n = arg_end - arg;
2188 ENSURE_ALLOCATION (xsum (length, n));
2189 DCHAR_CPY (result + length, arg, n);
2194 DCHAR_T *converted = result + length;
2195 size_t converted_len = allocated - length;
2197 /* Convert from UTF-16 to locale encoding. */
2199 u16_conv_to_encoding (locale_charset (),
2200 iconveh_question_mark,
2201 arg, arg_end - arg, NULL,
2202 converted, &converted_len);
2204 /* Convert from UTF-16 to UTF-8/UTF-32. */
2206 U16_TO_DCHAR (arg, arg_end - arg,
2207 converted, &converted_len);
2209 if (converted == NULL)
2211 int saved_errno = errno;
2212 if (!(result == resultbuf || result == NULL))
2214 if (buf_malloced != NULL)
2215 free (buf_malloced);
2217 errno = saved_errno;
2220 if (converted != result + length)
2222 ENSURE_ALLOCATION (xsum (length, converted_len));
2223 DCHAR_CPY (result + length, converted, converted_len);
2226 length += converted_len;
2230 if (has_width && width > characters
2231 && (dp->flags & FLAG_LEFT))
2233 size_t n = width - characters;
2234 ENSURE_ALLOCATION (xsum (length, n));
2235 DCHAR_SET (result + length, ' ', n);
2241 case TYPE_U32_STRING:
2243 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
2244 const uint32_t *arg_end;
2249 /* Use only PRECISION characters, from the left. */
2252 for (; precision > 0; precision--)
2254 int count = u32_strmblen (arg_end);
2259 if (!(result == resultbuf || result == NULL))
2261 if (buf_malloced != NULL)
2262 free (buf_malloced);
2273 /* Use the entire string, and count the number of
2279 int count = u32_strmblen (arg_end);
2284 if (!(result == resultbuf || result == NULL))
2286 if (buf_malloced != NULL)
2287 free (buf_malloced);
2298 /* Use the entire string. */
2299 arg_end = arg + u32_strlen (arg);
2300 /* The number of characters doesn't matter. */
2304 if (has_width && width > characters
2305 && !(dp->flags & FLAG_LEFT))
2307 size_t n = width - characters;
2308 ENSURE_ALLOCATION (xsum (length, n));
2309 DCHAR_SET (result + length, ' ', n);
2313 # if DCHAR_IS_UINT32_T
2315 size_t n = arg_end - arg;
2316 ENSURE_ALLOCATION (xsum (length, n));
2317 DCHAR_CPY (result + length, arg, n);
2322 DCHAR_T *converted = result + length;
2323 size_t converted_len = allocated - length;
2325 /* Convert from UTF-32 to locale encoding. */
2327 u32_conv_to_encoding (locale_charset (),
2328 iconveh_question_mark,
2329 arg, arg_end - arg, NULL,
2330 converted, &converted_len);
2332 /* Convert from UTF-32 to UTF-8/UTF-16. */
2334 U32_TO_DCHAR (arg, arg_end - arg,
2335 converted, &converted_len);
2337 if (converted == NULL)
2339 int saved_errno = errno;
2340 if (!(result == resultbuf || result == NULL))
2342 if (buf_malloced != NULL)
2343 free (buf_malloced);
2345 errno = saved_errno;
2348 if (converted != result + length)
2350 ENSURE_ALLOCATION (xsum (length, converted_len));
2351 DCHAR_CPY (result + length, converted, converted_len);
2354 length += converted_len;
2358 if (has_width && width > characters
2359 && (dp->flags & FLAG_LEFT))
2361 size_t n = width - characters;
2362 ENSURE_ALLOCATION (xsum (length, n));
2363 DCHAR_SET (result + length, ' ', n);
2374 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T
2375 else if (dp->conversion == 's'
2376 # if WIDE_CHAR_VERSION
2377 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2379 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2383 /* The normal handling of the 's' directive below requires
2384 allocating a temporary buffer. The determination of its
2385 length (tmp_length), in the case when a precision is
2386 specified, below requires a conversion between a char[]
2387 string and a wchar_t[] wide string. It could be done, but
2388 we have no guarantee that the implementation of sprintf will
2389 use the exactly same algorithm. Without this guarantee, it
2390 is possible to have buffer overrun bugs. In order to avoid
2391 such bugs, we implement the entire processing of the 's'
2392 directive ourselves. */
2393 int flags = dp->flags;
2401 if (dp->width_start != dp->width_end)
2403 if (dp->width_arg_index != ARG_NONE)
2407 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2409 arg = a.arg[dp->width_arg_index].a.a_int;
2412 /* "A negative field width is taken as a '-' flag
2413 followed by a positive field width." */
2415 width = (unsigned int) (-arg);
2422 const FCHAR_T *digitp = dp->width_start;
2425 width = xsum (xtimes (width, 10), *digitp++ - '0');
2426 while (digitp != dp->width_end);
2433 if (dp->precision_start != dp->precision_end)
2435 if (dp->precision_arg_index != ARG_NONE)
2439 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2441 arg = a.arg[dp->precision_arg_index].a.a_int;
2442 /* "A negative precision is taken as if the precision
2452 const FCHAR_T *digitp = dp->precision_start + 1;
2455 while (digitp != dp->precision_end)
2456 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2461 # if WIDE_CHAR_VERSION
2462 /* %s in vasnwprintf. See the specification of fwprintf. */
2464 const char *arg = a.arg[dp->arg_index].a.a_string;
2465 const char *arg_end;
2470 /* Use only as many bytes as needed to produce PRECISION
2471 wide characters, from the left. */
2474 memset (&state, '\0', sizeof (mbstate_t));
2478 for (; precision > 0; precision--)
2482 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2484 count = mblen (arg_end, MB_CUR_MAX);
2487 /* Found the terminating NUL. */
2491 /* Invalid or incomplete multibyte character. */
2492 if (!(result == resultbuf || result == NULL))
2494 if (buf_malloced != NULL)
2495 free (buf_malloced);
2506 /* Use the entire string, and count the number of wide
2510 memset (&state, '\0', sizeof (mbstate_t));
2518 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2520 count = mblen (arg_end, MB_CUR_MAX);
2523 /* Found the terminating NUL. */
2527 /* Invalid or incomplete multibyte character. */
2528 if (!(result == resultbuf || result == NULL))
2530 if (buf_malloced != NULL)
2531 free (buf_malloced);
2542 /* Use the entire string. */
2543 arg_end = arg + strlen (arg);
2544 /* The number of characters doesn't matter. */
2548 if (has_width && width > characters
2549 && !(dp->flags & FLAG_LEFT))
2551 size_t n = width - characters;
2552 ENSURE_ALLOCATION (xsum (length, n));
2553 DCHAR_SET (result + length, ' ', n);
2557 if (has_precision || has_width)
2559 /* We know the number of wide characters in advance. */
2563 memset (&state, '\0', sizeof (mbstate_t));
2565 ENSURE_ALLOCATION (xsum (length, characters));
2566 for (remaining = characters; remaining > 0; remaining--)
2571 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2573 count = mbtowc (&wc, arg, arg_end - arg);
2576 /* mbrtowc not consistent with mbrlen, or mbtowc
2577 not consistent with mblen. */
2579 result[length++] = wc;
2582 if (!(arg == arg_end))
2589 memset (&state, '\0', sizeof (mbstate_t));
2591 while (arg < arg_end)
2596 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2598 count = mbtowc (&wc, arg, arg_end - arg);
2601 /* mbrtowc not consistent with mbrlen, or mbtowc
2602 not consistent with mblen. */
2604 ENSURE_ALLOCATION (xsum (length, 1));
2605 result[length++] = wc;
2610 if (has_width && width > characters
2611 && (dp->flags & FLAG_LEFT))
2613 size_t n = width - characters;
2614 ENSURE_ALLOCATION (xsum (length, n));
2615 DCHAR_SET (result + length, ' ', n);
2620 /* %ls in vasnprintf. See the specification of fprintf. */
2622 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2623 const wchar_t *arg_end;
2625 # if !DCHAR_IS_TCHAR
2626 /* This code assumes that TCHAR_T is 'char'. */
2627 verify (sizeof (TCHAR_T) == 1);
2636 /* Use only as many wide characters as needed to produce
2637 at most PRECISION bytes, from the left. */
2638 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2640 memset (&state, '\0', sizeof (mbstate_t));
2644 while (precision > 0)
2646 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2650 /* Found the terminating null wide character. */
2652 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2653 count = wcrtomb (cbuf, *arg_end, &state);
2655 count = wctomb (cbuf, *arg_end);
2659 /* Cannot convert. */
2660 if (!(result == resultbuf || result == NULL))
2662 if (buf_malloced != NULL)
2663 free (buf_malloced);
2668 if (precision < count)
2671 characters += count;
2681 /* Use the entire string, and count the number of
2683 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2685 memset (&state, '\0', sizeof (mbstate_t));
2691 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2695 /* Found the terminating null wide character. */
2697 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2698 count = wcrtomb (cbuf, *arg_end, &state);
2700 count = wctomb (cbuf, *arg_end);
2704 /* Cannot convert. */
2705 if (!(result == resultbuf || result == NULL))
2707 if (buf_malloced != NULL)
2708 free (buf_malloced);
2714 characters += count;
2720 /* Use the entire string. */
2721 arg_end = arg + local_wcslen (arg);
2722 /* The number of bytes doesn't matter. */
2727 # if !DCHAR_IS_TCHAR
2728 /* Convert the string into a piece of temporary memory. */
2729 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2733 TCHAR_T *tmpptr = tmpsrc;
2735 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2737 memset (&state, '\0', sizeof (mbstate_t));
2739 for (remaining = characters; remaining > 0; )
2741 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2746 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2747 count = wcrtomb (cbuf, *arg, &state);
2749 count = wctomb (cbuf, *arg);
2752 /* Inconsistency. */
2754 memcpy (tmpptr, cbuf, count);
2759 if (!(arg == arg_end))
2763 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2765 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2766 iconveh_question_mark,
2772 int saved_errno = errno;
2774 if (!(result == resultbuf || result == NULL))
2776 if (buf_malloced != NULL)
2777 free (buf_malloced);
2779 errno = saved_errno;
2787 # if ENABLE_UNISTDIO
2788 /* Outside POSIX, it's preferrable to compare the width
2789 against the number of _characters_ of the converted
2791 w = DCHAR_MBSNLEN (result + length, characters);
2793 /* The width is compared against the number of _bytes_
2794 of the converted value, says POSIX. */
2799 /* w doesn't matter. */
2802 if (has_width && width > w
2803 && !(dp->flags & FLAG_LEFT))
2805 size_t n = width - w;
2806 ENSURE_ALLOCATION (xsum (length, n));
2807 DCHAR_SET (result + length, ' ', n);
2812 if (has_precision || has_width)
2814 /* We know the number of bytes in advance. */
2816 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2818 memset (&state, '\0', sizeof (mbstate_t));
2820 ENSURE_ALLOCATION (xsum (length, characters));
2821 for (remaining = characters; remaining > 0; )
2823 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2828 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2829 count = wcrtomb (cbuf, *arg, &state);
2831 count = wctomb (cbuf, *arg);
2834 /* Inconsistency. */
2836 memcpy (result + length, cbuf, count);
2841 if (!(arg == arg_end))
2846 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2848 memset (&state, '\0', sizeof (mbstate_t));
2850 while (arg < arg_end)
2852 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2857 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2858 count = wcrtomb (cbuf, *arg, &state);
2860 count = wctomb (cbuf, *arg);
2864 /* Cannot convert. */
2865 if (!(result == resultbuf || result == NULL))
2867 if (buf_malloced != NULL)
2868 free (buf_malloced);
2873 ENSURE_ALLOCATION (xsum (length, count));
2874 memcpy (result + length, cbuf, count);
2880 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2881 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2883 length += tmpdst_len;
2886 if (has_width && width > w
2887 && (dp->flags & FLAG_LEFT))
2889 size_t n = width - w;
2890 ENSURE_ALLOCATION (xsum (length, n));
2891 DCHAR_SET (result + length, ' ', n);
2898 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2899 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2900 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2902 # if NEED_PRINTF_DOUBLE
2903 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2905 # if NEED_PRINTF_LONG_DOUBLE
2906 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2912 arg_type type = a.arg[dp->arg_index].type;
2913 int flags = dp->flags;
2919 DCHAR_T tmpbuf[700];
2926 if (dp->width_start != dp->width_end)
2928 if (dp->width_arg_index != ARG_NONE)
2932 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2934 arg = a.arg[dp->width_arg_index].a.a_int;
2937 /* "A negative field width is taken as a '-' flag
2938 followed by a positive field width." */
2940 width = (unsigned int) (-arg);
2947 const FCHAR_T *digitp = dp->width_start;
2950 width = xsum (xtimes (width, 10), *digitp++ - '0');
2951 while (digitp != dp->width_end);
2958 if (dp->precision_start != dp->precision_end)
2960 if (dp->precision_arg_index != ARG_NONE)
2964 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2966 arg = a.arg[dp->precision_arg_index].a.a_int;
2967 /* "A negative precision is taken as if the precision
2977 const FCHAR_T *digitp = dp->precision_start + 1;
2980 while (digitp != dp->precision_end)
2981 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2986 /* Allocate a temporary buffer of sufficient size. */
2987 if (type == TYPE_LONGDOUBLE)
2989 (unsigned int) ((LDBL_DIG + 1)
2990 * 0.831 /* decimal -> hexadecimal */
2992 + 1; /* turn floor into ceil */
2995 (unsigned int) ((DBL_DIG + 1)
2996 * 0.831 /* decimal -> hexadecimal */
2998 + 1; /* turn floor into ceil */
2999 if (tmp_length < precision)
3000 tmp_length = precision;
3001 /* Account for sign, decimal point etc. */
3002 tmp_length = xsum (tmp_length, 12);
3004 if (tmp_length < width)
3007 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3009 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3013 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3015 if (size_overflow_p (tmp_memsize))
3016 /* Overflow, would lead to out of memory. */
3018 tmp = (DCHAR_T *) malloc (tmp_memsize);
3020 /* Out of memory. */
3026 if (type == TYPE_LONGDOUBLE)
3028 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
3029 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3033 if (dp->conversion == 'A')
3035 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3039 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3045 DECL_LONG_DOUBLE_ROUNDING
3047 BEGIN_LONG_DOUBLE_ROUNDING ();
3049 if (signbit (arg)) /* arg < 0.0L or negative zero */
3057 else if (flags & FLAG_SHOWSIGN)
3059 else if (flags & FLAG_SPACE)
3062 if (arg > 0.0L && arg + arg == arg)
3064 if (dp->conversion == 'A')
3066 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3070 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3076 long double mantissa;
3079 mantissa = printf_frexpl (arg, &exponent);
3087 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
3089 /* Round the mantissa. */
3090 long double tail = mantissa;
3093 for (q = precision; ; q--)
3095 int digit = (int) tail;
3099 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
3108 for (q = precision; q > 0; q--)
3114 *p++ = dp->conversion - 'A' + 'X';
3119 digit = (int) mantissa;
3122 if ((flags & FLAG_ALT)
3123 || mantissa > 0.0L || precision > 0)
3125 *p++ = decimal_point_char ();
3126 /* This loop terminates because we assume
3127 that FLT_RADIX is a power of 2. */
3128 while (mantissa > 0.0L)
3131 digit = (int) mantissa;
3136 : dp->conversion - 10);
3140 while (precision > 0)
3147 *p++ = dp->conversion - 'A' + 'P';
3148 # if WIDE_CHAR_VERSION
3150 static const wchar_t decimal_format[] =
3151 { '%', '+', 'd', '\0' };
3152 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3157 if (sizeof (DCHAR_T) == 1)
3159 sprintf ((char *) p, "%+d", exponent);
3167 sprintf (expbuf, "%+d", exponent);
3168 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3174 END_LONG_DOUBLE_ROUNDING ();
3182 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
3183 double arg = a.arg[dp->arg_index].a.a_double;
3187 if (dp->conversion == 'A')
3189 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3193 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3200 if (signbit (arg)) /* arg < 0.0 or negative zero */
3208 else if (flags & FLAG_SHOWSIGN)
3210 else if (flags & FLAG_SPACE)
3213 if (arg > 0.0 && arg + arg == arg)
3215 if (dp->conversion == 'A')
3217 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3221 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3230 mantissa = printf_frexp (arg, &exponent);
3238 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
3240 /* Round the mantissa. */
3241 double tail = mantissa;
3244 for (q = precision; ; q--)
3246 int digit = (int) tail;
3250 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
3259 for (q = precision; q > 0; q--)
3265 *p++ = dp->conversion - 'A' + 'X';
3270 digit = (int) mantissa;
3273 if ((flags & FLAG_ALT)
3274 || mantissa > 0.0 || precision > 0)
3276 *p++ = decimal_point_char ();
3277 /* This loop terminates because we assume
3278 that FLT_RADIX is a power of 2. */
3279 while (mantissa > 0.0)
3282 digit = (int) mantissa;
3287 : dp->conversion - 10);
3291 while (precision > 0)
3298 *p++ = dp->conversion - 'A' + 'P';
3299 # if WIDE_CHAR_VERSION
3301 static const wchar_t decimal_format[] =
3302 { '%', '+', 'd', '\0' };
3303 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3308 if (sizeof (DCHAR_T) == 1)
3310 sprintf ((char *) p, "%+d", exponent);
3318 sprintf (expbuf, "%+d", exponent);
3319 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3329 /* The generated string now extends from tmp to p, with the
3330 zero padding insertion point being at pad_ptr. */
3331 if (has_width && p - tmp < width)
3333 size_t pad = width - (p - tmp);
3334 DCHAR_T *end = p + pad;
3336 if (flags & FLAG_LEFT)
3338 /* Pad with spaces on the right. */
3339 for (; pad > 0; pad--)
3342 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3344 /* Pad with zeroes. */
3349 for (; pad > 0; pad--)
3354 /* Pad with spaces on the left. */
3359 for (; pad > 0; pad--)
3367 size_t count = p - tmp;
3369 if (count >= tmp_length)
3370 /* tmp_length was incorrectly calculated - fix the
3374 /* Make room for the result. */
3375 if (count >= allocated - length)
3377 size_t n = xsum (length, count);
3379 ENSURE_ALLOCATION (n);
3382 /* Append the result. */
3383 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3390 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3391 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3392 || dp->conversion == 'e' || dp->conversion == 'E'
3393 || dp->conversion == 'g' || dp->conversion == 'G'
3394 || dp->conversion == 'a' || dp->conversion == 'A')
3396 # if NEED_PRINTF_DOUBLE
3397 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3398 # elif NEED_PRINTF_INFINITE_DOUBLE
3399 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3400 /* The systems (mingw) which produce wrong output
3401 for Inf, -Inf, and NaN also do so for -0.0.
3402 Therefore we treat this case here as well. */
3403 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3405 # if NEED_PRINTF_LONG_DOUBLE
3406 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3407 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3408 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3409 /* Some systems produce wrong output for Inf,
3410 -Inf, and NaN. Some systems in this category
3411 (IRIX 5.3) also do so for -0.0. Therefore we
3412 treat this case here as well. */
3413 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3417 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3418 arg_type type = a.arg[dp->arg_index].type;
3420 int flags = dp->flags;
3426 DCHAR_T tmpbuf[700];
3433 if (dp->width_start != dp->width_end)
3435 if (dp->width_arg_index != ARG_NONE)
3439 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3441 arg = a.arg[dp->width_arg_index].a.a_int;
3444 /* "A negative field width is taken as a '-' flag
3445 followed by a positive field width." */
3447 width = (unsigned int) (-arg);
3454 const FCHAR_T *digitp = dp->width_start;
3457 width = xsum (xtimes (width, 10), *digitp++ - '0');
3458 while (digitp != dp->width_end);
3465 if (dp->precision_start != dp->precision_end)
3467 if (dp->precision_arg_index != ARG_NONE)
3471 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3473 arg = a.arg[dp->precision_arg_index].a.a_int;
3474 /* "A negative precision is taken as if the precision
3484 const FCHAR_T *digitp = dp->precision_start + 1;
3487 while (digitp != dp->precision_end)
3488 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3493 /* POSIX specifies the default precision to be 6 for %f, %F,
3494 %e, %E, but not for %g, %G. Implementations appear to use
3495 the same default precision also for %g, %G. But for %a, %A,
3496 the default precision is 0. */
3498 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3501 /* Allocate a temporary buffer of sufficient size. */
3502 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3503 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3504 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3505 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3506 # elif NEED_PRINTF_LONG_DOUBLE
3507 tmp_length = LDBL_DIG + 1;
3508 # elif NEED_PRINTF_DOUBLE
3509 tmp_length = DBL_DIG + 1;
3513 if (tmp_length < precision)
3514 tmp_length = precision;
3515 # if NEED_PRINTF_LONG_DOUBLE
3516 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3517 if (type == TYPE_LONGDOUBLE)
3519 if (dp->conversion == 'f' || dp->conversion == 'F')
3521 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3522 if (!(isnanl (arg) || arg + arg == arg))
3524 /* arg is finite and nonzero. */
3525 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3526 if (exponent >= 0 && tmp_length < exponent + precision)
3527 tmp_length = exponent + precision;
3531 # if NEED_PRINTF_DOUBLE
3532 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3533 if (type == TYPE_DOUBLE)
3535 if (dp->conversion == 'f' || dp->conversion == 'F')
3537 double arg = a.arg[dp->arg_index].a.a_double;
3538 if (!(isnand (arg) || arg + arg == arg))
3540 /* arg is finite and nonzero. */
3541 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3542 if (exponent >= 0 && tmp_length < exponent + precision)
3543 tmp_length = exponent + precision;
3547 /* Account for sign, decimal point etc. */
3548 tmp_length = xsum (tmp_length, 12);
3550 if (tmp_length < width)
3553 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3555 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3559 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3561 if (size_overflow_p (tmp_memsize))
3562 /* Overflow, would lead to out of memory. */
3564 tmp = (DCHAR_T *) malloc (tmp_memsize);
3566 /* Out of memory. */
3573 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3574 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3575 if (type == TYPE_LONGDOUBLE)
3578 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3582 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3584 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3588 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3594 DECL_LONG_DOUBLE_ROUNDING
3596 BEGIN_LONG_DOUBLE_ROUNDING ();
3598 if (signbit (arg)) /* arg < 0.0L or negative zero */
3606 else if (flags & FLAG_SHOWSIGN)
3608 else if (flags & FLAG_SPACE)
3611 if (arg > 0.0L && arg + arg == arg)
3613 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3615 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3619 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3624 # if NEED_PRINTF_LONG_DOUBLE
3627 if (dp->conversion == 'f' || dp->conversion == 'F')
3633 scale10_round_decimal_long_double (arg, precision);
3636 END_LONG_DOUBLE_ROUNDING ();
3639 ndigits = strlen (digits);
3641 if (ndigits > precision)
3645 *p++ = digits[ndigits];
3647 while (ndigits > precision);
3650 /* Here ndigits <= precision. */
3651 if ((flags & FLAG_ALT) || precision > 0)
3653 *p++ = decimal_point_char ();
3654 for (; precision > ndigits; precision--)
3659 *p++ = digits[ndigits];
3665 else if (dp->conversion == 'e' || dp->conversion == 'E')
3673 if ((flags & FLAG_ALT) || precision > 0)
3675 *p++ = decimal_point_char ();
3676 for (; precision > 0; precision--)
3687 exponent = floorlog10l (arg);
3692 scale10_round_decimal_long_double (arg,
3693 (int)precision - exponent);
3696 END_LONG_DOUBLE_ROUNDING ();
3699 ndigits = strlen (digits);
3701 if (ndigits == precision + 1)
3703 if (ndigits < precision
3704 || ndigits > precision + 2)
3705 /* The exponent was not guessed
3706 precisely enough. */
3709 /* None of two values of exponent is
3710 the right one. Prevent an endless
3714 if (ndigits == precision)
3720 /* Here ndigits = precision+1. */
3721 if (is_borderline (digits, precision))
3723 /* Maybe the exponent guess was too high
3724 and a smaller exponent can be reached
3725 by turning a 10...0 into 9...9x. */
3727 scale10_round_decimal_long_double (arg,
3728 (int)precision - exponent + 1);
3729 if (digits2 == NULL)
3732 END_LONG_DOUBLE_ROUNDING ();
3735 if (strlen (digits2) == precision + 1)
3744 /* Here ndigits = precision+1. */
3746 *p++ = digits[--ndigits];
3747 if ((flags & FLAG_ALT) || precision > 0)
3749 *p++ = decimal_point_char ();
3753 *p++ = digits[ndigits];
3760 *p++ = dp->conversion; /* 'e' or 'E' */
3761 # if WIDE_CHAR_VERSION
3763 static const wchar_t decimal_format[] =
3764 { '%', '+', '.', '2', 'd', '\0' };
3765 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3770 if (sizeof (DCHAR_T) == 1)
3772 sprintf ((char *) p, "%+.2d", exponent);
3780 sprintf (expbuf, "%+.2d", exponent);
3781 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3786 else if (dp->conversion == 'g' || dp->conversion == 'G')
3790 /* precision >= 1. */
3793 /* The exponent is 0, >= -4, < precision.
3794 Use fixed-point notation. */
3796 size_t ndigits = precision;
3797 /* Number of trailing zeroes that have to be
3800 (flags & FLAG_ALT ? 0 : precision - 1);
3804 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3806 *p++ = decimal_point_char ();
3807 while (ndigits > nzeroes)
3823 exponent = floorlog10l (arg);
3828 scale10_round_decimal_long_double (arg,
3829 (int)(precision - 1) - exponent);
3832 END_LONG_DOUBLE_ROUNDING ();
3835 ndigits = strlen (digits);
3837 if (ndigits == precision)
3839 if (ndigits < precision - 1
3840 || ndigits > precision + 1)
3841 /* The exponent was not guessed
3842 precisely enough. */
3845 /* None of two values of exponent is
3846 the right one. Prevent an endless
3850 if (ndigits < precision)
3856 /* Here ndigits = precision. */
3857 if (is_borderline (digits, precision - 1))
3859 /* Maybe the exponent guess was too high
3860 and a smaller exponent can be reached
3861 by turning a 10...0 into 9...9x. */
3863 scale10_round_decimal_long_double (arg,
3864 (int)(precision - 1) - exponent + 1);
3865 if (digits2 == NULL)
3868 END_LONG_DOUBLE_ROUNDING ();
3871 if (strlen (digits2) == precision)
3880 /* Here ndigits = precision. */
3882 /* Determine the number of trailing zeroes
3883 that have to be dropped. */
3885 if ((flags & FLAG_ALT) == 0)
3886 while (nzeroes < ndigits
3887 && digits[nzeroes] == '0')
3890 /* The exponent is now determined. */
3892 && exponent < (long)precision)
3894 /* Fixed-point notation:
3895 max(exponent,0)+1 digits, then the
3896 decimal point, then the remaining
3897 digits without trailing zeroes. */
3900 size_t count = exponent + 1;
3901 /* Note: count <= precision = ndigits. */
3902 for (; count > 0; count--)
3903 *p++ = digits[--ndigits];
3904 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3906 *p++ = decimal_point_char ();
3907 while (ndigits > nzeroes)
3910 *p++ = digits[ndigits];
3916 size_t count = -exponent - 1;
3918 *p++ = decimal_point_char ();
3919 for (; count > 0; count--)
3921 while (ndigits > nzeroes)
3924 *p++ = digits[ndigits];
3930 /* Exponential notation. */
3931 *p++ = digits[--ndigits];
3932 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3934 *p++ = decimal_point_char ();
3935 while (ndigits > nzeroes)
3938 *p++ = digits[ndigits];
3941 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3942 # if WIDE_CHAR_VERSION
3944 static const wchar_t decimal_format[] =
3945 { '%', '+', '.', '2', 'd', '\0' };
3946 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3951 if (sizeof (DCHAR_T) == 1)
3953 sprintf ((char *) p, "%+.2d", exponent);
3961 sprintf (expbuf, "%+.2d", exponent);
3962 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3974 /* arg is finite. */
3980 if (dp->conversion == 'f' || dp->conversion == 'F')
3983 if ((flags & FLAG_ALT) || precision > 0)
3985 *p++ = decimal_point_char ();
3986 for (; precision > 0; precision--)
3990 else if (dp->conversion == 'e' || dp->conversion == 'E')
3993 if ((flags & FLAG_ALT) || precision > 0)
3995 *p++ = decimal_point_char ();
3996 for (; precision > 0; precision--)
3999 *p++ = dp->conversion; /* 'e' or 'E' */
4004 else if (dp->conversion == 'g' || dp->conversion == 'G')
4007 if (flags & FLAG_ALT)
4010 (precision > 0 ? precision - 1 : 0);
4011 *p++ = decimal_point_char ();
4012 for (; ndigits > 0; --ndigits)
4016 else if (dp->conversion == 'a' || dp->conversion == 'A')
4019 *p++ = dp->conversion - 'A' + 'X';
4022 if ((flags & FLAG_ALT) || precision > 0)
4024 *p++ = decimal_point_char ();
4025 for (; precision > 0; precision--)
4028 *p++ = dp->conversion - 'A' + 'P';
4037 END_LONG_DOUBLE_ROUNDING ();
4040 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4044 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4046 double arg = a.arg[dp->arg_index].a.a_double;
4050 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4052 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4056 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4063 if (signbit (arg)) /* arg < 0.0 or negative zero */
4071 else if (flags & FLAG_SHOWSIGN)
4073 else if (flags & FLAG_SPACE)
4076 if (arg > 0.0 && arg + arg == arg)
4078 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4080 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4084 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4089 # if NEED_PRINTF_DOUBLE
4092 if (dp->conversion == 'f' || dp->conversion == 'F')
4098 scale10_round_decimal_double (arg, precision);
4101 ndigits = strlen (digits);
4103 if (ndigits > precision)
4107 *p++ = digits[ndigits];
4109 while (ndigits > precision);
4112 /* Here ndigits <= precision. */
4113 if ((flags & FLAG_ALT) || precision > 0)
4115 *p++ = decimal_point_char ();
4116 for (; precision > ndigits; precision--)
4121 *p++ = digits[ndigits];
4127 else if (dp->conversion == 'e' || dp->conversion == 'E')
4135 if ((flags & FLAG_ALT) || precision > 0)
4137 *p++ = decimal_point_char ();
4138 for (; precision > 0; precision--)
4149 exponent = floorlog10 (arg);
4154 scale10_round_decimal_double (arg,
4155 (int)precision - exponent);
4158 ndigits = strlen (digits);
4160 if (ndigits == precision + 1)
4162 if (ndigits < precision
4163 || ndigits > precision + 2)
4164 /* The exponent was not guessed
4165 precisely enough. */
4168 /* None of two values of exponent is
4169 the right one. Prevent an endless
4173 if (ndigits == precision)
4179 /* Here ndigits = precision+1. */
4180 if (is_borderline (digits, precision))
4182 /* Maybe the exponent guess was too high
4183 and a smaller exponent can be reached
4184 by turning a 10...0 into 9...9x. */
4186 scale10_round_decimal_double (arg,
4187 (int)precision - exponent + 1);
4188 if (digits2 == NULL)
4193 if (strlen (digits2) == precision + 1)
4202 /* Here ndigits = precision+1. */
4204 *p++ = digits[--ndigits];
4205 if ((flags & FLAG_ALT) || precision > 0)
4207 *p++ = decimal_point_char ();
4211 *p++ = digits[ndigits];
4218 *p++ = dp->conversion; /* 'e' or 'E' */
4219 # if WIDE_CHAR_VERSION
4221 static const wchar_t decimal_format[] =
4222 /* Produce the same number of exponent digits
4223 as the native printf implementation. */
4224 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4225 { '%', '+', '.', '3', 'd', '\0' };
4227 { '%', '+', '.', '2', 'd', '\0' };
4229 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4235 static const char decimal_format[] =
4236 /* Produce the same number of exponent digits
4237 as the native printf implementation. */
4238 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4243 if (sizeof (DCHAR_T) == 1)
4245 sprintf ((char *) p, decimal_format, exponent);
4253 sprintf (expbuf, decimal_format, exponent);
4254 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4260 else if (dp->conversion == 'g' || dp->conversion == 'G')
4264 /* precision >= 1. */
4267 /* The exponent is 0, >= -4, < precision.
4268 Use fixed-point notation. */
4270 size_t ndigits = precision;
4271 /* Number of trailing zeroes that have to be
4274 (flags & FLAG_ALT ? 0 : precision - 1);
4278 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4280 *p++ = decimal_point_char ();
4281 while (ndigits > nzeroes)
4297 exponent = floorlog10 (arg);
4302 scale10_round_decimal_double (arg,
4303 (int)(precision - 1) - exponent);
4306 ndigits = strlen (digits);
4308 if (ndigits == precision)
4310 if (ndigits < precision - 1
4311 || ndigits > precision + 1)
4312 /* The exponent was not guessed
4313 precisely enough. */
4316 /* None of two values of exponent is
4317 the right one. Prevent an endless
4321 if (ndigits < precision)
4327 /* Here ndigits = precision. */
4328 if (is_borderline (digits, precision - 1))
4330 /* Maybe the exponent guess was too high
4331 and a smaller exponent can be reached
4332 by turning a 10...0 into 9...9x. */
4334 scale10_round_decimal_double (arg,
4335 (int)(precision - 1) - exponent + 1);
4336 if (digits2 == NULL)
4341 if (strlen (digits2) == precision)
4350 /* Here ndigits = precision. */
4352 /* Determine the number of trailing zeroes
4353 that have to be dropped. */
4355 if ((flags & FLAG_ALT) == 0)
4356 while (nzeroes < ndigits
4357 && digits[nzeroes] == '0')
4360 /* The exponent is now determined. */
4362 && exponent < (long)precision)
4364 /* Fixed-point notation:
4365 max(exponent,0)+1 digits, then the
4366 decimal point, then the remaining
4367 digits without trailing zeroes. */
4370 size_t count = exponent + 1;
4371 /* Note: count <= precision = ndigits. */
4372 for (; count > 0; count--)
4373 *p++ = digits[--ndigits];
4374 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4376 *p++ = decimal_point_char ();
4377 while (ndigits > nzeroes)
4380 *p++ = digits[ndigits];
4386 size_t count = -exponent - 1;
4388 *p++ = decimal_point_char ();
4389 for (; count > 0; count--)
4391 while (ndigits > nzeroes)
4394 *p++ = digits[ndigits];
4400 /* Exponential notation. */
4401 *p++ = digits[--ndigits];
4402 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4404 *p++ = decimal_point_char ();
4405 while (ndigits > nzeroes)
4408 *p++ = digits[ndigits];
4411 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4412 # if WIDE_CHAR_VERSION
4414 static const wchar_t decimal_format[] =
4415 /* Produce the same number of exponent digits
4416 as the native printf implementation. */
4417 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4418 { '%', '+', '.', '3', 'd', '\0' };
4420 { '%', '+', '.', '2', 'd', '\0' };
4422 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4428 static const char decimal_format[] =
4429 /* Produce the same number of exponent digits
4430 as the native printf implementation. */
4431 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4436 if (sizeof (DCHAR_T) == 1)
4438 sprintf ((char *) p, decimal_format, exponent);
4446 sprintf (expbuf, decimal_format, exponent);
4447 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4460 /* arg is finite. */
4466 if (dp->conversion == 'f' || dp->conversion == 'F')
4469 if ((flags & FLAG_ALT) || precision > 0)
4471 *p++ = decimal_point_char ();
4472 for (; precision > 0; precision--)
4476 else if (dp->conversion == 'e' || dp->conversion == 'E')
4479 if ((flags & FLAG_ALT) || precision > 0)
4481 *p++ = decimal_point_char ();
4482 for (; precision > 0; precision--)
4485 *p++ = dp->conversion; /* 'e' or 'E' */
4487 /* Produce the same number of exponent digits as
4488 the native printf implementation. */
4489 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4495 else if (dp->conversion == 'g' || dp->conversion == 'G')
4498 if (flags & FLAG_ALT)
4501 (precision > 0 ? precision - 1 : 0);
4502 *p++ = decimal_point_char ();
4503 for (; ndigits > 0; --ndigits)
4515 /* The generated string now extends from tmp to p, with the
4516 zero padding insertion point being at pad_ptr. */
4517 if (has_width && p - tmp < width)
4519 size_t pad = width - (p - tmp);
4520 DCHAR_T *end = p + pad;
4522 if (flags & FLAG_LEFT)
4524 /* Pad with spaces on the right. */
4525 for (; pad > 0; pad--)
4528 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4530 /* Pad with zeroes. */
4535 for (; pad > 0; pad--)
4540 /* Pad with spaces on the left. */
4545 for (; pad > 0; pad--)
4553 size_t count = p - tmp;
4555 if (count >= tmp_length)
4556 /* tmp_length was incorrectly calculated - fix the
4560 /* Make room for the result. */
4561 if (count >= allocated - length)
4563 size_t n = xsum (length, count);
4565 ENSURE_ALLOCATION (n);
4568 /* Append the result. */
4569 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4578 arg_type type = a.arg[dp->arg_index].type;
4579 int flags = dp->flags;
4580 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4584 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4588 #if NEED_PRINTF_UNBOUNDED_PRECISION
4591 # define prec_ourselves 0
4593 #if NEED_PRINTF_FLAG_LEFTADJUST
4594 # define pad_ourselves 1
4595 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4598 # define pad_ourselves 0
4601 unsigned int prefix_count;
4602 int prefixes[2] IF_LINT (= { 0 });
4606 TCHAR_T tmpbuf[700];
4610 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4613 if (dp->width_start != dp->width_end)
4615 if (dp->width_arg_index != ARG_NONE)
4619 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4621 arg = a.arg[dp->width_arg_index].a.a_int;
4624 /* "A negative field width is taken as a '-' flag
4625 followed by a positive field width." */
4627 width = (unsigned int) (-arg);
4634 const FCHAR_T *digitp = dp->width_start;
4637 width = xsum (xtimes (width, 10), *digitp++ - '0');
4638 while (digitp != dp->width_end);
4644 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4647 if (dp->precision_start != dp->precision_end)
4649 if (dp->precision_arg_index != ARG_NONE)
4653 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4655 arg = a.arg[dp->precision_arg_index].a.a_int;
4656 /* "A negative precision is taken as if the precision
4666 const FCHAR_T *digitp = dp->precision_start + 1;
4669 while (digitp != dp->precision_end)
4670 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4676 /* Decide whether to handle the precision ourselves. */
4677 #if NEED_PRINTF_UNBOUNDED_PRECISION
4678 switch (dp->conversion)
4680 case 'd': case 'i': case 'u':
4682 case 'x': case 'X': case 'p':
4683 prec_ourselves = has_precision && (precision > 0);
4691 /* Decide whether to perform the padding ourselves. */
4692 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4693 switch (dp->conversion)
4695 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4696 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4697 to perform the padding after this conversion. Functions
4698 with unistdio extensions perform the padding based on
4699 character count rather than element count. */
4702 # if NEED_PRINTF_FLAG_ZERO
4703 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4709 pad_ourselves = prec_ourselves;
4715 /* Allocate a temporary buffer of sufficient size for calling
4718 MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
4719 flags, width, has_precision, precision,
4722 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4726 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4728 if (size_overflow_p (tmp_memsize))
4729 /* Overflow, would lead to out of memory. */
4731 tmp = (TCHAR_T *) malloc (tmp_memsize);
4733 /* Out of memory. */
4738 /* Construct the format string for calling snprintf or
4742 #if NEED_PRINTF_FLAG_GROUPING
4743 /* The underlying implementation doesn't support the ' flag.
4744 Produce no grouping characters in this case; this is
4745 acceptable because the grouping is locale dependent. */
4747 if (flags & FLAG_GROUP)
4750 if (flags & FLAG_LEFT)
4752 if (flags & FLAG_SHOWSIGN)
4754 if (flags & FLAG_SPACE)
4756 if (flags & FLAG_ALT)
4758 #if __GLIBC__ >= 2 && !defined __UCLIBC__
4759 if (flags & FLAG_LOCALIZED)
4764 if (flags & FLAG_ZERO)
4766 if (dp->width_start != dp->width_end)
4768 size_t n = dp->width_end - dp->width_start;
4769 /* The width specification is known to consist only
4770 of standard ASCII characters. */
4771 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4773 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4778 const FCHAR_T *mp = dp->width_start;
4780 *fbp++ = (unsigned char) *mp++;
4785 if (!prec_ourselves)
4787 if (dp->precision_start != dp->precision_end)
4789 size_t n = dp->precision_end - dp->precision_start;
4790 /* The precision specification is known to consist only
4791 of standard ASCII characters. */
4792 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4794 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4799 const FCHAR_T *mp = dp->precision_start;
4801 *fbp++ = (unsigned char) *mp++;
4809 #if HAVE_LONG_LONG_INT
4810 case TYPE_LONGLONGINT:
4811 case TYPE_ULONGLONGINT:
4812 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4825 case TYPE_WIDE_CHAR:
4828 case TYPE_WIDE_STRING:
4832 case TYPE_LONGDOUBLE:
4838 #if NEED_PRINTF_DIRECTIVE_F
4839 if (dp->conversion == 'F')
4843 *fbp = dp->conversion;
4845 # if !(((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) && !defined __UCLIBC__) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4850 /* On glibc2 systems from glibc >= 2.3 - probably also older
4851 ones - we know that snprintf's return value conforms to
4852 ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and
4853 gl_SNPRINTF_TRUNCATION_C99 pass.
4854 Therefore we can avoid using %n in this situation.
4855 On glibc2 systems from 2004-10-18 or newer, the use of %n
4856 in format strings in writable memory may crash the program
4857 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4858 in this situation. */
4859 /* On native Win32 systems (such as mingw), we can avoid using
4861 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4862 snprintf does not write more than the specified number
4863 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4864 '4', '5', '6' into buf, not '4', '5', '\0'.)
4865 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4866 allows us to recognize the case of an insufficient
4867 buffer size: it returns -1 in this case.
4868 On native Win32 systems (such as mingw) where the OS is
4869 Windows Vista, the use of %n in format strings by default
4870 crashes the program. See
4871 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4872 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4873 So we should avoid %n in this situation. */
4880 /* Construct the arguments for calling snprintf or sprintf. */
4882 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4884 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4886 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4888 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4890 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4892 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4896 /* The SNPRINTF result is appended after result[0..length].
4897 The latter is an array of DCHAR_T; SNPRINTF appends an
4898 array of TCHAR_T to it. This is possible because
4899 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4900 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4901 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4902 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4903 where an snprintf() with maxlen==1 acts like sprintf(). */
4904 ENSURE_ALLOCATION (xsum (length,
4905 (2 + TCHARS_PER_DCHAR - 1)
4906 / TCHARS_PER_DCHAR));
4907 /* Prepare checking whether snprintf returns the count
4909 *(TCHAR_T *) (result + length) = '\0';
4920 size_t maxlen = allocated - length;
4921 /* SNPRINTF can fail if its second argument is
4923 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4924 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4925 maxlen = maxlen * TCHARS_PER_DCHAR;
4926 # define SNPRINTF_BUF(arg) \
4927 switch (prefix_count) \
4930 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4935 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4937 prefixes[0], arg, &count); \
4940 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4942 prefixes[0], prefixes[1], arg, \
4949 # define SNPRINTF_BUF(arg) \
4950 switch (prefix_count) \
4953 count = sprintf (tmp, buf, arg); \
4956 count = sprintf (tmp, buf, prefixes[0], arg); \
4959 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4972 int arg = a.arg[dp->arg_index].a.a_schar;
4978 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4984 int arg = a.arg[dp->arg_index].a.a_short;
4990 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4996 int arg = a.arg[dp->arg_index].a.a_int;
5002 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
5008 long int arg = a.arg[dp->arg_index].a.a_longint;
5014 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
5018 #if HAVE_LONG_LONG_INT
5019 case TYPE_LONGLONGINT:
5021 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
5025 case TYPE_ULONGLONGINT:
5027 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
5034 double arg = a.arg[dp->arg_index].a.a_double;
5038 case TYPE_LONGDOUBLE:
5040 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5046 int arg = a.arg[dp->arg_index].a.a_char;
5051 case TYPE_WIDE_CHAR:
5053 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5060 const char *arg = a.arg[dp->arg_index].a.a_string;
5065 case TYPE_WIDE_STRING:
5067 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5074 void *arg = a.arg[dp->arg_index].a.a_pointer;
5083 /* Portability: Not all implementations of snprintf()
5084 are ISO C 99 compliant. Determine the number of
5085 bytes that snprintf() has produced or would have
5089 /* Verify that snprintf() has NUL-terminated its
5092 && ((TCHAR_T *) (result + length)) [count] != '\0')
5094 /* Portability hack. */
5095 if (retcount > count)
5100 /* snprintf() doesn't understand the '%n'
5104 /* Don't use the '%n' directive; instead, look
5105 at the snprintf() return value. */
5111 /* Look at the snprintf() return value. */
5114 # if !HAVE_SNPRINTF_RETVAL_C99
5115 /* HP-UX 10.20 snprintf() is doubly deficient:
5116 It doesn't understand the '%n' directive,
5117 *and* it returns -1 (rather than the length
5118 that would have been required) when the
5119 buffer is too small.
5120 But a failure at this point can also come
5121 from other reasons than a too small buffer,
5122 such as an invalid wide string argument to
5123 the %ls directive, or possibly an invalid
5124 floating-point argument. */
5126 MAX_ROOM_NEEDED (&a, dp->arg_index,
5127 dp->conversion, type, flags,
5128 width, has_precision,
5129 precision, pad_ourselves);
5131 if (maxlen < tmp_length)
5133 /* Make more room. But try to do through
5134 this reallocation only once. */
5135 size_t bigger_need =
5138 TCHARS_PER_DCHAR - 1)
5139 / TCHARS_PER_DCHAR);
5140 /* And always grow proportionally.
5141 (There may be several arguments, each
5142 needing a little more room than the
5144 size_t bigger_need2 =
5145 xsum (xtimes (allocated, 2), 12);
5146 if (bigger_need < bigger_need2)
5147 bigger_need = bigger_need2;
5148 ENSURE_ALLOCATION (bigger_need);
5159 /* Attempt to handle failure. */
5162 /* SNPRINTF or sprintf failed. Save and use the errno
5163 that it has set, if any. */
5164 int saved_errno = errno;
5166 if (!(result == resultbuf || result == NULL))
5168 if (buf_malloced != NULL)
5169 free (buf_malloced);
5174 : (dp->conversion == 'c' || dp->conversion == 's'
5181 /* Handle overflow of the allocated buffer.
5182 If such an overflow occurs, a C99 compliant snprintf()
5183 returns a count >= maxlen. However, a non-compliant
5184 snprintf() function returns only count = maxlen - 1. To
5185 cover both cases, test whether count >= maxlen - 1. */
5186 if ((unsigned int) count + 1 >= maxlen)
5188 /* If maxlen already has attained its allowed maximum,
5189 allocating more memory will not increase maxlen.
5190 Instead of looping, bail out. */
5191 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5195 /* Need at least (count + 1) * sizeof (TCHAR_T)
5196 bytes. (The +1 is for the trailing NUL.)
5197 But ask for (count + 2) * sizeof (TCHAR_T)
5198 bytes, so that in the next round, we likely get
5199 maxlen > (unsigned int) count + 1
5200 and so we don't get here again.
5201 And allocate proportionally, to avoid looping
5202 eternally if snprintf() reports a too small
5206 ((unsigned int) count + 2
5207 + TCHARS_PER_DCHAR - 1)
5208 / TCHARS_PER_DCHAR),
5209 xtimes (allocated, 2));
5211 ENSURE_ALLOCATION (n);
5217 #if NEED_PRINTF_UNBOUNDED_PRECISION
5220 /* Handle the precision. */
5223 (TCHAR_T *) (result + length);
5227 size_t prefix_count;
5231 /* Put the additional zeroes after the sign. */
5233 && (*prec_ptr == '-' || *prec_ptr == '+'
5234 || *prec_ptr == ' '))
5236 /* Put the additional zeroes after the 0x prefix if
5237 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5239 && prec_ptr[0] == '0'
5240 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5243 move = count - prefix_count;
5244 if (precision > move)
5246 /* Insert zeroes. */
5247 size_t insert = precision - move;
5253 (count + insert + TCHARS_PER_DCHAR - 1)
5254 / TCHARS_PER_DCHAR);
5255 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5256 ENSURE_ALLOCATION (n);
5257 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5258 prec_ptr = (TCHAR_T *) (result + length);
5261 prec_end = prec_ptr + count;
5262 prec_ptr += prefix_count;
5264 while (prec_end > prec_ptr)
5267 prec_end[insert] = prec_end[0];
5273 while (prec_end > prec_ptr);
5281 if (count >= tmp_length)
5282 /* tmp_length was incorrectly calculated - fix the
5288 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5289 if (dp->conversion == 'c' || dp->conversion == 's')
5291 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5293 The result string is not certainly ASCII. */
5294 const TCHAR_T *tmpsrc;
5297 /* This code assumes that TCHAR_T is 'char'. */
5298 verify (sizeof (TCHAR_T) == 1);
5300 tmpsrc = (TCHAR_T *) (result + length);
5305 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5306 iconveh_question_mark,
5312 int saved_errno = errno;
5313 if (!(result == resultbuf || result == NULL))
5315 if (buf_malloced != NULL)
5316 free (buf_malloced);
5318 errno = saved_errno;
5321 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5322 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5328 /* The result string is ASCII.
5329 Simple 1:1 conversion. */
5331 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5332 no-op conversion, in-place on the array starting
5333 at (result + length). */
5334 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5337 const TCHAR_T *tmpsrc;
5342 if (result == resultbuf)
5344 tmpsrc = (TCHAR_T *) (result + length);
5345 /* ENSURE_ALLOCATION will not move tmpsrc
5346 (because it's part of resultbuf). */
5347 ENSURE_ALLOCATION (xsum (length, count));
5351 /* ENSURE_ALLOCATION will move the array
5352 (because it uses realloc(). */
5353 ENSURE_ALLOCATION (xsum (length, count));
5354 tmpsrc = (TCHAR_T *) (result + length);
5358 ENSURE_ALLOCATION (xsum (length, count));
5360 tmpdst = result + length;
5361 /* Copy backwards, because of overlapping. */
5364 for (n = count; n > 0; n--)
5365 *--tmpdst = (unsigned char) *--tmpsrc;
5370 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5371 /* Make room for the result. */
5372 if (count > allocated - length)
5374 /* Need at least count elements. But allocate
5377 xmax (xsum (length, count), xtimes (allocated, 2));
5379 ENSURE_ALLOCATION (n);
5383 /* Here count <= allocated - length. */
5385 /* Perform padding. */
5386 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5387 if (pad_ourselves && has_width)
5390 # if ENABLE_UNISTDIO
5391 /* Outside POSIX, it's preferrable to compare the width
5392 against the number of _characters_ of the converted
5394 w = DCHAR_MBSNLEN (result + length, count);
5396 /* The width is compared against the number of _bytes_
5397 of the converted value, says POSIX. */
5402 size_t pad = width - w;
5404 /* Make room for the result. */
5405 if (xsum (count, pad) > allocated - length)
5407 /* Need at least count + pad elements. But
5408 allocate proportionally. */
5410 xmax (xsum3 (length, count, pad),
5411 xtimes (allocated, 2));
5415 ENSURE_ALLOCATION (n);
5418 ENSURE_ALLOCATION (n);
5421 /* Here count + pad <= allocated - length. */
5424 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5425 DCHAR_T * const rp = result + length;
5427 DCHAR_T * const rp = tmp;
5429 DCHAR_T *p = rp + count;
5430 DCHAR_T *end = p + pad;
5432 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5433 if (dp->conversion == 'c'
5434 || dp->conversion == 's')
5435 /* No zero-padding for string directives. */
5440 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5441 /* No zero-padding of "inf" and "nan". */
5442 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5443 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5446 /* The generated string now extends from rp to p,
5447 with the zero padding insertion point being at
5450 count = count + pad; /* = end - rp */
5452 if (flags & FLAG_LEFT)
5454 /* Pad with spaces on the right. */
5455 for (; pad > 0; pad--)
5458 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5460 /* Pad with zeroes. */
5465 for (; pad > 0; pad--)
5470 /* Pad with spaces on the left. */
5475 for (; pad > 0; pad--)
5483 /* Here still count <= allocated - length. */
5485 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5486 /* The snprintf() result did fit. */
5488 /* Append the sprintf() result. */
5489 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5496 #if NEED_PRINTF_DIRECTIVE_F
5497 if (dp->conversion == 'F')
5499 /* Convert the %f result to upper case for %F. */
5500 DCHAR_T *rp = result + length;
5502 for (rc = count; rc > 0; rc--, rp++)
5503 if (*rp >= 'a' && *rp <= 'z')
5504 *rp = *rp - 'a' + 'A';
5512 #undef pad_ourselves
5513 #undef prec_ourselves
5518 /* Add the final NUL. */
5519 ENSURE_ALLOCATION (xsum (length, 1));
5520 result[length] = '\0';
5522 if (result != resultbuf && length + 1 < allocated)
5524 /* Shrink the allocated memory if possible. */
5527 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5532 if (buf_malloced != NULL)
5533 free (buf_malloced);
5536 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5537 says that snprintf() fails with errno = EOVERFLOW in this case, but
5538 that's only because snprintf() returns an 'int'. This function does
5539 not have this limitation. */
5544 if (!(result == resultbuf || result == NULL))
5546 if (buf_malloced != NULL)
5547 free (buf_malloced);
5554 if (!(result == resultbuf || result == NULL))
5556 if (buf_malloced != NULL)
5557 free (buf_malloced);
5565 #undef MAX_ROOM_NEEDED
5566 #undef TCHARS_PER_DCHAR
5574 #undef DCHAR_IS_TCHAR