1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2016 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, see <http://www.gnu.org/licenses/>. */
17 /* This file can be parametrized with the following macros:
18 VASNPRINTF The name of the function being defined.
19 FCHAR_T The element type of the format string.
20 DCHAR_T The element type of the destination (result) string.
21 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
22 in the format string are ASCII. MUST be set if
23 FCHAR_T and DCHAR_T are not the same type.
24 DIRECTIVE Structure denoting a format directive.
26 DIRECTIVES Structure denoting the set of format directives of a
27 format string. Depends on FCHAR_T.
28 PRINTF_PARSE Function that parses a format string.
30 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
31 DCHAR_SET memset like function for DCHAR_T[] arrays.
32 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
33 SNPRINTF The system's snprintf (or similar) function.
34 This may be either snprintf or swprintf.
35 TCHAR_T The element type of the argument and result string
36 of the said SNPRINTF function. This may be either
37 char or wchar_t. The code exploits that
38 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
39 alignof (TCHAR_T) <= alignof (DCHAR_T).
40 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
41 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
42 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
43 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
44 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
46 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
47 This must come before <config.h> because <config.h> may include
48 <features.h>, and once <features.h> has been included, it's too late. */
50 # define _GNU_SOURCE 1
62 # if WIDE_CHAR_VERSION
63 # include "vasnwprintf.h"
65 # include "vasnprintf.h"
69 #include <locale.h> /* localeconv() */
70 #include <stdio.h> /* snprintf(), sprintf() */
71 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
72 #include <string.h> /* memcpy(), strlen() */
73 #include <errno.h> /* errno */
74 #include <limits.h> /* CHAR_BIT */
75 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
77 # include <langinfo.h>
80 # if WIDE_CHAR_VERSION
81 # include "wprintf-parse.h"
83 # include "printf-parse.h"
87 /* Checked size_t computations. */
92 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
97 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
99 # include "isnand-nolibm.h"
102 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
104 # include "isnanl-nolibm.h"
108 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
110 # include "isnand-nolibm.h"
111 # include "printf-frexp.h"
114 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
116 # include "isnanl-nolibm.h"
117 # include "printf-frexpl.h"
121 /* Default parameters. */
123 # if WIDE_CHAR_VERSION
124 # define VASNPRINTF vasnwprintf
125 # define FCHAR_T wchar_t
126 # define DCHAR_T wchar_t
127 # define TCHAR_T wchar_t
128 # define DCHAR_IS_TCHAR 1
129 # define DIRECTIVE wchar_t_directive
130 # define DIRECTIVES wchar_t_directives
131 # define PRINTF_PARSE wprintf_parse
132 # define DCHAR_CPY wmemcpy
133 # define DCHAR_SET wmemset
135 # define VASNPRINTF vasnprintf
136 # define FCHAR_T char
137 # define DCHAR_T char
138 # define TCHAR_T char
139 # define DCHAR_IS_TCHAR 1
140 # define DIRECTIVE char_directive
141 # define DIRECTIVES char_directives
142 # define PRINTF_PARSE printf_parse
143 # define DCHAR_CPY memcpy
144 # define DCHAR_SET memset
147 #if WIDE_CHAR_VERSION
148 /* TCHAR_T is wchar_t. */
149 # define USE_SNPRINTF 1
150 # if HAVE_DECL__SNWPRINTF
151 /* On Windows, the function swprintf() has a different signature than
152 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
153 instead. The mingw function snwprintf() has fewer bugs than the
154 MSVCRT function _snwprintf(), so prefer that. */
155 # if defined __MINGW32__
156 # define SNPRINTF snwprintf
158 # define SNPRINTF _snwprintf
162 # define SNPRINTF swprintf
165 /* TCHAR_T is char. */
166 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
167 But don't use it on BeOS, since BeOS snprintf produces no output if the
168 size argument is >= 0x3000000.
169 Also don't use it on Linux libc5, since there snprintf with size = 1
170 writes any output without bounds, like sprintf. */
171 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
172 # define USE_SNPRINTF 1
174 # define USE_SNPRINTF 0
176 # if HAVE_DECL__SNPRINTF
177 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
178 function _snprintf(), so prefer that. */
179 # if defined __MINGW32__
180 # define SNPRINTF snprintf
181 /* Here we need to call the native snprintf, not rpl_snprintf. */
184 # define SNPRINTF _snprintf
188 # define SNPRINTF snprintf
189 /* Here we need to call the native snprintf, not rpl_snprintf. */
193 /* Here we need to call the native sprintf, not rpl_sprintf. */
196 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
197 warnings in this file. Use -Dlint to suppress them. */
198 #if defined GCC_LINT || defined lint
199 # define IF_LINT(Code) Code
201 # define IF_LINT(Code) /* empty */
204 /* Avoid some warnings from "gcc -Wshadow".
205 This file doesn't use the exp() and remainder() functions. */
209 #define remainder rem
211 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && !WIDE_CHAR_VERSION
212 # if (HAVE_STRNLEN && !defined _AIX)
213 # define local_strnlen strnlen
215 # ifndef local_strnlen_defined
216 # define local_strnlen_defined 1
218 local_strnlen (const char *string, size_t maxlen)
220 const char *end = memchr (string, '\0', maxlen);
221 return end ? (size_t) (end - string) : maxlen;
227 #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
229 # define local_wcslen wcslen
231 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
232 a dependency towards this library, here is a local substitute.
233 Define this substitute only once, even if this file is included
234 twice in the same compilation unit. */
235 # ifndef local_wcslen_defined
236 # define local_wcslen_defined 1
238 local_wcslen (const wchar_t *s)
242 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
250 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
252 # define local_wcsnlen wcsnlen
254 # ifndef local_wcsnlen_defined
255 # define local_wcsnlen_defined 1
257 local_wcsnlen (const wchar_t *s, size_t maxlen)
261 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
269 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
270 /* Determine the decimal-point character according to the current locale. */
271 # ifndef decimal_point_char_defined
272 # define decimal_point_char_defined 1
274 decimal_point_char (void)
277 /* Determine it in a multithread-safe way. We know nl_langinfo is
278 multithread-safe on glibc systems and Mac OS X systems, but is not required
279 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
280 localeconv() is rarely multithread-safe. */
281 # if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
282 point = nl_langinfo (RADIXCHAR);
285 sprintf (pointbuf, "%#.0f", 1.0);
286 point = &pointbuf[1];
288 point = localeconv () -> decimal_point;
290 /* The decimal point is always a single byte: either '.' or ','. */
291 return (point[0] != '\0' ? point[0] : '.');
296 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
298 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
300 is_infinite_or_zero (double x)
302 return isnand (x) || x + x == x;
307 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
309 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
311 is_infinite_or_zerol (long double x)
313 return isnanl (x) || x + x == x;
318 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
320 /* Converting 'long double' to decimal without rare rounding bugs requires
321 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
322 (and slower) algorithms. */
324 typedef unsigned int mp_limb_t;
325 # define GMP_LIMB_BITS 32
326 verify (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS);
328 typedef unsigned long long mp_twolimb_t;
329 # define GMP_TWOLIMB_BITS 64
330 verify (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS);
332 /* Representation of a bignum >= 0. */
336 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
339 /* Compute the product of two bignums >= 0.
340 Return the allocated memory in case of success, NULL in case of memory
341 allocation failure. */
343 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
350 if (src1.nlimbs <= src2.nlimbs)
364 /* Now 0 <= len1 <= len2. */
367 /* src1 or src2 is zero. */
369 dest->limbs = (mp_limb_t *) malloc (1);
373 /* Here 1 <= len1 <= len2. */
379 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
382 for (k = len2; k > 0; )
384 for (i = 0; i < len1; i++)
386 mp_limb_t digit1 = p1[i];
387 mp_twolimb_t carry = 0;
388 for (j = 0; j < len2; j++)
390 mp_limb_t digit2 = p2[j];
391 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
393 dp[i + j] = (mp_limb_t) carry;
394 carry = carry >> GMP_LIMB_BITS;
396 dp[i + len2] = (mp_limb_t) carry;
399 while (dlen > 0 && dp[dlen - 1] == 0)
407 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
408 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
410 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
412 Return the allocated memory in case of success, NULL in case of memory
413 allocation failure. */
415 divide (mpn_t a, mpn_t b, mpn_t *q)
418 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
419 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
420 If m<n, then q:=0 and r:=a.
421 If m>=n=1, perform a single-precision division:
424 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
425 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
426 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
427 Normalise [q[m-1],...,q[0]], yields q.
428 If m>=n>1, perform a multiple-precision division:
429 We have a/b < beta^(m-n+1).
430 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
431 Shift a and b left by s bits, copying them. r:=a.
432 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
433 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
435 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
436 In case of overflow (q* >= beta) set q* := beta-1.
437 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
438 and c3 := b[n-2] * q*.
439 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
440 occurred. Furthermore 0 <= c3 < beta^2.
441 If there was overflow and
442 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
443 the next test can be skipped.}
444 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
445 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
447 Put r := r - b * q* * beta^j. In detail:
448 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
449 hence: u:=0, for i:=0 to n-1 do
451 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
452 u:=u div beta (+ 1, if carry in subtraction)
454 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
456 the carry u does not overflow.}
457 If a negative carry occurs, put q* := q* - 1
458 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
460 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
461 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
463 The room for q[j] can be allocated at the memory location of r[n+j].
464 Finally, round-to-even:
465 Shift r left by 1 bit.
466 If r > b or if r = b and q[0] is odd, q := q+1.
468 const mp_limb_t *a_ptr = a.limbs;
469 size_t a_len = a.nlimbs;
470 const mp_limb_t *b_ptr = b.limbs;
471 size_t b_len = b.nlimbs;
473 mp_limb_t *tmp_roomptr = NULL;
479 /* Allocate room for a_len+2 digits.
480 (Need a_len+1 digits for the real division and 1 more digit for the
481 final rounding of q.) */
482 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
487 while (a_len > 0 && a_ptr[a_len - 1] == 0)
494 /* Division by zero. */
496 if (b_ptr[b_len - 1] == 0)
502 /* Here m = a_len >= 0 and n = b_len > 0. */
506 /* m<n: trivial case. q=0, r := copy of a. */
509 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
510 q_ptr = roomptr + a_len;
515 /* n=1: single precision division.
516 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
520 mp_limb_t den = b_ptr[0];
521 mp_limb_t remainder = 0;
522 const mp_limb_t *sourceptr = a_ptr + a_len;
523 mp_limb_t *destptr = q_ptr + a_len;
525 for (count = a_len; count > 0; count--)
528 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
529 *--destptr = num / den;
530 remainder = num % den;
532 /* Normalise and store r. */
535 r_ptr[0] = remainder;
542 if (q_ptr[q_len - 1] == 0)
548 /* n>1: multiple precision division.
549 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
550 beta^(m-n-1) <= a/b < beta^(m-n+1). */
554 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
555 /* Determine s = GMP_LIMB_BITS - integer_length (msd).
556 Code copied from gnulib's integer_length.c. */
557 # if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
558 s = __builtin_clz (msd);
560 # if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT
561 if (GMP_LIMB_BITS <= DBL_MANT_BIT)
563 /* Use 'double' operations.
564 Assumes an IEEE 754 'double' implementation. */
565 # define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)
566 # define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1)
568 ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
569 union { double value; unsigned int word[NWORDS]; } m;
571 /* Use a single integer to floating-point conversion. */
575 - (((m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK)
611 /* 0 <= s < GMP_LIMB_BITS.
612 Copy b, shifting it left by s bits. */
615 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
616 if (tmp_roomptr == NULL)
622 const mp_limb_t *sourceptr = b_ptr;
623 mp_limb_t *destptr = tmp_roomptr;
624 mp_twolimb_t accu = 0;
626 for (count = b_len; count > 0; count--)
628 accu += (mp_twolimb_t) *sourceptr++ << s;
629 *destptr++ = (mp_limb_t) accu;
630 accu = accu >> GMP_LIMB_BITS;
632 /* accu must be zero, since that was how s was determined. */
638 /* Copy a, shifting it left by s bits, yields r.
640 At the beginning: r = roomptr[0..a_len],
641 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
645 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
650 const mp_limb_t *sourceptr = a_ptr;
651 mp_limb_t *destptr = r_ptr;
652 mp_twolimb_t accu = 0;
654 for (count = a_len; count > 0; count--)
656 accu += (mp_twolimb_t) *sourceptr++ << s;
657 *destptr++ = (mp_limb_t) accu;
658 accu = accu >> GMP_LIMB_BITS;
660 *destptr++ = (mp_limb_t) accu;
662 q_ptr = roomptr + b_len;
663 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
665 size_t j = a_len - b_len; /* m-n */
666 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
667 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
668 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
669 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
670 /* Division loop, traversed m-n+1 times.
671 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
676 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
678 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
680 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
681 | r_ptr[j + b_len - 1];
682 q_star = num / b_msd;
687 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
688 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
689 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
690 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
691 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
693 If yes, jump directly to the subtraction loop.
694 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
695 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
696 if (r_ptr[j + b_len] > b_msd
697 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
698 /* r[j+n] >= b[n-1]+1 or
699 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
704 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
706 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
707 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
708 mp_twolimb_t c3 = /* b[n-2] * q* */
709 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
710 /* While c2 < c3, increase c2 and decrease c3.
711 Consider c3-c2. While it is > 0, decrease it by
712 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
713 this can happen only twice. */
716 q_star = q_star - 1; /* q* := q* - 1 */
717 if (c3 - c2 > b_msdd)
718 q_star = q_star - 1; /* q* := q* - 1 */
724 /* Subtract r := r - b * q* * beta^j. */
727 const mp_limb_t *sourceptr = b_ptr;
728 mp_limb_t *destptr = r_ptr + j;
729 mp_twolimb_t carry = 0;
731 for (count = b_len; count > 0; count--)
733 /* Here 0 <= carry <= q*. */
736 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
737 + (mp_limb_t) ~(*destptr);
738 /* Here 0 <= carry <= beta*q* + beta-1. */
739 *destptr++ = ~(mp_limb_t) carry;
740 carry = carry >> GMP_LIMB_BITS; /* <= q* */
742 cr = (mp_limb_t) carry;
744 /* Subtract cr from r_ptr[j + b_len], then forget about
746 if (cr > r_ptr[j + b_len])
748 /* Subtraction gave a carry. */
749 q_star = q_star - 1; /* q* := q* - 1 */
752 const mp_limb_t *sourceptr = b_ptr;
753 mp_limb_t *destptr = r_ptr + j;
756 for (count = b_len; count > 0; count--)
758 mp_limb_t source1 = *sourceptr++;
759 mp_limb_t source2 = *destptr;
760 *destptr++ = source1 + source2 + carry;
763 ? source1 >= (mp_limb_t) ~source2
764 : source1 > (mp_limb_t) ~source2);
767 /* Forget about the carry and about r[j+n]. */
770 /* q* is determined. Store it as q[j]. */
779 if (q_ptr[q_len - 1] == 0)
781 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
782 b is shifted left by s bits. */
783 /* Shift r right by s bits. */
786 mp_limb_t ptr = r_ptr + r_len;
787 mp_twolimb_t accu = 0;
789 for (count = r_len; count > 0; count--)
791 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
792 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
793 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
798 while (r_len > 0 && r_ptr[r_len - 1] == 0)
801 /* Compare r << 1 with b. */
809 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
810 | (i < r_len ? r_ptr[i] << 1 : 0);
811 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
821 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
826 for (i = 0; i < q_len; i++)
827 if (++(q_ptr[i]) != 0)
832 if (tmp_roomptr != NULL)
839 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
841 Destroys the contents of a.
842 Return the allocated memory - containing the decimal digits in low-to-high
843 order, terminated with a NUL character - in case of success, NULL in case
844 of memory allocation failure. */
846 convert_to_decimal (mpn_t a, size_t extra_zeroes)
848 mp_limb_t *a_ptr = a.limbs;
849 size_t a_len = a.nlimbs;
850 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
851 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
852 /* We need extra_zeroes bytes for zeroes, followed by c_len bytes for the
853 digits of a, followed by 1 byte for the terminating NUL. */
854 char *c_ptr = (char *) malloc (xsum (xsum (extra_zeroes, c_len), 1));
858 for (; extra_zeroes > 0; extra_zeroes--)
862 /* Divide a by 10^9, in-place. */
863 mp_limb_t remainder = 0;
864 mp_limb_t *ptr = a_ptr + a_len;
866 for (count = a_len; count > 0; count--)
869 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
870 *ptr = num / 1000000000;
871 remainder = num % 1000000000;
873 /* Store the remainder as 9 decimal digits. */
874 for (count = 9; count > 0; count--)
876 *d_ptr++ = '0' + (remainder % 10);
877 remainder = remainder / 10;
880 if (a_ptr[a_len - 1] == 0)
883 /* Remove leading zeroes. */
884 while (d_ptr > c_ptr && d_ptr[-1] == '0')
886 /* But keep at least one zero. */
889 /* Terminate the string. */
895 # if NEED_PRINTF_LONG_DOUBLE
897 /* Assuming x is finite and >= 0:
898 write x as x = 2^e * m, where m is a bignum.
899 Return the allocated memory in case of success, NULL in case of memory
900 allocation failure. */
902 decode_long_double (long double x, int *ep, mpn_t *mp)
909 /* Allocate memory for result. */
910 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
911 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
914 /* Split into exponential part and mantissa. */
915 y = frexpl (x, &exp);
916 if (!(y >= 0.0L && y < 1.0L))
918 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the
919 latter is an integer. */
920 /* Convert the mantissa (y * 2^LDBL_MANT_BIT) to a sequence of limbs.
921 I'm not sure whether it's safe to cast a 'long double' value between
922 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
923 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
925 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
926 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
929 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
932 if (!(y >= 0.0L && y < 1.0L))
934 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
937 if (!(y >= 0.0L && y < 1.0L))
939 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
944 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
947 if (!(y >= 0.0L && y < 1.0L))
949 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
953 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
956 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
959 if (!(y >= 0.0L && y < 1.0L))
961 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
964 if (!(y >= 0.0L && y < 1.0L))
966 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
968 # if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
974 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
977 *ep = exp - LDBL_MANT_BIT;
983 # if NEED_PRINTF_DOUBLE
985 /* Assuming x is finite and >= 0:
986 write x as x = 2^e * m, where m is a bignum.
987 Return the allocated memory in case of success, NULL in case of memory
988 allocation failure. */
990 decode_double (double x, int *ep, mpn_t *mp)
997 /* Allocate memory for result. */
998 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
999 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
1000 if (m.limbs == NULL)
1002 /* Split into exponential part and mantissa. */
1003 y = frexp (x, &exp);
1004 if (!(y >= 0.0 && y < 1.0))
1006 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the
1007 latter is an integer. */
1008 /* Convert the mantissa (y * 2^DBL_MANT_BIT) to a sequence of limbs.
1009 I'm not sure whether it's safe to cast a 'double' value between
1010 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1011 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1013 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
1014 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1017 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
1020 if (!(y >= 0.0 && y < 1.0))
1022 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1025 if (!(y >= 0.0 && y < 1.0))
1027 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1032 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
1035 if (!(y >= 0.0 && y < 1.0))
1037 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
1041 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1044 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1047 if (!(y >= 0.0 && y < 1.0))
1049 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1052 if (!(y >= 0.0 && y < 1.0))
1054 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1059 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1062 *ep = exp - DBL_MANT_BIT;
1068 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1069 Returns the decimal representation of round (x * 10^n).
1070 Return the allocated memory - containing the decimal digits in low-to-high
1071 order, terminated with a NUL character - in case of success, NULL in case
1072 of memory allocation failure. */
1074 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1077 size_t extra_zeroes;
1080 mp_limb_t *pow5_ptr;
1082 unsigned int s_limbs;
1083 unsigned int s_bits;
1091 /* x = 2^e * m, hence
1092 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1093 = round (2^s * 5^n * m). */
1096 /* Factor out a common power of 10 if possible. */
1099 extra_zeroes = (s < n ? s : n);
1103 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1104 Before converting to decimal, we need to compute
1105 z = round (2^s * 5^n * m). */
1106 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1107 sign. 2.322 is slightly larger than log(5)/log(2). */
1108 abs_n = (n >= 0 ? n : -n);
1109 abs_s = (s >= 0 ? s : -s);
1110 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1111 + abs_s / GMP_LIMB_BITS + 1)
1112 * sizeof (mp_limb_t));
1113 if (pow5_ptr == NULL)
1118 /* Initialize with 1. */
1121 /* Multiply with 5^|n|. */
1124 static mp_limb_t const small_pow5[13 + 1] =
1126 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1127 48828125, 244140625, 1220703125
1130 for (n13 = 0; n13 <= abs_n; n13 += 13)
1132 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1134 mp_twolimb_t carry = 0;
1135 for (j = 0; j < pow5_len; j++)
1137 mp_limb_t digit2 = pow5_ptr[j];
1138 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1139 pow5_ptr[j] = (mp_limb_t) carry;
1140 carry = carry >> GMP_LIMB_BITS;
1143 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1146 s_limbs = abs_s / GMP_LIMB_BITS;
1147 s_bits = abs_s % GMP_LIMB_BITS;
1148 if (n >= 0 ? s >= 0 : s <= 0)
1150 /* Multiply with 2^|s|. */
1153 mp_limb_t *ptr = pow5_ptr;
1154 mp_twolimb_t accu = 0;
1156 for (count = pow5_len; count > 0; count--)
1158 accu += (mp_twolimb_t) *ptr << s_bits;
1159 *ptr++ = (mp_limb_t) accu;
1160 accu = accu >> GMP_LIMB_BITS;
1164 *ptr = (mp_limb_t) accu;
1171 for (count = pow5_len; count > 0;)
1174 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1176 for (count = s_limbs; count > 0;)
1179 pow5_ptr[count] = 0;
1181 pow5_len += s_limbs;
1183 pow5.limbs = pow5_ptr;
1184 pow5.nlimbs = pow5_len;
1187 /* Multiply m with pow5. No division needed. */
1188 z_memory = multiply (m, pow5, &z);
1192 /* Divide m by pow5 and round. */
1193 z_memory = divide (m, pow5, &z);
1198 pow5.limbs = pow5_ptr;
1199 pow5.nlimbs = pow5_len;
1203 Multiply m with pow5, then divide by 2^|s|. */
1207 tmp_memory = multiply (m, pow5, &numerator);
1208 if (tmp_memory == NULL)
1214 /* Construct 2^|s|. */
1216 mp_limb_t *ptr = pow5_ptr + pow5_len;
1218 for (i = 0; i < s_limbs; i++)
1220 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1221 denominator.limbs = ptr;
1222 denominator.nlimbs = s_limbs + 1;
1224 z_memory = divide (numerator, denominator, &z);
1230 Multiply m with 2^s, then divide by pow5. */
1233 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1234 * sizeof (mp_limb_t));
1235 if (num_ptr == NULL)
1242 mp_limb_t *destptr = num_ptr;
1245 for (i = 0; i < s_limbs; i++)
1250 const mp_limb_t *sourceptr = m.limbs;
1251 mp_twolimb_t accu = 0;
1253 for (count = m.nlimbs; count > 0; count--)
1255 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1256 *destptr++ = (mp_limb_t) accu;
1257 accu = accu >> GMP_LIMB_BITS;
1260 *destptr++ = (mp_limb_t) accu;
1264 const mp_limb_t *sourceptr = m.limbs;
1266 for (count = m.nlimbs; count > 0; count--)
1267 *destptr++ = *sourceptr++;
1269 numerator.limbs = num_ptr;
1270 numerator.nlimbs = destptr - num_ptr;
1272 z_memory = divide (numerator, pow5, &z);
1279 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1281 if (z_memory == NULL)
1283 digits = convert_to_decimal (z, extra_zeroes);
1288 # if NEED_PRINTF_LONG_DOUBLE
1290 /* Assuming x is finite and >= 0, and n is an integer:
1291 Returns the decimal representation of round (x * 10^n).
1292 Return the allocated memory - containing the decimal digits in low-to-high
1293 order, terminated with a NUL character - in case of success, NULL in case
1294 of memory allocation failure. */
1296 scale10_round_decimal_long_double (long double x, int n)
1300 void *memory = decode_long_double (x, &e, &m);
1301 return scale10_round_decimal_decoded (e, m, memory, n);
1306 # if NEED_PRINTF_DOUBLE
1308 /* Assuming x is finite and >= 0, and n is an integer:
1309 Returns the decimal representation of round (x * 10^n).
1310 Return the allocated memory - containing the decimal digits in low-to-high
1311 order, terminated with a NUL character - in case of success, NULL in case
1312 of memory allocation failure. */
1314 scale10_round_decimal_double (double x, int n)
1318 void *memory = decode_double (x, &e, &m);
1319 return scale10_round_decimal_decoded (e, m, memory, n);
1324 # if NEED_PRINTF_LONG_DOUBLE
1326 /* Assuming x is finite and > 0:
1327 Return an approximation for n with 10^n <= x < 10^(n+1).
1328 The approximation is usually the right n, but may be off by 1 sometimes. */
1330 floorlog10l (long double x)
1337 /* Split into exponential part and mantissa. */
1338 y = frexpl (x, &exp);
1339 if (!(y >= 0.0L && y < 1.0L))
1345 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1347 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1348 exp -= GMP_LIMB_BITS;
1350 if (y < (1.0L / (1 << 16)))
1352 y *= 1.0L * (1 << 16);
1355 if (y < (1.0L / (1 << 8)))
1357 y *= 1.0L * (1 << 8);
1360 if (y < (1.0L / (1 << 4)))
1362 y *= 1.0L * (1 << 4);
1365 if (y < (1.0L / (1 << 2)))
1367 y *= 1.0L * (1 << 2);
1370 if (y < (1.0L / (1 << 1)))
1372 y *= 1.0L * (1 << 1);
1376 if (!(y >= 0.5L && y < 1.0L))
1378 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1381 if (z < 0.70710678118654752444)
1383 z *= 1.4142135623730950488;
1386 if (z < 0.8408964152537145431)
1388 z *= 1.1892071150027210667;
1391 if (z < 0.91700404320467123175)
1393 z *= 1.0905077326652576592;
1396 if (z < 0.9576032806985736469)
1398 z *= 1.0442737824274138403;
1401 /* Now 0.95 <= z <= 1.01. */
1403 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1404 Four terms are enough to get an approximation with error < 10^-7. */
1405 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1406 /* Finally multiply with log(2)/log(10), yields an approximation for
1408 l *= 0.30102999566398119523;
1409 /* Round down to the next integer. */
1410 return (int) l + (l < 0 ? -1 : 0);
1415 # if NEED_PRINTF_DOUBLE
1417 /* Assuming x is finite and > 0:
1418 Return an approximation for n with 10^n <= x < 10^(n+1).
1419 The approximation is usually the right n, but may be off by 1 sometimes. */
1421 floorlog10 (double x)
1428 /* Split into exponential part and mantissa. */
1429 y = frexp (x, &exp);
1430 if (!(y >= 0.0 && y < 1.0))
1436 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1438 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1439 exp -= GMP_LIMB_BITS;
1441 if (y < (1.0 / (1 << 16)))
1443 y *= 1.0 * (1 << 16);
1446 if (y < (1.0 / (1 << 8)))
1448 y *= 1.0 * (1 << 8);
1451 if (y < (1.0 / (1 << 4)))
1453 y *= 1.0 * (1 << 4);
1456 if (y < (1.0 / (1 << 2)))
1458 y *= 1.0 * (1 << 2);
1461 if (y < (1.0 / (1 << 1)))
1463 y *= 1.0 * (1 << 1);
1467 if (!(y >= 0.5 && y < 1.0))
1469 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1472 if (z < 0.70710678118654752444)
1474 z *= 1.4142135623730950488;
1477 if (z < 0.8408964152537145431)
1479 z *= 1.1892071150027210667;
1482 if (z < 0.91700404320467123175)
1484 z *= 1.0905077326652576592;
1487 if (z < 0.9576032806985736469)
1489 z *= 1.0442737824274138403;
1492 /* Now 0.95 <= z <= 1.01. */
1494 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1495 Four terms are enough to get an approximation with error < 10^-7. */
1496 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1497 /* Finally multiply with log(2)/log(10), yields an approximation for
1499 l *= 0.30102999566398119523;
1500 /* Round down to the next integer. */
1501 return (int) l + (l < 0 ? -1 : 0);
1506 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1507 a single '1' digit. */
1509 is_borderline (const char *digits, size_t precision)
1511 for (; precision > 0; precision--, digits++)
1517 return *digits == '\0';
1522 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99
1524 /* Use a different function name, to make it possible that the 'wchar_t'
1525 parametrization and the 'char' parametrization get compiled in the same
1526 translation unit. */
1527 # if WIDE_CHAR_VERSION
1528 # define MAX_ROOM_NEEDED wmax_room_needed
1530 # define MAX_ROOM_NEEDED max_room_needed
1533 /* Returns the number of TCHAR_T units needed as temporary space for the result
1534 of sprintf or SNPRINTF of a single conversion directive. */
1536 MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
1537 arg_type type, int flags, size_t width, int has_precision,
1538 size_t precision, int pad_ourselves)
1544 case 'd': case 'i': case 'u':
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.30103 /* binary -> decimal */
1551 + 1; /* turn floor into ceil */
1554 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1556 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1557 * 0.30103 /* binary -> decimal */
1559 + 1; /* turn floor into ceil */
1562 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1563 * 0.30103 /* binary -> decimal */
1565 + 1; /* turn floor into ceil */
1566 if (tmp_length < precision)
1567 tmp_length = precision;
1568 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1569 tmp_length = xsum (tmp_length, tmp_length);
1570 /* Add 1, to account for a leading sign. */
1571 tmp_length = xsum (tmp_length, 1);
1575 # if HAVE_LONG_LONG_INT
1576 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1578 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1579 * 0.333334 /* binary -> octal */
1581 + 1; /* turn floor into ceil */
1584 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1586 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1587 * 0.333334 /* binary -> octal */
1589 + 1; /* turn floor into ceil */
1592 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1593 * 0.333334 /* binary -> octal */
1595 + 1; /* turn floor into ceil */
1596 if (tmp_length < precision)
1597 tmp_length = precision;
1598 /* Add 1, to account for a leading sign. */
1599 tmp_length = xsum (tmp_length, 1);
1603 # if HAVE_LONG_LONG_INT
1604 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1606 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1607 * 0.25 /* binary -> hexadecimal */
1609 + 1; /* turn floor into ceil */
1612 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1614 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1615 * 0.25 /* binary -> hexadecimal */
1617 + 1; /* turn floor into ceil */
1620 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1621 * 0.25 /* binary -> hexadecimal */
1623 + 1; /* turn floor into ceil */
1624 if (tmp_length < precision)
1625 tmp_length = precision;
1626 /* Add 2, to account for a leading sign or alternate form. */
1627 tmp_length = xsum (tmp_length, 2);
1631 if (type == TYPE_LONGDOUBLE)
1633 (unsigned int) (LDBL_MAX_EXP
1634 * 0.30103 /* binary -> decimal */
1635 * 2 /* estimate for FLAG_GROUP */
1637 + 1 /* turn floor into ceil */
1638 + 10; /* sign, decimal point etc. */
1641 (unsigned int) (DBL_MAX_EXP
1642 * 0.30103 /* binary -> decimal */
1643 * 2 /* estimate for FLAG_GROUP */
1645 + 1 /* turn floor into ceil */
1646 + 10; /* sign, decimal point etc. */
1647 tmp_length = xsum (tmp_length, precision);
1650 case 'e': case 'E': case 'g': case 'G':
1652 12; /* sign, decimal point, exponent etc. */
1653 tmp_length = xsum (tmp_length, precision);
1657 if (type == TYPE_LONGDOUBLE)
1659 (unsigned int) (LDBL_DIG
1660 * 0.831 /* decimal -> hexadecimal */
1662 + 1; /* turn floor into ceil */
1665 (unsigned int) (DBL_DIG
1666 * 0.831 /* decimal -> hexadecimal */
1668 + 1; /* turn floor into ceil */
1669 if (tmp_length < precision)
1670 tmp_length = precision;
1671 /* Account for sign, decimal point etc. */
1672 tmp_length = xsum (tmp_length, 12);
1676 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
1677 if (type == TYPE_WIDE_CHAR)
1678 tmp_length = MB_CUR_MAX;
1686 if (type == TYPE_WIDE_STRING)
1688 # if WIDE_CHAR_VERSION
1689 /* ISO C says about %ls in fwprintf:
1690 "If the precision is not specified or is greater than the size
1691 of the array, the array shall contain a null wide character."
1692 So if there is a precision, we must not use wcslen. */
1693 const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
1696 tmp_length = local_wcsnlen (arg, precision);
1698 tmp_length = local_wcslen (arg);
1700 /* ISO C says about %ls in fprintf:
1701 "If a precision is specified, no more than that many bytes are
1702 written (including shift sequences, if any), and the array
1703 shall contain a null wide character if, to equal the multibyte
1704 character sequence length given by the precision, the function
1705 would need to access a wide character one past the end of the
1707 So if there is a precision, we must not use wcslen. */
1708 /* This case has already been handled separately in VASNPRINTF. */
1715 # if WIDE_CHAR_VERSION
1716 /* ISO C says about %s in fwprintf:
1717 "If the precision is not specified or is greater than the size
1718 of the converted array, the converted array shall contain a
1719 null wide character."
1720 So if there is a precision, we must not use strlen. */
1721 /* This case has already been handled separately in VASNPRINTF. */
1724 /* ISO C says about %s in fprintf:
1725 "If the precision is not specified or greater than the size of
1726 the array, the array shall contain a null character."
1727 So if there is a precision, we must not use strlen. */
1728 const char *arg = ap->arg[arg_index].a.a_string;
1731 tmp_length = local_strnlen (arg, precision);
1733 tmp_length = strlen (arg);
1740 (unsigned int) (sizeof (void *) * CHAR_BIT
1741 * 0.25 /* binary -> hexadecimal */
1743 + 1 /* turn floor into ceil */
1744 + 2; /* account for leading 0x */
1753 # if ENABLE_UNISTDIO
1754 /* Padding considers the number of characters, therefore the number of
1755 elements after padding may be
1756 > max (tmp_length, width)
1758 <= tmp_length + width. */
1759 tmp_length = xsum (tmp_length, width);
1761 /* Padding considers the number of elements, says POSIX. */
1762 if (tmp_length < width)
1767 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1775 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1776 const FCHAR_T *format, va_list args)
1781 if (PRINTF_PARSE (format, &d, &a) < 0)
1782 /* errno is already set. */
1786 if (d.dir != d.direct_alloc_dir) \
1788 if (a.arg != a.direct_alloc_arg) \
1791 if (PRINTF_FETCHARGS (args, &a) < 0)
1799 size_t buf_neededlength;
1801 TCHAR_T *buf_malloced;
1805 /* Output string accumulator. */
1810 /* Allocate a small buffer that will hold a directive passed to
1811 sprintf or snprintf. */
1813 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1815 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1817 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1818 buf_malloced = NULL;
1823 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1824 if (size_overflow_p (buf_memsize))
1825 goto out_of_memory_1;
1826 buf = (TCHAR_T *) malloc (buf_memsize);
1828 goto out_of_memory_1;
1832 if (resultbuf != NULL)
1835 allocated = *lengthp;
1844 result is either == resultbuf or == NULL or malloc-allocated.
1845 If length > 0, then result != NULL. */
1847 /* Ensures that allocated >= needed. Aborts through a jump to
1848 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1849 #define ENSURE_ALLOCATION(needed) \
1850 if ((needed) > allocated) \
1852 size_t memory_size; \
1855 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1856 if ((needed) > allocated) \
1857 allocated = (needed); \
1858 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1859 if (size_overflow_p (memory_size)) \
1860 goto out_of_memory; \
1861 if (result == resultbuf || result == NULL) \
1862 memory = (DCHAR_T *) malloc (memory_size); \
1864 memory = (DCHAR_T *) realloc (result, memory_size); \
1865 if (memory == NULL) \
1866 goto out_of_memory; \
1867 if (result == resultbuf && length > 0) \
1868 DCHAR_CPY (memory, result, length); \
1872 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1874 if (cp != dp->dir_start)
1876 size_t n = dp->dir_start - cp;
1877 size_t augmented_length = xsum (length, n);
1879 ENSURE_ALLOCATION (augmented_length);
1880 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1881 need that the format string contains only ASCII characters
1882 if FCHAR_T and DCHAR_T are not the same type. */
1883 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1885 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1886 length = augmented_length;
1891 result[length++] = *cp++;
1898 /* Execute a single directive. */
1899 if (dp->conversion == '%')
1901 size_t augmented_length;
1903 if (!(dp->arg_index == ARG_NONE))
1905 augmented_length = xsum (length, 1);
1906 ENSURE_ALLOCATION (augmented_length);
1907 result[length] = '%';
1908 length = augmented_length;
1912 if (!(dp->arg_index != ARG_NONE))
1915 if (dp->conversion == 'n')
1917 switch (a.arg[dp->arg_index].type)
1919 case TYPE_COUNT_SCHAR_POINTER:
1920 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1922 case TYPE_COUNT_SHORT_POINTER:
1923 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1925 case TYPE_COUNT_INT_POINTER:
1926 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1928 case TYPE_COUNT_LONGINT_POINTER:
1929 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1931 #if HAVE_LONG_LONG_INT
1932 case TYPE_COUNT_LONGLONGINT_POINTER:
1933 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1941 /* The unistdio extensions. */
1942 else if (dp->conversion == 'U')
1944 arg_type type = a.arg[dp->arg_index].type;
1945 int flags = dp->flags;
1953 if (dp->width_start != dp->width_end)
1955 if (dp->width_arg_index != ARG_NONE)
1959 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1961 arg = a.arg[dp->width_arg_index].a.a_int;
1965 /* "A negative field width is taken as a '-' flag
1966 followed by a positive field width." */
1973 const FCHAR_T *digitp = dp->width_start;
1976 width = xsum (xtimes (width, 10), *digitp++ - '0');
1977 while (digitp != dp->width_end);
1984 if (dp->precision_start != dp->precision_end)
1986 if (dp->precision_arg_index != ARG_NONE)
1990 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1992 arg = a.arg[dp->precision_arg_index].a.a_int;
1993 /* "A negative precision is taken as if the precision
2003 const FCHAR_T *digitp = dp->precision_start + 1;
2006 while (digitp != dp->precision_end)
2007 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2014 case TYPE_U8_STRING:
2016 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
2017 const uint8_t *arg_end;
2022 /* Use only PRECISION characters, from the left. */
2025 for (; precision > 0; precision--)
2027 int count = u8_strmblen (arg_end);
2032 if (!(result == resultbuf || result == NULL))
2034 if (buf_malloced != NULL)
2035 free (buf_malloced);
2046 /* Use the entire string, and count the number of
2052 int count = u8_strmblen (arg_end);
2057 if (!(result == resultbuf || result == NULL))
2059 if (buf_malloced != NULL)
2060 free (buf_malloced);
2071 /* Use the entire string. */
2072 arg_end = arg + u8_strlen (arg);
2073 /* The number of characters doesn't matter. */
2077 if (characters < width && !(dp->flags & FLAG_LEFT))
2079 size_t n = width - characters;
2080 ENSURE_ALLOCATION (xsum (length, n));
2081 DCHAR_SET (result + length, ' ', n);
2085 # if DCHAR_IS_UINT8_T
2087 size_t n = arg_end - arg;
2088 ENSURE_ALLOCATION (xsum (length, n));
2089 DCHAR_CPY (result + length, arg, n);
2094 DCHAR_T *converted = result + length;
2095 size_t converted_len = allocated - length;
2097 /* Convert from UTF-8 to locale encoding. */
2099 u8_conv_to_encoding (locale_charset (),
2100 iconveh_question_mark,
2101 arg, arg_end - arg, NULL,
2102 converted, &converted_len);
2104 /* Convert from UTF-8 to UTF-16/UTF-32. */
2106 U8_TO_DCHAR (arg, arg_end - arg,
2107 converted, &converted_len);
2109 if (converted == NULL)
2111 int saved_errno = errno;
2112 if (!(result == resultbuf || result == NULL))
2114 if (buf_malloced != NULL)
2115 free (buf_malloced);
2117 errno = saved_errno;
2120 if (converted != result + length)
2122 ENSURE_ALLOCATION (xsum (length, converted_len));
2123 DCHAR_CPY (result + length, converted, converted_len);
2126 length += converted_len;
2130 if (characters < width && (dp->flags & FLAG_LEFT))
2132 size_t n = width - characters;
2133 ENSURE_ALLOCATION (xsum (length, n));
2134 DCHAR_SET (result + length, ' ', n);
2140 case TYPE_U16_STRING:
2142 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
2143 const uint16_t *arg_end;
2148 /* Use only PRECISION characters, from the left. */
2151 for (; precision > 0; precision--)
2153 int count = u16_strmblen (arg_end);
2158 if (!(result == resultbuf || result == NULL))
2160 if (buf_malloced != NULL)
2161 free (buf_malloced);
2172 /* Use the entire string, and count the number of
2178 int count = u16_strmblen (arg_end);
2183 if (!(result == resultbuf || result == NULL))
2185 if (buf_malloced != NULL)
2186 free (buf_malloced);
2197 /* Use the entire string. */
2198 arg_end = arg + u16_strlen (arg);
2199 /* The number of characters doesn't matter. */
2203 if (characters < width && !(dp->flags & FLAG_LEFT))
2205 size_t n = width - characters;
2206 ENSURE_ALLOCATION (xsum (length, n));
2207 DCHAR_SET (result + length, ' ', n);
2211 # if DCHAR_IS_UINT16_T
2213 size_t n = arg_end - arg;
2214 ENSURE_ALLOCATION (xsum (length, n));
2215 DCHAR_CPY (result + length, arg, n);
2220 DCHAR_T *converted = result + length;
2221 size_t converted_len = allocated - length;
2223 /* Convert from UTF-16 to locale encoding. */
2225 u16_conv_to_encoding (locale_charset (),
2226 iconveh_question_mark,
2227 arg, arg_end - arg, NULL,
2228 converted, &converted_len);
2230 /* Convert from UTF-16 to UTF-8/UTF-32. */
2232 U16_TO_DCHAR (arg, arg_end - arg,
2233 converted, &converted_len);
2235 if (converted == NULL)
2237 int saved_errno = errno;
2238 if (!(result == resultbuf || result == NULL))
2240 if (buf_malloced != NULL)
2241 free (buf_malloced);
2243 errno = saved_errno;
2246 if (converted != result + length)
2248 ENSURE_ALLOCATION (xsum (length, converted_len));
2249 DCHAR_CPY (result + length, converted, converted_len);
2252 length += converted_len;
2256 if (characters < width && (dp->flags & FLAG_LEFT))
2258 size_t n = width - characters;
2259 ENSURE_ALLOCATION (xsum (length, n));
2260 DCHAR_SET (result + length, ' ', n);
2266 case TYPE_U32_STRING:
2268 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
2269 const uint32_t *arg_end;
2274 /* Use only PRECISION characters, from the left. */
2277 for (; precision > 0; precision--)
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, and count the number of
2304 int count = u32_strmblen (arg_end);
2309 if (!(result == resultbuf || result == NULL))
2311 if (buf_malloced != NULL)
2312 free (buf_malloced);
2323 /* Use the entire string. */
2324 arg_end = arg + u32_strlen (arg);
2325 /* The number of characters doesn't matter. */
2329 if (characters < width && !(dp->flags & FLAG_LEFT))
2331 size_t n = width - characters;
2332 ENSURE_ALLOCATION (xsum (length, n));
2333 DCHAR_SET (result + length, ' ', n);
2337 # if DCHAR_IS_UINT32_T
2339 size_t n = arg_end - arg;
2340 ENSURE_ALLOCATION (xsum (length, n));
2341 DCHAR_CPY (result + length, arg, n);
2346 DCHAR_T *converted = result + length;
2347 size_t converted_len = allocated - length;
2349 /* Convert from UTF-32 to locale encoding. */
2351 u32_conv_to_encoding (locale_charset (),
2352 iconveh_question_mark,
2353 arg, arg_end - arg, NULL,
2354 converted, &converted_len);
2356 /* Convert from UTF-32 to UTF-8/UTF-16. */
2358 U32_TO_DCHAR (arg, arg_end - arg,
2359 converted, &converted_len);
2361 if (converted == NULL)
2363 int saved_errno = errno;
2364 if (!(result == resultbuf || result == NULL))
2366 if (buf_malloced != NULL)
2367 free (buf_malloced);
2369 errno = saved_errno;
2372 if (converted != result + length)
2374 ENSURE_ALLOCATION (xsum (length, converted_len));
2375 DCHAR_CPY (result + length, converted, converted_len);
2378 length += converted_len;
2382 if (characters < width && (dp->flags & FLAG_LEFT))
2384 size_t n = width - characters;
2385 ENSURE_ALLOCATION (xsum (length, n));
2386 DCHAR_SET (result + length, ' ', n);
2397 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T
2398 else if (dp->conversion == 's'
2399 # if WIDE_CHAR_VERSION
2400 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2402 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2406 /* The normal handling of the 's' directive below requires
2407 allocating a temporary buffer. The determination of its
2408 length (tmp_length), in the case when a precision is
2409 specified, below requires a conversion between a char[]
2410 string and a wchar_t[] wide string. It could be done, but
2411 we have no guarantee that the implementation of sprintf will
2412 use the exactly same algorithm. Without this guarantee, it
2413 is possible to have buffer overrun bugs. In order to avoid
2414 such bugs, we implement the entire processing of the 's'
2415 directive ourselves. */
2416 int flags = dp->flags;
2424 if (dp->width_start != dp->width_end)
2426 if (dp->width_arg_index != ARG_NONE)
2430 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2432 arg = a.arg[dp->width_arg_index].a.a_int;
2436 /* "A negative field width is taken as a '-' flag
2437 followed by a positive field width." */
2444 const FCHAR_T *digitp = dp->width_start;
2447 width = xsum (xtimes (width, 10), *digitp++ - '0');
2448 while (digitp != dp->width_end);
2455 if (dp->precision_start != dp->precision_end)
2457 if (dp->precision_arg_index != ARG_NONE)
2461 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2463 arg = a.arg[dp->precision_arg_index].a.a_int;
2464 /* "A negative precision is taken as if the precision
2474 const FCHAR_T *digitp = dp->precision_start + 1;
2477 while (digitp != dp->precision_end)
2478 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2483 # if WIDE_CHAR_VERSION
2484 /* %s in vasnwprintf. See the specification of fwprintf. */
2486 const char *arg = a.arg[dp->arg_index].a.a_string;
2487 const char *arg_end;
2492 /* Use only as many bytes as needed to produce PRECISION
2493 wide characters, from the left. */
2496 memset (&state, '\0', sizeof (mbstate_t));
2500 for (; precision > 0; precision--)
2504 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2506 count = mblen (arg_end, MB_CUR_MAX);
2509 /* Found the terminating NUL. */
2513 /* Invalid or incomplete multibyte character. */
2514 if (!(result == resultbuf || result == NULL))
2516 if (buf_malloced != NULL)
2517 free (buf_malloced);
2528 /* Use the entire string, and count the number of wide
2532 memset (&state, '\0', sizeof (mbstate_t));
2540 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2542 count = mblen (arg_end, MB_CUR_MAX);
2545 /* Found the terminating NUL. */
2549 /* Invalid or incomplete multibyte character. */
2550 if (!(result == resultbuf || result == NULL))
2552 if (buf_malloced != NULL)
2553 free (buf_malloced);
2564 /* Use the entire string. */
2565 arg_end = arg + strlen (arg);
2566 /* The number of characters doesn't matter. */
2570 if (characters < width && !(dp->flags & FLAG_LEFT))
2572 size_t n = width - characters;
2573 ENSURE_ALLOCATION (xsum (length, n));
2574 DCHAR_SET (result + length, ' ', n);
2578 if (has_precision || has_width)
2580 /* We know the number of wide characters in advance. */
2584 memset (&state, '\0', sizeof (mbstate_t));
2586 ENSURE_ALLOCATION (xsum (length, characters));
2587 for (remaining = characters; remaining > 0; remaining--)
2592 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2594 count = mbtowc (&wc, arg, arg_end - arg);
2597 /* mbrtowc not consistent with mbrlen, or mbtowc
2598 not consistent with mblen. */
2600 result[length++] = wc;
2603 if (!(arg == arg_end))
2610 memset (&state, '\0', sizeof (mbstate_t));
2612 while (arg < arg_end)
2617 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2619 count = mbtowc (&wc, arg, arg_end - arg);
2622 /* mbrtowc not consistent with mbrlen, or mbtowc
2623 not consistent with mblen. */
2625 ENSURE_ALLOCATION (xsum (length, 1));
2626 result[length++] = wc;
2631 if (characters < width && (dp->flags & FLAG_LEFT))
2633 size_t n = width - characters;
2634 ENSURE_ALLOCATION (xsum (length, n));
2635 DCHAR_SET (result + length, ' ', n);
2640 /* %ls in vasnprintf. See the specification of fprintf. */
2642 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2643 const wchar_t *arg_end;
2645 # if !DCHAR_IS_TCHAR
2646 /* This code assumes that TCHAR_T is 'char'. */
2647 verify (sizeof (TCHAR_T) == 1);
2656 /* Use only as many wide characters as needed to produce
2657 at most PRECISION bytes, from the left. */
2658 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2660 memset (&state, '\0', sizeof (mbstate_t));
2664 while (precision > 0)
2666 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2670 /* Found the terminating null wide character. */
2672 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2673 count = wcrtomb (cbuf, *arg_end, &state);
2675 count = wctomb (cbuf, *arg_end);
2679 /* Cannot convert. */
2680 if (!(result == resultbuf || result == NULL))
2682 if (buf_malloced != NULL)
2683 free (buf_malloced);
2688 if (precision < count)
2691 characters += count;
2701 /* Use the entire string, and count the number of
2703 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2705 memset (&state, '\0', sizeof (mbstate_t));
2711 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2715 /* Found the terminating null wide character. */
2717 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2718 count = wcrtomb (cbuf, *arg_end, &state);
2720 count = wctomb (cbuf, *arg_end);
2724 /* Cannot convert. */
2725 if (!(result == resultbuf || result == NULL))
2727 if (buf_malloced != NULL)
2728 free (buf_malloced);
2734 characters += count;
2740 /* Use the entire string. */
2741 arg_end = arg + local_wcslen (arg);
2742 /* The number of bytes doesn't matter. */
2747 # if !DCHAR_IS_TCHAR
2748 /* Convert the string into a piece of temporary memory. */
2749 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2753 TCHAR_T *tmpptr = tmpsrc;
2755 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2757 memset (&state, '\0', sizeof (mbstate_t));
2759 for (remaining = characters; remaining > 0; )
2761 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2766 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2767 count = wcrtomb (cbuf, *arg, &state);
2769 count = wctomb (cbuf, *arg);
2772 /* Inconsistency. */
2774 memcpy (tmpptr, cbuf, count);
2779 if (!(arg == arg_end))
2783 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2785 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2786 iconveh_question_mark,
2792 int saved_errno = errno;
2794 if (!(result == resultbuf || result == NULL))
2796 if (buf_malloced != NULL)
2797 free (buf_malloced);
2799 errno = saved_errno;
2807 # if ENABLE_UNISTDIO
2808 /* Outside POSIX, it's preferable to compare the width
2809 against the number of _characters_ of the converted
2811 w = DCHAR_MBSNLEN (result + length, characters);
2813 /* The width is compared against the number of _bytes_
2814 of the converted value, says POSIX. */
2819 /* w doesn't matter. */
2822 if (w < width && !(dp->flags & FLAG_LEFT))
2824 size_t n = width - w;
2825 ENSURE_ALLOCATION (xsum (length, n));
2826 DCHAR_SET (result + length, ' ', n);
2831 if (has_precision || has_width)
2833 /* We know the number of bytes in advance. */
2835 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2837 memset (&state, '\0', sizeof (mbstate_t));
2839 ENSURE_ALLOCATION (xsum (length, characters));
2840 for (remaining = characters; remaining > 0; )
2842 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2847 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2848 count = wcrtomb (cbuf, *arg, &state);
2850 count = wctomb (cbuf, *arg);
2853 /* Inconsistency. */
2855 memcpy (result + length, cbuf, count);
2860 if (!(arg == arg_end))
2865 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2867 memset (&state, '\0', sizeof (mbstate_t));
2869 while (arg < arg_end)
2871 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2876 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2877 count = wcrtomb (cbuf, *arg, &state);
2879 count = wctomb (cbuf, *arg);
2883 /* Cannot convert. */
2884 if (!(result == resultbuf || result == NULL))
2886 if (buf_malloced != NULL)
2887 free (buf_malloced);
2892 ENSURE_ALLOCATION (xsum (length, count));
2893 memcpy (result + length, cbuf, count);
2899 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2900 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2902 length += tmpdst_len;
2905 if (w < width && (dp->flags & FLAG_LEFT))
2907 size_t n = width - w;
2908 ENSURE_ALLOCATION (xsum (length, n));
2909 DCHAR_SET (result + length, ' ', n);
2916 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2917 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2918 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2920 # if NEED_PRINTF_DOUBLE
2921 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2923 # if NEED_PRINTF_LONG_DOUBLE
2924 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2930 arg_type type = a.arg[dp->arg_index].type;
2931 int flags = dp->flags;
2937 DCHAR_T tmpbuf[700];
2943 if (dp->width_start != dp->width_end)
2945 if (dp->width_arg_index != ARG_NONE)
2949 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2951 arg = a.arg[dp->width_arg_index].a.a_int;
2955 /* "A negative field width is taken as a '-' flag
2956 followed by a positive field width." */
2963 const FCHAR_T *digitp = dp->width_start;
2966 width = xsum (xtimes (width, 10), *digitp++ - '0');
2967 while (digitp != dp->width_end);
2973 if (dp->precision_start != dp->precision_end)
2975 if (dp->precision_arg_index != ARG_NONE)
2979 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2981 arg = a.arg[dp->precision_arg_index].a.a_int;
2982 /* "A negative precision is taken as if the precision
2992 const FCHAR_T *digitp = dp->precision_start + 1;
2995 while (digitp != dp->precision_end)
2996 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3001 /* Allocate a temporary buffer of sufficient size. */
3002 if (type == TYPE_LONGDOUBLE)
3004 (unsigned int) ((LDBL_DIG + 1)
3005 * 0.831 /* decimal -> hexadecimal */
3007 + 1; /* turn floor into ceil */
3010 (unsigned int) ((DBL_DIG + 1)
3011 * 0.831 /* decimal -> hexadecimal */
3013 + 1; /* turn floor into ceil */
3014 if (tmp_length < precision)
3015 tmp_length = precision;
3016 /* Account for sign, decimal point etc. */
3017 tmp_length = xsum (tmp_length, 12);
3019 if (tmp_length < width)
3022 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3024 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3028 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3030 if (size_overflow_p (tmp_memsize))
3031 /* Overflow, would lead to out of memory. */
3033 tmp = (DCHAR_T *) malloc (tmp_memsize);
3035 /* Out of memory. */
3041 if (type == TYPE_LONGDOUBLE)
3043 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
3044 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3048 if (dp->conversion == 'A')
3050 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3054 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3060 DECL_LONG_DOUBLE_ROUNDING
3062 BEGIN_LONG_DOUBLE_ROUNDING ();
3064 if (signbit (arg)) /* arg < 0.0L or negative zero */
3072 else if (flags & FLAG_SHOWSIGN)
3074 else if (flags & FLAG_SPACE)
3077 if (arg > 0.0L && arg + arg == arg)
3079 if (dp->conversion == 'A')
3081 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3085 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3091 long double mantissa;
3094 mantissa = printf_frexpl (arg, &exponent);
3102 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
3104 /* Round the mantissa. */
3105 long double tail = mantissa;
3108 for (q = precision; ; q--)
3110 int digit = (int) tail;
3114 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
3123 for (q = precision; q > 0; q--)
3129 *p++ = dp->conversion - 'A' + 'X';
3134 digit = (int) mantissa;
3137 if ((flags & FLAG_ALT)
3138 || mantissa > 0.0L || precision > 0)
3140 *p++ = decimal_point_char ();
3141 /* This loop terminates because we assume
3142 that FLT_RADIX is a power of 2. */
3143 while (mantissa > 0.0L)
3146 digit = (int) mantissa;
3151 : dp->conversion - 10);
3155 while (precision > 0)
3162 *p++ = dp->conversion - 'A' + 'P';
3163 # if WIDE_CHAR_VERSION
3165 static const wchar_t decimal_format[] =
3166 { '%', '+', 'd', '\0' };
3167 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3172 if (sizeof (DCHAR_T) == 1)
3174 sprintf ((char *) p, "%+d", exponent);
3182 sprintf (expbuf, "%+d", exponent);
3183 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3189 END_LONG_DOUBLE_ROUNDING ();
3197 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
3198 double arg = a.arg[dp->arg_index].a.a_double;
3202 if (dp->conversion == 'A')
3204 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3208 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3215 if (signbit (arg)) /* arg < 0.0 or negative zero */
3223 else if (flags & FLAG_SHOWSIGN)
3225 else if (flags & FLAG_SPACE)
3228 if (arg > 0.0 && arg + arg == arg)
3230 if (dp->conversion == 'A')
3232 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3236 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3245 mantissa = printf_frexp (arg, &exponent);
3253 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
3255 /* Round the mantissa. */
3256 double tail = mantissa;
3259 for (q = precision; ; q--)
3261 int digit = (int) tail;
3265 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
3274 for (q = precision; q > 0; q--)
3280 *p++ = dp->conversion - 'A' + 'X';
3285 digit = (int) mantissa;
3288 if ((flags & FLAG_ALT)
3289 || mantissa > 0.0 || precision > 0)
3291 *p++ = decimal_point_char ();
3292 /* This loop terminates because we assume
3293 that FLT_RADIX is a power of 2. */
3294 while (mantissa > 0.0)
3297 digit = (int) mantissa;
3302 : dp->conversion - 10);
3306 while (precision > 0)
3313 *p++ = dp->conversion - 'A' + 'P';
3314 # if WIDE_CHAR_VERSION
3316 static const wchar_t decimal_format[] =
3317 { '%', '+', 'd', '\0' };
3318 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3323 if (sizeof (DCHAR_T) == 1)
3325 sprintf ((char *) p, "%+d", exponent);
3333 sprintf (expbuf, "%+d", exponent);
3334 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3345 /* The generated string now extends from tmp to p, with the
3346 zero padding insertion point being at pad_ptr. */
3351 size_t pad = width - count;
3352 DCHAR_T *end = p + pad;
3354 if (flags & FLAG_LEFT)
3356 /* Pad with spaces on the right. */
3357 for (; pad > 0; pad--)
3360 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3362 /* Pad with zeroes. */
3367 for (; pad > 0; pad--)
3372 /* Pad with spaces on the left. */
3377 for (; pad > 0; pad--)
3386 if (count >= tmp_length)
3387 /* tmp_length was incorrectly calculated - fix the
3391 /* Make room for the result. */
3392 if (count >= allocated - length)
3394 size_t n = xsum (length, count);
3396 ENSURE_ALLOCATION (n);
3399 /* Append the result. */
3400 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3406 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3407 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3408 || dp->conversion == 'e' || dp->conversion == 'E'
3409 || dp->conversion == 'g' || dp->conversion == 'G'
3410 || dp->conversion == 'a' || dp->conversion == 'A')
3412 # if NEED_PRINTF_DOUBLE
3413 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3414 # elif NEED_PRINTF_INFINITE_DOUBLE
3415 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3416 /* The systems (mingw) which produce wrong output
3417 for Inf, -Inf, and NaN also do so for -0.0.
3418 Therefore we treat this case here as well. */
3419 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3421 # if NEED_PRINTF_LONG_DOUBLE
3422 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3423 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3424 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3425 /* Some systems produce wrong output for Inf,
3426 -Inf, and NaN. Some systems in this category
3427 (IRIX 5.3) also do so for -0.0. Therefore we
3428 treat this case here as well. */
3429 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3433 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3434 arg_type type = a.arg[dp->arg_index].type;
3436 int flags = dp->flags;
3442 DCHAR_T tmpbuf[700];
3448 if (dp->width_start != dp->width_end)
3450 if (dp->width_arg_index != ARG_NONE)
3454 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3456 arg = a.arg[dp->width_arg_index].a.a_int;
3460 /* "A negative field width is taken as a '-' flag
3461 followed by a positive field width." */
3468 const FCHAR_T *digitp = dp->width_start;
3471 width = xsum (xtimes (width, 10), *digitp++ - '0');
3472 while (digitp != dp->width_end);
3478 if (dp->precision_start != dp->precision_end)
3480 if (dp->precision_arg_index != ARG_NONE)
3484 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3486 arg = a.arg[dp->precision_arg_index].a.a_int;
3487 /* "A negative precision is taken as if the precision
3497 const FCHAR_T *digitp = dp->precision_start + 1;
3500 while (digitp != dp->precision_end)
3501 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3506 /* POSIX specifies the default precision to be 6 for %f, %F,
3507 %e, %E, but not for %g, %G. Implementations appear to use
3508 the same default precision also for %g, %G. But for %a, %A,
3509 the default precision is 0. */
3511 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3514 /* Allocate a temporary buffer of sufficient size. */
3515 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3516 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3517 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3518 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3519 # elif NEED_PRINTF_LONG_DOUBLE
3520 tmp_length = LDBL_DIG + 1;
3521 # elif NEED_PRINTF_DOUBLE
3522 tmp_length = DBL_DIG + 1;
3526 if (tmp_length < precision)
3527 tmp_length = precision;
3528 # if NEED_PRINTF_LONG_DOUBLE
3529 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3530 if (type == TYPE_LONGDOUBLE)
3532 if (dp->conversion == 'f' || dp->conversion == 'F')
3534 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3535 if (!(isnanl (arg) || arg + arg == arg))
3537 /* arg is finite and nonzero. */
3538 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3539 if (exponent >= 0 && tmp_length < exponent + precision)
3540 tmp_length = exponent + precision;
3544 # if NEED_PRINTF_DOUBLE
3545 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3546 if (type == TYPE_DOUBLE)
3548 if (dp->conversion == 'f' || dp->conversion == 'F')
3550 double arg = a.arg[dp->arg_index].a.a_double;
3551 if (!(isnand (arg) || arg + arg == arg))
3553 /* arg is finite and nonzero. */
3554 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3555 if (exponent >= 0 && tmp_length < exponent + precision)
3556 tmp_length = exponent + precision;
3560 /* Account for sign, decimal point etc. */
3561 tmp_length = xsum (tmp_length, 12);
3563 if (tmp_length < width)
3566 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3568 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3572 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3574 if (size_overflow_p (tmp_memsize))
3575 /* Overflow, would lead to out of memory. */
3577 tmp = (DCHAR_T *) malloc (tmp_memsize);
3579 /* Out of memory. */
3586 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3587 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3588 if (type == TYPE_LONGDOUBLE)
3591 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3595 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3597 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3601 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3607 DECL_LONG_DOUBLE_ROUNDING
3609 BEGIN_LONG_DOUBLE_ROUNDING ();
3611 if (signbit (arg)) /* arg < 0.0L or negative zero */
3619 else if (flags & FLAG_SHOWSIGN)
3621 else if (flags & FLAG_SPACE)
3624 if (arg > 0.0L && arg + arg == arg)
3626 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3628 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3632 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3637 # if NEED_PRINTF_LONG_DOUBLE
3640 if (dp->conversion == 'f' || dp->conversion == 'F')
3646 scale10_round_decimal_long_double (arg, precision);
3649 END_LONG_DOUBLE_ROUNDING ();
3652 ndigits = strlen (digits);
3654 if (ndigits > precision)
3658 *p++ = digits[ndigits];
3660 while (ndigits > precision);
3663 /* Here ndigits <= precision. */
3664 if ((flags & FLAG_ALT) || precision > 0)
3666 *p++ = decimal_point_char ();
3667 for (; precision > ndigits; precision--)
3672 *p++ = digits[ndigits];
3678 else if (dp->conversion == 'e' || dp->conversion == 'E')
3686 if ((flags & FLAG_ALT) || precision > 0)
3688 *p++ = decimal_point_char ();
3689 for (; precision > 0; precision--)
3700 exponent = floorlog10l (arg);
3705 scale10_round_decimal_long_double (arg,
3706 (int)precision - exponent);
3709 END_LONG_DOUBLE_ROUNDING ();
3712 ndigits = strlen (digits);
3714 if (ndigits == precision + 1)
3716 if (ndigits < precision
3717 || ndigits > precision + 2)
3718 /* The exponent was not guessed
3719 precisely enough. */
3722 /* None of two values of exponent is
3723 the right one. Prevent an endless
3727 if (ndigits == precision)
3733 /* Here ndigits = precision+1. */
3734 if (is_borderline (digits, precision))
3736 /* Maybe the exponent guess was too high
3737 and a smaller exponent can be reached
3738 by turning a 10...0 into 9...9x. */
3740 scale10_round_decimal_long_double (arg,
3741 (int)precision - exponent + 1);
3742 if (digits2 == NULL)
3745 END_LONG_DOUBLE_ROUNDING ();
3748 if (strlen (digits2) == precision + 1)
3757 /* Here ndigits = precision+1. */
3759 *p++ = digits[--ndigits];
3760 if ((flags & FLAG_ALT) || precision > 0)
3762 *p++ = decimal_point_char ();
3766 *p++ = digits[ndigits];
3773 *p++ = dp->conversion; /* 'e' or 'E' */
3774 # if WIDE_CHAR_VERSION
3776 static const wchar_t decimal_format[] =
3777 { '%', '+', '.', '2', 'd', '\0' };
3778 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3783 if (sizeof (DCHAR_T) == 1)
3785 sprintf ((char *) p, "%+.2d", exponent);
3793 sprintf (expbuf, "%+.2d", exponent);
3794 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3799 else if (dp->conversion == 'g' || dp->conversion == 'G')
3803 /* precision >= 1. */
3806 /* The exponent is 0, >= -4, < precision.
3807 Use fixed-point notation. */
3809 size_t ndigits = precision;
3810 /* Number of trailing zeroes that have to be
3813 (flags & FLAG_ALT ? 0 : precision - 1);
3817 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3819 *p++ = decimal_point_char ();
3820 while (ndigits > nzeroes)
3836 exponent = floorlog10l (arg);
3841 scale10_round_decimal_long_double (arg,
3842 (int)(precision - 1) - exponent);
3845 END_LONG_DOUBLE_ROUNDING ();
3848 ndigits = strlen (digits);
3850 if (ndigits == precision)
3852 if (ndigits < precision - 1
3853 || ndigits > precision + 1)
3854 /* The exponent was not guessed
3855 precisely enough. */
3858 /* None of two values of exponent is
3859 the right one. Prevent an endless
3863 if (ndigits < precision)
3869 /* Here ndigits = precision. */
3870 if (is_borderline (digits, precision - 1))
3872 /* Maybe the exponent guess was too high
3873 and a smaller exponent can be reached
3874 by turning a 10...0 into 9...9x. */
3876 scale10_round_decimal_long_double (arg,
3877 (int)(precision - 1) - exponent + 1);
3878 if (digits2 == NULL)
3881 END_LONG_DOUBLE_ROUNDING ();
3884 if (strlen (digits2) == precision)
3893 /* Here ndigits = precision. */
3895 /* Determine the number of trailing zeroes
3896 that have to be dropped. */
3898 if ((flags & FLAG_ALT) == 0)
3899 while (nzeroes < ndigits
3900 && digits[nzeroes] == '0')
3903 /* The exponent is now determined. */
3905 && exponent < (long)precision)
3907 /* Fixed-point notation:
3908 max(exponent,0)+1 digits, then the
3909 decimal point, then the remaining
3910 digits without trailing zeroes. */
3913 size_t ecount = exponent + 1;
3914 /* Note: count <= precision = ndigits. */
3915 for (; ecount > 0; ecount--)
3916 *p++ = digits[--ndigits];
3917 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3919 *p++ = decimal_point_char ();
3920 while (ndigits > nzeroes)
3923 *p++ = digits[ndigits];
3929 size_t ecount = -exponent - 1;
3931 *p++ = decimal_point_char ();
3932 for (; ecount > 0; ecount--)
3934 while (ndigits > nzeroes)
3937 *p++ = digits[ndigits];
3943 /* Exponential notation. */
3944 *p++ = digits[--ndigits];
3945 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3947 *p++ = decimal_point_char ();
3948 while (ndigits > nzeroes)
3951 *p++ = digits[ndigits];
3954 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3955 # if WIDE_CHAR_VERSION
3957 static const wchar_t decimal_format[] =
3958 { '%', '+', '.', '2', 'd', '\0' };
3959 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3964 if (sizeof (DCHAR_T) == 1)
3966 sprintf ((char *) p, "%+.2d", exponent);
3974 sprintf (expbuf, "%+.2d", exponent);
3975 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3987 /* arg is finite. */
3993 if (dp->conversion == 'f' || dp->conversion == 'F')
3996 if ((flags & FLAG_ALT) || precision > 0)
3998 *p++ = decimal_point_char ();
3999 for (; precision > 0; precision--)
4003 else if (dp->conversion == 'e' || dp->conversion == 'E')
4006 if ((flags & FLAG_ALT) || precision > 0)
4008 *p++ = decimal_point_char ();
4009 for (; precision > 0; precision--)
4012 *p++ = dp->conversion; /* 'e' or 'E' */
4017 else if (dp->conversion == 'g' || dp->conversion == 'G')
4020 if (flags & FLAG_ALT)
4023 (precision > 0 ? precision - 1 : 0);
4024 *p++ = decimal_point_char ();
4025 for (; ndigits > 0; --ndigits)
4029 else if (dp->conversion == 'a' || dp->conversion == 'A')
4032 *p++ = dp->conversion - 'A' + 'X';
4035 if ((flags & FLAG_ALT) || precision > 0)
4037 *p++ = decimal_point_char ();
4038 for (; precision > 0; precision--)
4041 *p++ = dp->conversion - 'A' + 'P';
4050 END_LONG_DOUBLE_ROUNDING ();
4053 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4057 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4059 double arg = a.arg[dp->arg_index].a.a_double;
4063 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4065 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4069 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4076 if (signbit (arg)) /* arg < 0.0 or negative zero */
4084 else if (flags & FLAG_SHOWSIGN)
4086 else if (flags & FLAG_SPACE)
4089 if (arg > 0.0 && arg + arg == arg)
4091 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4093 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4097 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4102 # if NEED_PRINTF_DOUBLE
4105 if (dp->conversion == 'f' || dp->conversion == 'F')
4111 scale10_round_decimal_double (arg, precision);
4114 ndigits = strlen (digits);
4116 if (ndigits > precision)
4120 *p++ = digits[ndigits];
4122 while (ndigits > precision);
4125 /* Here ndigits <= precision. */
4126 if ((flags & FLAG_ALT) || precision > 0)
4128 *p++ = decimal_point_char ();
4129 for (; precision > ndigits; precision--)
4134 *p++ = digits[ndigits];
4140 else if (dp->conversion == 'e' || dp->conversion == 'E')
4148 if ((flags & FLAG_ALT) || precision > 0)
4150 *p++ = decimal_point_char ();
4151 for (; precision > 0; precision--)
4162 exponent = floorlog10 (arg);
4167 scale10_round_decimal_double (arg,
4168 (int)precision - exponent);
4171 ndigits = strlen (digits);
4173 if (ndigits == precision + 1)
4175 if (ndigits < precision
4176 || ndigits > precision + 2)
4177 /* The exponent was not guessed
4178 precisely enough. */
4181 /* None of two values of exponent is
4182 the right one. Prevent an endless
4186 if (ndigits == precision)
4192 /* Here ndigits = precision+1. */
4193 if (is_borderline (digits, precision))
4195 /* Maybe the exponent guess was too high
4196 and a smaller exponent can be reached
4197 by turning a 10...0 into 9...9x. */
4199 scale10_round_decimal_double (arg,
4200 (int)precision - exponent + 1);
4201 if (digits2 == NULL)
4206 if (strlen (digits2) == precision + 1)
4215 /* Here ndigits = precision+1. */
4217 *p++ = digits[--ndigits];
4218 if ((flags & FLAG_ALT) || precision > 0)
4220 *p++ = decimal_point_char ();
4224 *p++ = digits[ndigits];
4231 *p++ = dp->conversion; /* 'e' or 'E' */
4232 # if WIDE_CHAR_VERSION
4234 static const wchar_t decimal_format[] =
4235 /* Produce the same number of exponent digits
4236 as the native printf implementation. */
4237 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4238 { '%', '+', '.', '3', 'd', '\0' };
4240 { '%', '+', '.', '2', 'd', '\0' };
4242 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4248 static const char decimal_format[] =
4249 /* Produce the same number of exponent digits
4250 as the native printf implementation. */
4251 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4256 if (sizeof (DCHAR_T) == 1)
4258 sprintf ((char *) p, decimal_format, exponent);
4266 sprintf (expbuf, decimal_format, exponent);
4267 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4273 else if (dp->conversion == 'g' || dp->conversion == 'G')
4277 /* precision >= 1. */
4280 /* The exponent is 0, >= -4, < precision.
4281 Use fixed-point notation. */
4283 size_t ndigits = precision;
4284 /* Number of trailing zeroes that have to be
4287 (flags & FLAG_ALT ? 0 : precision - 1);
4291 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4293 *p++ = decimal_point_char ();
4294 while (ndigits > nzeroes)
4310 exponent = floorlog10 (arg);
4315 scale10_round_decimal_double (arg,
4316 (int)(precision - 1) - exponent);
4319 ndigits = strlen (digits);
4321 if (ndigits == precision)
4323 if (ndigits < precision - 1
4324 || ndigits > precision + 1)
4325 /* The exponent was not guessed
4326 precisely enough. */
4329 /* None of two values of exponent is
4330 the right one. Prevent an endless
4334 if (ndigits < precision)
4340 /* Here ndigits = precision. */
4341 if (is_borderline (digits, precision - 1))
4343 /* Maybe the exponent guess was too high
4344 and a smaller exponent can be reached
4345 by turning a 10...0 into 9...9x. */
4347 scale10_round_decimal_double (arg,
4348 (int)(precision - 1) - exponent + 1);
4349 if (digits2 == NULL)
4354 if (strlen (digits2) == precision)
4363 /* Here ndigits = precision. */
4365 /* Determine the number of trailing zeroes
4366 that have to be dropped. */
4368 if ((flags & FLAG_ALT) == 0)
4369 while (nzeroes < ndigits
4370 && digits[nzeroes] == '0')
4373 /* The exponent is now determined. */
4375 && exponent < (long)precision)
4377 /* Fixed-point notation:
4378 max(exponent,0)+1 digits, then the
4379 decimal point, then the remaining
4380 digits without trailing zeroes. */
4383 size_t ecount = exponent + 1;
4384 /* Note: ecount <= precision = ndigits. */
4385 for (; ecount > 0; ecount--)
4386 *p++ = digits[--ndigits];
4387 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4389 *p++ = decimal_point_char ();
4390 while (ndigits > nzeroes)
4393 *p++ = digits[ndigits];
4399 size_t ecount = -exponent - 1;
4401 *p++ = decimal_point_char ();
4402 for (; ecount > 0; ecount--)
4404 while (ndigits > nzeroes)
4407 *p++ = digits[ndigits];
4413 /* Exponential notation. */
4414 *p++ = digits[--ndigits];
4415 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4417 *p++ = decimal_point_char ();
4418 while (ndigits > nzeroes)
4421 *p++ = digits[ndigits];
4424 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4425 # if WIDE_CHAR_VERSION
4427 static const wchar_t decimal_format[] =
4428 /* Produce the same number of exponent digits
4429 as the native printf implementation. */
4430 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4431 { '%', '+', '.', '3', 'd', '\0' };
4433 { '%', '+', '.', '2', 'd', '\0' };
4435 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4441 static const char decimal_format[] =
4442 /* Produce the same number of exponent digits
4443 as the native printf implementation. */
4444 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4449 if (sizeof (DCHAR_T) == 1)
4451 sprintf ((char *) p, decimal_format, exponent);
4459 sprintf (expbuf, decimal_format, exponent);
4460 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4473 /* arg is finite. */
4479 if (dp->conversion == 'f' || dp->conversion == 'F')
4482 if ((flags & FLAG_ALT) || precision > 0)
4484 *p++ = decimal_point_char ();
4485 for (; precision > 0; precision--)
4489 else if (dp->conversion == 'e' || dp->conversion == 'E')
4492 if ((flags & FLAG_ALT) || precision > 0)
4494 *p++ = decimal_point_char ();
4495 for (; precision > 0; precision--)
4498 *p++ = dp->conversion; /* 'e' or 'E' */
4500 /* Produce the same number of exponent digits as
4501 the native printf implementation. */
4502 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4508 else if (dp->conversion == 'g' || dp->conversion == 'G')
4511 if (flags & FLAG_ALT)
4514 (precision > 0 ? precision - 1 : 0);
4515 *p++ = decimal_point_char ();
4516 for (; ndigits > 0; --ndigits)
4528 /* The generated string now extends from tmp to p, with the
4529 zero padding insertion point being at pad_ptr. */
4534 size_t pad = width - count;
4535 DCHAR_T *end = p + pad;
4537 if (flags & FLAG_LEFT)
4539 /* Pad with spaces on the right. */
4540 for (; pad > 0; pad--)
4543 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4545 /* Pad with zeroes. */
4550 for (; pad > 0; pad--)
4555 /* Pad with spaces on the left. */
4560 for (; pad > 0; pad--)
4569 if (count >= tmp_length)
4570 /* tmp_length was incorrectly calculated - fix the
4574 /* Make room for the result. */
4575 if (count >= allocated - length)
4577 size_t n = xsum (length, count);
4579 ENSURE_ALLOCATION (n);
4582 /* Append the result. */
4583 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4591 arg_type type = a.arg[dp->arg_index].type;
4592 int flags = dp->flags;
4593 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4596 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4599 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4603 #if NEED_PRINTF_UNBOUNDED_PRECISION
4606 # define prec_ourselves 0
4608 #if NEED_PRINTF_FLAG_LEFTADJUST
4609 # define pad_ourselves 1
4610 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4613 # define pad_ourselves 0
4616 unsigned int prefix_count;
4617 int prefixes[2] IF_LINT (= { 0 });
4621 TCHAR_T tmpbuf[700];
4625 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4628 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4630 if (dp->width_start != dp->width_end)
4632 if (dp->width_arg_index != ARG_NONE)
4636 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4638 arg = a.arg[dp->width_arg_index].a.a_int;
4642 /* "A negative field width is taken as a '-' flag
4643 followed by a positive field width." */
4650 const FCHAR_T *digitp = dp->width_start;
4653 width = xsum (xtimes (width, 10), *digitp++ - '0');
4654 while (digitp != dp->width_end);
4656 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4662 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
4665 if (dp->precision_start != dp->precision_end)
4667 if (dp->precision_arg_index != ARG_NONE)
4671 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4673 arg = a.arg[dp->precision_arg_index].a.a_int;
4674 /* "A negative precision is taken as if the precision
4684 const FCHAR_T *digitp = dp->precision_start + 1;
4687 while (digitp != dp->precision_end)
4688 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4694 /* Decide whether to handle the precision ourselves. */
4695 #if NEED_PRINTF_UNBOUNDED_PRECISION
4696 switch (dp->conversion)
4698 case 'd': case 'i': case 'u':
4700 case 'x': case 'X': case 'p':
4701 prec_ourselves = has_precision && (precision > 0);
4709 /* Decide whether to perform the padding ourselves. */
4710 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4711 switch (dp->conversion)
4713 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4714 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4715 to perform the padding after this conversion. Functions
4716 with unistdio extensions perform the padding based on
4717 character count rather than element count. */
4720 # if NEED_PRINTF_FLAG_ZERO
4721 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4727 pad_ourselves = prec_ourselves;
4733 /* Allocate a temporary buffer of sufficient size for calling
4736 MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
4737 flags, width, has_precision, precision,
4740 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4744 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4746 if (size_overflow_p (tmp_memsize))
4747 /* Overflow, would lead to out of memory. */
4749 tmp = (TCHAR_T *) malloc (tmp_memsize);
4751 /* Out of memory. */
4756 /* Construct the format string for calling snprintf or
4760 #if NEED_PRINTF_FLAG_GROUPING
4761 /* The underlying implementation doesn't support the ' flag.
4762 Produce no grouping characters in this case; this is
4763 acceptable because the grouping is locale dependent. */
4765 if (flags & FLAG_GROUP)
4768 if (flags & FLAG_LEFT)
4770 if (flags & FLAG_SHOWSIGN)
4772 if (flags & FLAG_SPACE)
4774 if (flags & FLAG_ALT)
4776 #if __GLIBC__ >= 2 && !defined __UCLIBC__
4777 if (flags & FLAG_LOCALIZED)
4782 if (flags & FLAG_ZERO)
4784 if (dp->width_start != dp->width_end)
4786 size_t n = dp->width_end - dp->width_start;
4787 /* The width specification is known to consist only
4788 of standard ASCII characters. */
4789 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4791 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4796 const FCHAR_T *mp = dp->width_start;
4803 if (!prec_ourselves)
4805 if (dp->precision_start != dp->precision_end)
4807 size_t n = dp->precision_end - dp->precision_start;
4808 /* The precision specification is known to consist only
4809 of standard ASCII characters. */
4810 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4812 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4817 const FCHAR_T *mp = dp->precision_start;
4827 #if HAVE_LONG_LONG_INT
4828 case TYPE_LONGLONGINT:
4829 case TYPE_ULONGLONGINT:
4830 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4843 case TYPE_WIDE_CHAR:
4846 case TYPE_WIDE_STRING:
4850 case TYPE_LONGDOUBLE:
4856 #if NEED_PRINTF_DIRECTIVE_F
4857 if (dp->conversion == 'F')
4861 *fbp = dp->conversion;
4863 # if !(((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) && !defined __UCLIBC__) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4868 /* On glibc2 systems from glibc >= 2.3 - probably also older
4869 ones - we know that snprintf's return value conforms to
4870 ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and
4871 gl_SNPRINTF_TRUNCATION_C99 pass.
4872 Therefore we can avoid using %n in this situation.
4873 On glibc2 systems from 2004-10-18 or newer, the use of %n
4874 in format strings in writable memory may crash the program
4875 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4876 in this situation. */
4877 /* On native Windows systems (such as mingw), we can avoid using
4879 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4880 snprintf does not write more than the specified number
4881 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4882 '4', '5', '6' into buf, not '4', '5', '\0'.)
4883 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4884 allows us to recognize the case of an insufficient
4885 buffer size: it returns -1 in this case.
4886 On native Windows systems (such as mingw) where the OS is
4887 Windows Vista, the use of %n in format strings by default
4888 crashes the program. See
4889 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4890 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4891 So we should avoid %n in this situation. */
4898 /* Construct the arguments for calling snprintf or sprintf. */
4900 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4902 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4904 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4906 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4908 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4910 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4914 /* The SNPRINTF result is appended after result[0..length].
4915 The latter is an array of DCHAR_T; SNPRINTF appends an
4916 array of TCHAR_T to it. This is possible because
4917 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4918 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4919 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4920 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4921 where an snprintf() with maxlen==1 acts like sprintf(). */
4922 ENSURE_ALLOCATION (xsum (length,
4923 (2 + TCHARS_PER_DCHAR - 1)
4924 / TCHARS_PER_DCHAR));
4925 /* Prepare checking whether snprintf returns the count
4927 *(TCHAR_T *) (result + length) = '\0';
4938 size_t maxlen = allocated - length;
4939 /* SNPRINTF can fail if its second argument is
4941 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4942 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4943 maxlen = maxlen * TCHARS_PER_DCHAR;
4944 # define SNPRINTF_BUF(arg) \
4945 switch (prefix_count) \
4948 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4953 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4955 prefixes[0], arg, &count); \
4958 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4960 prefixes[0], prefixes[1], arg, \
4967 # define SNPRINTF_BUF(arg) \
4968 switch (prefix_count) \
4971 count = sprintf (tmp, buf, arg); \
4974 count = sprintf (tmp, buf, prefixes[0], arg); \
4977 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4990 int arg = a.arg[dp->arg_index].a.a_schar;
4996 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
5002 int arg = a.arg[dp->arg_index].a.a_short;
5008 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
5014 int arg = a.arg[dp->arg_index].a.a_int;
5020 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
5026 long int arg = a.arg[dp->arg_index].a.a_longint;
5032 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
5036 #if HAVE_LONG_LONG_INT
5037 case TYPE_LONGLONGINT:
5039 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
5043 case TYPE_ULONGLONGINT:
5045 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
5052 double arg = a.arg[dp->arg_index].a.a_double;
5056 case TYPE_LONGDOUBLE:
5058 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5064 int arg = a.arg[dp->arg_index].a.a_char;
5069 case TYPE_WIDE_CHAR:
5071 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5078 const char *arg = a.arg[dp->arg_index].a.a_string;
5083 case TYPE_WIDE_STRING:
5085 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5092 void *arg = a.arg[dp->arg_index].a.a_pointer;
5101 /* Portability: Not all implementations of snprintf()
5102 are ISO C 99 compliant. Determine the number of
5103 bytes that snprintf() has produced or would have
5107 /* Verify that snprintf() has NUL-terminated its
5110 && ((TCHAR_T *) (result + length)) [count] != '\0')
5112 /* Portability hack. */
5113 if (retcount > count)
5118 /* snprintf() doesn't understand the '%n'
5122 /* Don't use the '%n' directive; instead, look
5123 at the snprintf() return value. */
5129 /* Look at the snprintf() return value. */
5132 # if !HAVE_SNPRINTF_RETVAL_C99
5133 /* HP-UX 10.20 snprintf() is doubly deficient:
5134 It doesn't understand the '%n' directive,
5135 *and* it returns -1 (rather than the length
5136 that would have been required) when the
5137 buffer is too small.
5138 But a failure at this point can also come
5139 from other reasons than a too small buffer,
5140 such as an invalid wide string argument to
5141 the %ls directive, or possibly an invalid
5142 floating-point argument. */
5144 MAX_ROOM_NEEDED (&a, dp->arg_index,
5145 dp->conversion, type, flags,
5148 precision, pad_ourselves);
5150 if (maxlen < tmp_length)
5152 /* Make more room. But try to do through
5153 this reallocation only once. */
5154 size_t bigger_need =
5157 TCHARS_PER_DCHAR - 1)
5158 / TCHARS_PER_DCHAR);
5159 /* And always grow proportionally.
5160 (There may be several arguments, each
5161 needing a little more room than the
5163 size_t bigger_need2 =
5164 xsum (xtimes (allocated, 2), 12);
5165 if (bigger_need < bigger_need2)
5166 bigger_need = bigger_need2;
5167 ENSURE_ALLOCATION (bigger_need);
5178 /* Attempt to handle failure. */
5181 /* SNPRINTF or sprintf failed. Save and use the errno
5182 that it has set, if any. */
5183 int saved_errno = errno;
5184 if (saved_errno == 0)
5186 if (dp->conversion == 'c' || dp->conversion == 's')
5187 saved_errno = EILSEQ;
5189 saved_errno = EINVAL;
5192 if (!(result == resultbuf || result == NULL))
5194 if (buf_malloced != NULL)
5195 free (buf_malloced);
5198 errno = saved_errno;
5203 /* Handle overflow of the allocated buffer.
5204 If such an overflow occurs, a C99 compliant snprintf()
5205 returns a count >= maxlen. However, a non-compliant
5206 snprintf() function returns only count = maxlen - 1. To
5207 cover both cases, test whether count >= maxlen - 1. */
5208 if ((unsigned int) count + 1 >= maxlen)
5210 /* If maxlen already has attained its allowed maximum,
5211 allocating more memory will not increase maxlen.
5212 Instead of looping, bail out. */
5213 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5217 /* Need at least (count + 1) * sizeof (TCHAR_T)
5218 bytes. (The +1 is for the trailing NUL.)
5219 But ask for (count + 2) * sizeof (TCHAR_T)
5220 bytes, so that in the next round, we likely get
5221 maxlen > (unsigned int) count + 1
5222 and so we don't get here again.
5223 And allocate proportionally, to avoid looping
5224 eternally if snprintf() reports a too small
5228 ((unsigned int) count + 2
5229 + TCHARS_PER_DCHAR - 1)
5230 / TCHARS_PER_DCHAR),
5231 xtimes (allocated, 2));
5233 ENSURE_ALLOCATION (n);
5239 #if NEED_PRINTF_UNBOUNDED_PRECISION
5242 /* Handle the precision. */
5245 (TCHAR_T *) (result + length);
5249 size_t prefix_count;
5253 /* Put the additional zeroes after the sign. */
5255 && (*prec_ptr == '-' || *prec_ptr == '+'
5256 || *prec_ptr == ' '))
5258 /* Put the additional zeroes after the 0x prefix if
5259 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5261 && prec_ptr[0] == '0'
5262 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5265 move = count - prefix_count;
5266 if (precision > move)
5268 /* Insert zeroes. */
5269 size_t insert = precision - move;
5275 (count + insert + TCHARS_PER_DCHAR - 1)
5276 / TCHARS_PER_DCHAR);
5277 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5278 ENSURE_ALLOCATION (n);
5279 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5280 prec_ptr = (TCHAR_T *) (result + length);
5283 prec_end = prec_ptr + count;
5284 prec_ptr += prefix_count;
5286 while (prec_end > prec_ptr)
5289 prec_end[insert] = prec_end[0];
5295 while (prec_end > prec_ptr);
5303 if (count >= tmp_length)
5304 /* tmp_length was incorrectly calculated - fix the
5310 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5311 if (dp->conversion == 'c' || dp->conversion == 's')
5313 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5315 The result string is not certainly ASCII. */
5316 const TCHAR_T *tmpsrc;
5319 /* This code assumes that TCHAR_T is 'char'. */
5320 verify (sizeof (TCHAR_T) == 1);
5322 tmpsrc = (TCHAR_T *) (result + length);
5327 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5328 iconveh_question_mark,
5334 int saved_errno = errno;
5335 if (!(result == resultbuf || result == NULL))
5337 if (buf_malloced != NULL)
5338 free (buf_malloced);
5340 errno = saved_errno;
5343 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5344 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5350 /* The result string is ASCII.
5351 Simple 1:1 conversion. */
5353 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5354 no-op conversion, in-place on the array starting
5355 at (result + length). */
5356 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5359 const TCHAR_T *tmpsrc;
5364 if (result == resultbuf)
5366 tmpsrc = (TCHAR_T *) (result + length);
5367 /* ENSURE_ALLOCATION will not move tmpsrc
5368 (because it's part of resultbuf). */
5369 ENSURE_ALLOCATION (xsum (length, count));
5373 /* ENSURE_ALLOCATION will move the array
5374 (because it uses realloc(). */
5375 ENSURE_ALLOCATION (xsum (length, count));
5376 tmpsrc = (TCHAR_T *) (result + length);
5380 ENSURE_ALLOCATION (xsum (length, count));
5382 tmpdst = result + length;
5383 /* Copy backwards, because of overlapping. */
5386 for (n = count; n > 0; n--)
5387 *--tmpdst = *--tmpsrc;
5392 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5393 /* Make room for the result. */
5394 if (count > allocated - length)
5396 /* Need at least count elements. But allocate
5399 xmax (xsum (length, count), xtimes (allocated, 2));
5401 ENSURE_ALLOCATION (n);
5405 /* Here count <= allocated - length. */
5407 /* Perform padding. */
5408 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5409 if (pad_ourselves && has_width)
5412 # if ENABLE_UNISTDIO
5413 /* Outside POSIX, it's preferable to compare the width
5414 against the number of _characters_ of the converted
5416 w = DCHAR_MBSNLEN (result + length, count);
5418 /* The width is compared against the number of _bytes_
5419 of the converted value, says POSIX. */
5424 size_t pad = width - w;
5426 /* Make room for the result. */
5427 if (xsum (count, pad) > allocated - length)
5429 /* Need at least count + pad elements. But
5430 allocate proportionally. */
5432 xmax (xsum3 (length, count, pad),
5433 xtimes (allocated, 2));
5437 ENSURE_ALLOCATION (n);
5440 ENSURE_ALLOCATION (n);
5443 /* Here count + pad <= allocated - length. */
5446 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5447 DCHAR_T * const rp = result + length;
5449 DCHAR_T * const rp = tmp;
5451 DCHAR_T *p = rp + count;
5452 DCHAR_T *end = p + pad;
5454 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5455 if (dp->conversion == 'c'
5456 || dp->conversion == 's')
5457 /* No zero-padding for string directives. */
5462 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5463 /* No zero-padding of "inf" and "nan". */
5464 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5465 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5468 /* The generated string now extends from rp to p,
5469 with the zero padding insertion point being at
5472 count = count + pad; /* = end - rp */
5474 if (flags & FLAG_LEFT)
5476 /* Pad with spaces on the right. */
5477 for (; pad > 0; pad--)
5480 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5482 /* Pad with zeroes. */
5487 for (; pad > 0; pad--)
5492 /* Pad with spaces on the left. */
5497 for (; pad > 0; pad--)
5505 /* Here still count <= allocated - length. */
5507 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5508 /* The snprintf() result did fit. */
5510 /* Append the sprintf() result. */
5511 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5518 #if NEED_PRINTF_DIRECTIVE_F
5519 if (dp->conversion == 'F')
5521 /* Convert the %f result to upper case for %F. */
5522 DCHAR_T *rp = result + length;
5524 for (rc = count; rc > 0; rc--, rp++)
5525 if (*rp >= 'a' && *rp <= 'z')
5526 *rp = *rp - 'a' + 'A';
5534 #undef pad_ourselves
5535 #undef prec_ourselves
5540 /* Add the final NUL. */
5541 ENSURE_ALLOCATION (xsum (length, 1));
5542 result[length] = '\0';
5544 if (result != resultbuf && length + 1 < allocated)
5546 /* Shrink the allocated memory if possible. */
5549 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5554 if (buf_malloced != NULL)
5555 free (buf_malloced);
5558 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5559 says that snprintf() fails with errno = EOVERFLOW in this case, but
5560 that's only because snprintf() returns an 'int'. This function does
5561 not have this limitation. */
5566 if (!(result == resultbuf || result == NULL))
5568 if (buf_malloced != NULL)
5569 free (buf_malloced);
5576 if (!(result == resultbuf || result == NULL))
5578 if (buf_malloced != NULL)
5579 free (buf_malloced);
5587 #undef MAX_ROOM_NEEDED
5588 #undef TCHARS_PER_DCHAR
5596 #undef DCHAR_IS_TCHAR