1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2019 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 Lesser General Public License as published by
6 the Free Software Foundation; either version 2.1, 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 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License along
15 with this program; if not, see <https://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. */
47 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
48 This must come before <config.h> because <config.h> may include
49 <features.h>, and once <features.h> has been included, it's too late. */
51 # define _GNU_SOURCE 1
58 #include "glib/galloca.h"
64 # if WIDE_CHAR_VERSION
65 # include "vasnwprintf.h"
67 # include "vasnprintf.h"
71 #include <locale.h> /* localeconv() */
72 #include <stdio.h> /* snprintf(), sprintf() */
73 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
74 #include <string.h> /* memcpy(), strlen() */
75 #include <errno.h> /* errno */
76 #include <limits.h> /* CHAR_BIT */
77 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
79 # include <langinfo.h>
82 # if WIDE_CHAR_VERSION
83 # include "wprintf-parse.h"
85 # include "printf-parse.h"
89 /* Checked size_t computations. */
94 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
95 # include <gnulib_math.h>
99 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
100 # include <gnulib_math.h>
101 # include "isnand-nolibm.h"
104 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
105 # include <gnulib_math.h>
106 # include "isnanl-nolibm.h"
110 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
111 # include <gnulib_math.h>
112 # include "isnand-nolibm.h"
113 # include "printf-frexp.h"
116 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
117 # include <gnulib_math.h>
118 # include "isnanl-nolibm.h"
119 # include "printf-frexpl.h"
125 # define FALLTHROUGH ((void) 0)
127 # define FALLTHROUGH __attribute__ ((__fallthrough__))
131 /* Default parameters. */
133 # if WIDE_CHAR_VERSION
134 # define VASNPRINTF vasnwprintf
135 # define FCHAR_T wchar_t
136 # define DCHAR_T wchar_t
137 # define TCHAR_T wchar_t
138 # define DCHAR_IS_TCHAR 1
139 # define DIRECTIVE wchar_t_directive
140 # define DIRECTIVES wchar_t_directives
141 # define PRINTF_PARSE wprintf_parse
142 # define DCHAR_CPY wmemcpy
143 # define DCHAR_SET wmemset
145 # define VASNPRINTF vasnprintf
146 # define FCHAR_T char
147 # define DCHAR_T char
148 # define TCHAR_T char
149 # define DCHAR_IS_TCHAR 1
150 # define DIRECTIVE char_directive
151 # define DIRECTIVES char_directives
152 # define PRINTF_PARSE printf_parse
153 # define DCHAR_CPY memcpy
154 # define DCHAR_SET memset
157 #if WIDE_CHAR_VERSION
158 /* TCHAR_T is wchar_t. */
159 # define USE_SNPRINTF 1
160 # if HAVE_DECL__SNWPRINTF
161 /* On Windows, the function swprintf() has a different signature than
162 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
163 instead. The mingw function snwprintf() has fewer bugs than the
164 MSVCRT function _snwprintf(), so prefer that. */
165 # if defined __MINGW32__
166 # define SNPRINTF snwprintf
168 # define SNPRINTF _snwprintf
169 # define USE_MSVC__SNPRINTF 1
173 # define SNPRINTF swprintf
176 /* TCHAR_T is char. */
177 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
178 But don't use it on BeOS, since BeOS snprintf produces no output if the
179 size argument is >= 0x3000000.
180 Also don't use it on Linux libc5, since there snprintf with size = 1
181 writes any output without bounds, like sprintf. */
182 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
183 # define USE_SNPRINTF 1
185 # define USE_SNPRINTF 0
187 # if HAVE_DECL__SNPRINTF
188 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
189 function _snprintf(), so prefer that. */
190 # if defined __MINGW32__
191 # define SNPRINTF snprintf
192 /* Here we need to call the native snprintf, not rpl_snprintf. */
195 /* MSVC versions < 14 did not have snprintf, only _snprintf. */
196 # define SNPRINTF _snprintf
197 # define USE_MSVC__SNPRINTF 1
201 # define SNPRINTF snprintf
202 /* Here we need to call the native snprintf, not rpl_snprintf. */
206 /* Here we need to call the native sprintf, not rpl_sprintf. */
209 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
210 warnings in this file. Use -Dlint to suppress them. */
211 #if defined GCC_LINT || defined lint
212 # define IF_LINT(Code) Code
214 # define IF_LINT(Code) /* empty */
217 /* Avoid some warnings from "gcc -Wshadow".
218 This file doesn't use the exp() and remainder() functions. */
222 #define remainder rem
224 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && !WIDE_CHAR_VERSION
225 # if (HAVE_STRNLEN && !defined _AIX)
226 # define local_strnlen strnlen
228 # ifndef local_strnlen_defined
229 # define local_strnlen_defined 1
231 local_strnlen (const char *string, size_t maxlen)
233 const char *end = memchr (string, '\0', maxlen);
234 return end ? (size_t) (end - string) : maxlen;
240 #if (((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && WIDE_CHAR_VERSION) || ((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && !WIDE_CHAR_VERSION && DCHAR_IS_TCHAR)) && HAVE_WCHAR_T
242 # define local_wcslen wcslen
244 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
245 a dependency towards this library, here is a local substitute.
246 Define this substitute only once, even if this file is included
247 twice in the same compilation unit. */
248 # ifndef local_wcslen_defined
249 # define local_wcslen_defined 1
251 local_wcslen (const wchar_t *s)
255 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
263 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
265 # define local_wcsnlen wcsnlen
267 # ifndef local_wcsnlen_defined
268 # define local_wcsnlen_defined 1
270 local_wcsnlen (const wchar_t *s, size_t maxlen)
274 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
282 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
283 /* Determine the decimal-point character according to the current locale. */
284 # ifndef decimal_point_char_defined
285 # define decimal_point_char_defined 1
287 decimal_point_char (void)
290 /* Determine it in a multithread-safe way. We know nl_langinfo is
291 multithread-safe on glibc systems and Mac OS X systems, but is not required
292 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
293 localeconv() is rarely multithread-safe. */
294 # if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
295 point = nl_langinfo (RADIXCHAR);
298 sprintf (pointbuf, "%#.0f", 1.0);
299 point = &pointbuf[1];
301 point = localeconv () -> decimal_point;
303 /* The decimal point is always a single byte: either '.' or ','. */
304 return (point[0] != '\0' ? point[0] : '.');
309 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
311 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
313 is_infinite_or_zero (double x)
315 return isnand (x) || x + x == x;
320 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
322 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
324 is_infinite_or_zerol (long double x)
326 return isnanl (x) || x + x == x;
331 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
333 /* Converting 'long double' to decimal without rare rounding bugs requires
334 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
335 (and slower) algorithms. */
337 typedef unsigned int mp_limb_t;
338 # define GMP_LIMB_BITS 32
339 verify (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS);
341 typedef unsigned long long mp_twolimb_t;
342 # define GMP_TWOLIMB_BITS 64
343 verify (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS);
345 /* Representation of a bignum >= 0. */
349 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
352 /* Compute the product of two bignums >= 0.
353 Return the allocated memory in case of success, NULL in case of memory
354 allocation failure. */
356 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
363 if (src1.nlimbs <= src2.nlimbs)
377 /* Now 0 <= len1 <= len2. */
380 /* src1 or src2 is zero. */
382 dest->limbs = (mp_limb_t *) malloc (1);
386 /* Here 1 <= len1 <= len2. */
392 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
395 for (k = len2; k > 0; )
397 for (i = 0; i < len1; i++)
399 mp_limb_t digit1 = p1[i];
400 mp_twolimb_t carry = 0;
401 for (j = 0; j < len2; j++)
403 mp_limb_t digit2 = p2[j];
404 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
406 dp[i + j] = (mp_limb_t) carry;
407 carry = carry >> GMP_LIMB_BITS;
409 dp[i + len2] = (mp_limb_t) carry;
412 while (dlen > 0 && dp[dlen - 1] == 0)
420 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
421 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
423 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
425 Return the allocated memory in case of success, NULL in case of memory
426 allocation failure. */
428 divide (mpn_t a, mpn_t b, mpn_t *q)
431 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
432 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
433 If m<n, then q:=0 and r:=a.
434 If m>=n=1, perform a single-precision division:
437 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
438 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
439 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
440 Normalise [q[m-1],...,q[0]], yields q.
441 If m>=n>1, perform a multiple-precision division:
442 We have a/b < beta^(m-n+1).
443 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
444 Shift a and b left by s bits, copying them. r:=a.
445 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
446 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
448 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
449 In case of overflow (q* >= beta) set q* := beta-1.
450 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
451 and c3 := b[n-2] * q*.
452 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
453 occurred. Furthermore 0 <= c3 < beta^2.
454 If there was overflow and
455 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
456 the next test can be skipped.}
457 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
458 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
460 Put r := r - b * q* * beta^j. In detail:
461 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
462 hence: u:=0, for i:=0 to n-1 do
464 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
465 u:=u div beta (+ 1, if carry in subtraction)
467 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
469 the carry u does not overflow.}
470 If a negative carry occurs, put q* := q* - 1
471 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
473 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
474 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
476 The room for q[j] can be allocated at the memory location of r[n+j].
477 Finally, round-to-even:
478 Shift r left by 1 bit.
479 If r > b or if r = b and q[0] is odd, q := q+1.
481 const mp_limb_t *a_ptr = a.limbs;
482 size_t a_len = a.nlimbs;
483 const mp_limb_t *b_ptr = b.limbs;
484 size_t b_len = b.nlimbs;
486 mp_limb_t *tmp_roomptr = NULL;
492 /* Allocate room for a_len+2 digits.
493 (Need a_len+1 digits for the real division and 1 more digit for the
494 final rounding of q.) */
495 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
500 while (a_len > 0 && a_ptr[a_len - 1] == 0)
507 /* Division by zero. */
509 if (b_ptr[b_len - 1] == 0)
515 /* Here m = a_len >= 0 and n = b_len > 0. */
519 /* m<n: trivial case. q=0, r := copy of a. */
522 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
523 q_ptr = roomptr + a_len;
528 /* n=1: single precision division.
529 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
533 mp_limb_t den = b_ptr[0];
534 mp_limb_t remainder = 0;
535 const mp_limb_t *sourceptr = a_ptr + a_len;
536 mp_limb_t *destptr = q_ptr + a_len;
538 for (count = a_len; count > 0; count--)
541 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
542 *--destptr = num / den;
543 remainder = num % den;
545 /* Normalise and store r. */
548 r_ptr[0] = remainder;
555 if (q_ptr[q_len - 1] == 0)
561 /* n>1: multiple precision division.
562 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
563 beta^(m-n-1) <= a/b < beta^(m-n+1). */
567 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
568 /* Determine s = GMP_LIMB_BITS - integer_length (msd).
569 Code copied from gnulib's integer_length.c. */
570 # if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
571 s = __builtin_clz (msd);
573 # if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT
574 if (GMP_LIMB_BITS <= DBL_MANT_BIT)
576 /* Use 'double' operations.
577 Assumes an IEEE 754 'double' implementation. */
578 # define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)
579 # define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1)
581 ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
582 union { double value; unsigned int word[NWORDS]; } m;
584 /* Use a single integer to floating-point conversion. */
588 - (((m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK)
624 /* 0 <= s < GMP_LIMB_BITS.
625 Copy b, shifting it left by s bits. */
628 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
629 if (tmp_roomptr == NULL)
635 const mp_limb_t *sourceptr = b_ptr;
636 mp_limb_t *destptr = tmp_roomptr;
637 mp_twolimb_t accu = 0;
639 for (count = b_len; count > 0; count--)
641 accu += (mp_twolimb_t) *sourceptr++ << s;
642 *destptr++ = (mp_limb_t) accu;
643 accu = accu >> GMP_LIMB_BITS;
645 /* accu must be zero, since that was how s was determined. */
651 /* Copy a, shifting it left by s bits, yields r.
653 At the beginning: r = roomptr[0..a_len],
654 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
658 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
663 const mp_limb_t *sourceptr = a_ptr;
664 mp_limb_t *destptr = r_ptr;
665 mp_twolimb_t accu = 0;
667 for (count = a_len; count > 0; count--)
669 accu += (mp_twolimb_t) *sourceptr++ << s;
670 *destptr++ = (mp_limb_t) accu;
671 accu = accu >> GMP_LIMB_BITS;
673 *destptr++ = (mp_limb_t) accu;
675 q_ptr = roomptr + b_len;
676 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
678 size_t j = a_len - b_len; /* m-n */
679 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
680 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
681 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
682 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
683 /* Division loop, traversed m-n+1 times.
684 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
689 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
691 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
693 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
694 | r_ptr[j + b_len - 1];
695 q_star = num / b_msd;
700 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
701 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
702 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
703 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
704 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
706 If yes, jump directly to the subtraction loop.
707 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
708 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
709 if (r_ptr[j + b_len] > b_msd
710 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
711 /* r[j+n] >= b[n-1]+1 or
712 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
717 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
719 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
720 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
721 mp_twolimb_t c3 = /* b[n-2] * q* */
722 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
723 /* While c2 < c3, increase c2 and decrease c3.
724 Consider c3-c2. While it is > 0, decrease it by
725 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
726 this can happen only twice. */
729 q_star = q_star - 1; /* q* := q* - 1 */
730 if (c3 - c2 > b_msdd)
731 q_star = q_star - 1; /* q* := q* - 1 */
737 /* Subtract r := r - b * q* * beta^j. */
740 const mp_limb_t *sourceptr = b_ptr;
741 mp_limb_t *destptr = r_ptr + j;
742 mp_twolimb_t carry = 0;
744 for (count = b_len; count > 0; count--)
746 /* Here 0 <= carry <= q*. */
749 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
750 + (mp_limb_t) ~(*destptr);
751 /* Here 0 <= carry <= beta*q* + beta-1. */
752 *destptr++ = ~(mp_limb_t) carry;
753 carry = carry >> GMP_LIMB_BITS; /* <= q* */
755 cr = (mp_limb_t) carry;
757 /* Subtract cr from r_ptr[j + b_len], then forget about
759 if (cr > r_ptr[j + b_len])
761 /* Subtraction gave a carry. */
762 q_star = q_star - 1; /* q* := q* - 1 */
765 const mp_limb_t *sourceptr = b_ptr;
766 mp_limb_t *destptr = r_ptr + j;
769 for (count = b_len; count > 0; count--)
771 mp_limb_t source1 = *sourceptr++;
772 mp_limb_t source2 = *destptr;
773 *destptr++ = source1 + source2 + carry;
776 ? source1 >= (mp_limb_t) ~source2
777 : source1 > (mp_limb_t) ~source2);
780 /* Forget about the carry and about r[j+n]. */
783 /* q* is determined. Store it as q[j]. */
792 if (q_ptr[q_len - 1] == 0)
794 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
795 b is shifted left by s bits. */
796 /* Shift r right by s bits. */
799 mp_limb_t ptr = r_ptr + r_len;
800 mp_twolimb_t accu = 0;
802 for (count = r_len; count > 0; count--)
804 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
805 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
806 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
811 while (r_len > 0 && r_ptr[r_len - 1] == 0)
814 /* Compare r << 1 with b. */
822 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
823 | (i < r_len ? r_ptr[i] << 1 : 0);
824 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
834 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
839 for (i = 0; i < q_len; i++)
840 if (++(q_ptr[i]) != 0)
845 if (tmp_roomptr != NULL)
852 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
854 Destroys the contents of a.
855 Return the allocated memory - containing the decimal digits in low-to-high
856 order, terminated with a NUL character - in case of success, NULL in case
857 of memory allocation failure. */
859 convert_to_decimal (mpn_t a, size_t extra_zeroes)
861 mp_limb_t *a_ptr = a.limbs;
862 size_t a_len = a.nlimbs;
863 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
864 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
865 /* We need extra_zeroes bytes for zeroes, followed by c_len bytes for the
866 digits of a, followed by 1 byte for the terminating NUL. */
867 char *c_ptr = (char *) malloc (xsum (xsum (extra_zeroes, c_len), 1));
871 for (; extra_zeroes > 0; extra_zeroes--)
875 /* Divide a by 10^9, in-place. */
876 mp_limb_t remainder = 0;
877 mp_limb_t *ptr = a_ptr + a_len;
879 for (count = a_len; count > 0; count--)
882 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
883 *ptr = num / 1000000000;
884 remainder = num % 1000000000;
886 /* Store the remainder as 9 decimal digits. */
887 for (count = 9; count > 0; count--)
889 *d_ptr++ = '0' + (remainder % 10);
890 remainder = remainder / 10;
893 if (a_ptr[a_len - 1] == 0)
896 /* Remove leading zeroes. */
897 while (d_ptr > c_ptr && d_ptr[-1] == '0')
899 /* But keep at least one zero. */
902 /* Terminate the string. */
908 # if NEED_PRINTF_LONG_DOUBLE
910 /* Assuming x is finite and >= 0:
911 write x as x = 2^e * m, where m is a bignum.
912 Return the allocated memory in case of success, NULL in case of memory
913 allocation failure. */
915 decode_long_double (long double x, int *ep, mpn_t *mp)
922 /* Allocate memory for result. */
923 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
924 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
927 /* Split into exponential part and mantissa. */
928 y = frexpl (x, &exp);
929 if (!(y >= 0.0L && y < 1.0L))
931 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the
932 latter is an integer. */
933 /* Convert the mantissa (y * 2^LDBL_MANT_BIT) to a sequence of limbs.
934 I'm not sure whether it's safe to cast a 'long double' value between
935 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
936 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
938 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
939 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
942 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
945 if (!(y >= 0.0L && y < 1.0L))
947 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
950 if (!(y >= 0.0L && y < 1.0L))
952 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
957 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
960 if (!(y >= 0.0L && y < 1.0L))
962 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
966 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
969 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
972 if (!(y >= 0.0L && y < 1.0L))
974 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
977 if (!(y >= 0.0L && y < 1.0L))
979 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
981 # if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
987 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
990 *ep = exp - LDBL_MANT_BIT;
996 # if NEED_PRINTF_DOUBLE
998 /* Assuming x is finite and >= 0:
999 write x as x = 2^e * m, where m is a bignum.
1000 Return the allocated memory in case of success, NULL in case of memory
1001 allocation failure. */
1003 decode_double (double x, int *ep, mpn_t *mp)
1010 /* Allocate memory for result. */
1011 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
1012 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
1013 if (m.limbs == NULL)
1015 /* Split into exponential part and mantissa. */
1016 y = frexp (x, &exp);
1017 if (!(y >= 0.0 && y < 1.0))
1019 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the
1020 latter is an integer. */
1021 /* Convert the mantissa (y * 2^DBL_MANT_BIT) to a sequence of limbs.
1022 I'm not sure whether it's safe to cast a 'double' value between
1023 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1024 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1026 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
1027 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1030 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
1033 if (!(y >= 0.0 && y < 1.0))
1035 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1038 if (!(y >= 0.0 && y < 1.0))
1040 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1045 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
1048 if (!(y >= 0.0 && y < 1.0))
1050 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
1054 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1057 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1060 if (!(y >= 0.0 && y < 1.0))
1062 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1065 if (!(y >= 0.0 && y < 1.0))
1067 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1072 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1075 *ep = exp - DBL_MANT_BIT;
1081 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1082 Returns the decimal representation of round (x * 10^n).
1083 Return the allocated memory - containing the decimal digits in low-to-high
1084 order, terminated with a NUL character - in case of success, NULL in case
1085 of memory allocation failure. */
1087 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1090 size_t extra_zeroes;
1093 mp_limb_t *pow5_ptr;
1095 unsigned int s_limbs;
1096 unsigned int s_bits;
1104 /* x = 2^e * m, hence
1105 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1106 = round (2^s * 5^n * m). */
1109 /* Factor out a common power of 10 if possible. */
1112 extra_zeroes = (s < n ? s : n);
1116 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1117 Before converting to decimal, we need to compute
1118 z = round (2^s * 5^n * m). */
1119 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1120 sign. 2.322 is slightly larger than log(5)/log(2). */
1121 abs_n = (n >= 0 ? n : -n);
1122 abs_s = (s >= 0 ? s : -s);
1123 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1124 + abs_s / GMP_LIMB_BITS + 1)
1125 * sizeof (mp_limb_t));
1126 if (pow5_ptr == NULL)
1131 /* Initialize with 1. */
1134 /* Multiply with 5^|n|. */
1137 static mp_limb_t const small_pow5[13 + 1] =
1139 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1140 48828125, 244140625, 1220703125
1143 for (n13 = 0; n13 <= abs_n; n13 += 13)
1145 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1147 mp_twolimb_t carry = 0;
1148 for (j = 0; j < pow5_len; j++)
1150 mp_limb_t digit2 = pow5_ptr[j];
1151 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1152 pow5_ptr[j] = (mp_limb_t) carry;
1153 carry = carry >> GMP_LIMB_BITS;
1156 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1159 s_limbs = abs_s / GMP_LIMB_BITS;
1160 s_bits = abs_s % GMP_LIMB_BITS;
1161 if (n >= 0 ? s >= 0 : s <= 0)
1163 /* Multiply with 2^|s|. */
1166 mp_limb_t *ptr = pow5_ptr;
1167 mp_twolimb_t accu = 0;
1169 for (count = pow5_len; count > 0; count--)
1171 accu += (mp_twolimb_t) *ptr << s_bits;
1172 *ptr++ = (mp_limb_t) accu;
1173 accu = accu >> GMP_LIMB_BITS;
1177 *ptr = (mp_limb_t) accu;
1184 for (count = pow5_len; count > 0;)
1187 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1189 for (count = s_limbs; count > 0;)
1192 pow5_ptr[count] = 0;
1194 pow5_len += s_limbs;
1196 pow5.limbs = pow5_ptr;
1197 pow5.nlimbs = pow5_len;
1200 /* Multiply m with pow5. No division needed. */
1201 z_memory = multiply (m, pow5, &z);
1205 /* Divide m by pow5 and round. */
1206 z_memory = divide (m, pow5, &z);
1211 pow5.limbs = pow5_ptr;
1212 pow5.nlimbs = pow5_len;
1216 Multiply m with pow5, then divide by 2^|s|. */
1220 tmp_memory = multiply (m, pow5, &numerator);
1221 if (tmp_memory == NULL)
1227 /* Construct 2^|s|. */
1229 mp_limb_t *ptr = pow5_ptr + pow5_len;
1231 for (i = 0; i < s_limbs; i++)
1233 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1234 denominator.limbs = ptr;
1235 denominator.nlimbs = s_limbs + 1;
1237 z_memory = divide (numerator, denominator, &z);
1243 Multiply m with 2^s, then divide by pow5. */
1246 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1247 * sizeof (mp_limb_t));
1248 if (num_ptr == NULL)
1255 mp_limb_t *destptr = num_ptr;
1258 for (i = 0; i < s_limbs; i++)
1263 const mp_limb_t *sourceptr = m.limbs;
1264 mp_twolimb_t accu = 0;
1266 for (count = m.nlimbs; count > 0; count--)
1268 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1269 *destptr++ = (mp_limb_t) accu;
1270 accu = accu >> GMP_LIMB_BITS;
1273 *destptr++ = (mp_limb_t) accu;
1277 const mp_limb_t *sourceptr = m.limbs;
1279 for (count = m.nlimbs; count > 0; count--)
1280 *destptr++ = *sourceptr++;
1282 numerator.limbs = num_ptr;
1283 numerator.nlimbs = destptr - num_ptr;
1285 z_memory = divide (numerator, pow5, &z);
1292 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1294 if (z_memory == NULL)
1296 digits = convert_to_decimal (z, extra_zeroes);
1301 # if NEED_PRINTF_LONG_DOUBLE
1303 /* Assuming x is finite and >= 0, and n is an integer:
1304 Returns the decimal representation of round (x * 10^n).
1305 Return the allocated memory - containing the decimal digits in low-to-high
1306 order, terminated with a NUL character - in case of success, NULL in case
1307 of memory allocation failure. */
1309 scale10_round_decimal_long_double (long double x, int n)
1313 void *memory = decode_long_double (x, &e, &m);
1314 return scale10_round_decimal_decoded (e, m, memory, n);
1319 # if NEED_PRINTF_DOUBLE
1321 /* Assuming x is finite and >= 0, and n is an integer:
1322 Returns the decimal representation of round (x * 10^n).
1323 Return the allocated memory - containing the decimal digits in low-to-high
1324 order, terminated with a NUL character - in case of success, NULL in case
1325 of memory allocation failure. */
1327 scale10_round_decimal_double (double x, int n)
1331 void *memory = decode_double (x, &e, &m);
1332 return scale10_round_decimal_decoded (e, m, memory, n);
1337 # if NEED_PRINTF_LONG_DOUBLE
1339 /* Assuming x is finite and > 0:
1340 Return an approximation for n with 10^n <= x < 10^(n+1).
1341 The approximation is usually the right n, but may be off by 1 sometimes. */
1343 floorlog10l (long double x)
1350 /* Split into exponential part and mantissa. */
1351 y = frexpl (x, &exp);
1352 if (!(y >= 0.0L && y < 1.0L))
1358 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1360 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1361 exp -= GMP_LIMB_BITS;
1363 if (y < (1.0L / (1 << 16)))
1365 y *= 1.0L * (1 << 16);
1368 if (y < (1.0L / (1 << 8)))
1370 y *= 1.0L * (1 << 8);
1373 if (y < (1.0L / (1 << 4)))
1375 y *= 1.0L * (1 << 4);
1378 if (y < (1.0L / (1 << 2)))
1380 y *= 1.0L * (1 << 2);
1383 if (y < (1.0L / (1 << 1)))
1385 y *= 1.0L * (1 << 1);
1389 if (!(y >= 0.5L && y < 1.0L))
1391 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1394 if (z < 0.70710678118654752444)
1396 z *= 1.4142135623730950488;
1399 if (z < 0.8408964152537145431)
1401 z *= 1.1892071150027210667;
1404 if (z < 0.91700404320467123175)
1406 z *= 1.0905077326652576592;
1409 if (z < 0.9576032806985736469)
1411 z *= 1.0442737824274138403;
1414 /* Now 0.95 <= z <= 1.01. */
1416 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1417 Four terms are enough to get an approximation with error < 10^-7. */
1418 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1419 /* Finally multiply with log(2)/log(10), yields an approximation for
1421 l *= 0.30102999566398119523;
1422 /* Round down to the next integer. */
1423 return (int) l + (l < 0 ? -1 : 0);
1428 # if NEED_PRINTF_DOUBLE
1430 /* Assuming x is finite and > 0:
1431 Return an approximation for n with 10^n <= x < 10^(n+1).
1432 The approximation is usually the right n, but may be off by 1 sometimes. */
1434 floorlog10 (double x)
1441 /* Split into exponential part and mantissa. */
1442 y = frexp (x, &exp);
1443 if (!(y >= 0.0 && y < 1.0))
1449 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1451 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1452 exp -= GMP_LIMB_BITS;
1454 if (y < (1.0 / (1 << 16)))
1456 y *= 1.0 * (1 << 16);
1459 if (y < (1.0 / (1 << 8)))
1461 y *= 1.0 * (1 << 8);
1464 if (y < (1.0 / (1 << 4)))
1466 y *= 1.0 * (1 << 4);
1469 if (y < (1.0 / (1 << 2)))
1471 y *= 1.0 * (1 << 2);
1474 if (y < (1.0 / (1 << 1)))
1476 y *= 1.0 * (1 << 1);
1480 if (!(y >= 0.5 && y < 1.0))
1482 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1485 if (z < 0.70710678118654752444)
1487 z *= 1.4142135623730950488;
1490 if (z < 0.8408964152537145431)
1492 z *= 1.1892071150027210667;
1495 if (z < 0.91700404320467123175)
1497 z *= 1.0905077326652576592;
1500 if (z < 0.9576032806985736469)
1502 z *= 1.0442737824274138403;
1505 /* Now 0.95 <= z <= 1.01. */
1507 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1508 Four terms are enough to get an approximation with error < 10^-7. */
1509 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1510 /* Finally multiply with log(2)/log(10), yields an approximation for
1512 l *= 0.30102999566398119523;
1513 /* Round down to the next integer. */
1514 return (int) l + (l < 0 ? -1 : 0);
1519 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1520 a single '1' digit. */
1522 is_borderline (const char *digits, size_t precision)
1524 for (; precision > 0; precision--, digits++)
1530 return *digits == '\0';
1535 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF
1537 /* Use a different function name, to make it possible that the 'wchar_t'
1538 parametrization and the 'char' parametrization get compiled in the same
1539 translation unit. */
1540 # if WIDE_CHAR_VERSION
1541 # define MAX_ROOM_NEEDED wmax_room_needed
1543 # define MAX_ROOM_NEEDED max_room_needed
1546 /* Returns the number of TCHAR_T units needed as temporary space for the result
1547 of sprintf or SNPRINTF of a single conversion directive. */
1549 MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
1550 arg_type type, int flags, size_t width, int has_precision,
1551 size_t precision, int pad_ourselves)
1557 case 'd': case 'i': case 'u':
1559 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1561 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1562 * 0.30103 /* binary -> decimal */
1564 + 1; /* turn floor into ceil */
1567 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1569 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1570 * 0.30103 /* binary -> decimal */
1572 + 1; /* turn floor into ceil */
1575 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1576 * 0.30103 /* binary -> decimal */
1578 + 1; /* turn floor into ceil */
1579 if (tmp_length < precision)
1580 tmp_length = precision;
1581 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1582 tmp_length = xsum (tmp_length, tmp_length);
1583 /* Add 1, to account for a leading sign. */
1584 tmp_length = xsum (tmp_length, 1);
1589 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1591 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1592 * 0.333334 /* binary -> octal */
1594 + 1; /* turn floor into ceil */
1597 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1599 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1600 * 0.333334 /* binary -> octal */
1602 + 1; /* turn floor into ceil */
1605 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1606 * 0.333334 /* binary -> octal */
1608 + 1; /* turn floor into ceil */
1609 if (tmp_length < precision)
1610 tmp_length = precision;
1611 /* Add 1, to account for a leading sign. */
1612 tmp_length = xsum (tmp_length, 1);
1617 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1619 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1620 * 0.25 /* binary -> hexadecimal */
1622 + 1; /* turn floor into ceil */
1625 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1627 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1628 * 0.25 /* binary -> hexadecimal */
1630 + 1; /* turn floor into ceil */
1633 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1634 * 0.25 /* binary -> hexadecimal */
1636 + 1; /* turn floor into ceil */
1637 if (tmp_length < precision)
1638 tmp_length = precision;
1639 /* Add 2, to account for a leading sign or alternate form. */
1640 tmp_length = xsum (tmp_length, 2);
1644 if (type == TYPE_LONGDOUBLE)
1646 (unsigned int) (LDBL_MAX_EXP
1647 * 0.30103 /* binary -> decimal */
1648 * 2 /* estimate for FLAG_GROUP */
1650 + 1 /* turn floor into ceil */
1651 + 10; /* sign, decimal point etc. */
1654 (unsigned int) (DBL_MAX_EXP
1655 * 0.30103 /* binary -> decimal */
1656 * 2 /* estimate for FLAG_GROUP */
1658 + 1 /* turn floor into ceil */
1659 + 10; /* sign, decimal point etc. */
1660 tmp_length = xsum (tmp_length, precision);
1663 case 'e': case 'E': case 'g': case 'G':
1665 12; /* sign, decimal point, exponent etc. */
1666 tmp_length = xsum (tmp_length, precision);
1670 if (type == TYPE_LONGDOUBLE)
1672 (unsigned int) (LDBL_DIG
1673 * 0.831 /* decimal -> hexadecimal */
1675 + 1; /* turn floor into ceil */
1678 (unsigned int) (DBL_DIG
1679 * 0.831 /* decimal -> hexadecimal */
1681 + 1; /* turn floor into ceil */
1682 if (tmp_length < precision)
1683 tmp_length = precision;
1684 /* Account for sign, decimal point etc. */
1685 tmp_length = xsum (tmp_length, 12);
1689 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
1690 if (type == TYPE_WIDE_CHAR)
1691 tmp_length = MB_CUR_MAX;
1699 if (type == TYPE_WIDE_STRING)
1701 # if WIDE_CHAR_VERSION
1702 /* ISO C says about %ls in fwprintf:
1703 "If the precision is not specified or is greater than the size
1704 of the array, the array shall contain a null wide character."
1705 So if there is a precision, we must not use wcslen. */
1706 const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
1709 tmp_length = local_wcsnlen (arg, precision);
1711 tmp_length = local_wcslen (arg);
1713 /* ISO C says about %ls in fprintf:
1714 "If a precision is specified, no more than that many bytes are
1715 written (including shift sequences, if any), and the array
1716 shall contain a null wide character if, to equal the multibyte
1717 character sequence length given by the precision, the function
1718 would need to access a wide character one past the end of the
1720 So if there is a precision, we must not use wcslen. */
1721 /* This case has already been handled separately in VASNPRINTF. */
1728 # if WIDE_CHAR_VERSION
1729 /* ISO C says about %s in fwprintf:
1730 "If the precision is not specified or is greater than the size
1731 of the converted array, the converted array shall contain a
1732 null wide character."
1733 So if there is a precision, we must not use strlen. */
1734 /* This case has already been handled separately in VASNPRINTF. */
1737 /* ISO C says about %s in fprintf:
1738 "If the precision is not specified or greater than the size of
1739 the array, the array shall contain a null character."
1740 So if there is a precision, we must not use strlen. */
1741 const char *arg = ap->arg[arg_index].a.a_string;
1744 tmp_length = local_strnlen (arg, precision);
1746 tmp_length = strlen (arg);
1753 (unsigned int) (sizeof (void *) * CHAR_BIT
1754 * 0.25 /* binary -> hexadecimal */
1756 + 1 /* turn floor into ceil */
1757 + 2; /* account for leading 0x */
1766 # if ENABLE_UNISTDIO
1767 /* Padding considers the number of characters, therefore the number of
1768 elements after padding may be
1769 > max (tmp_length, width)
1771 <= tmp_length + width. */
1772 tmp_length = xsum (tmp_length, width);
1774 /* Padding considers the number of elements, says POSIX. */
1775 if (tmp_length < width)
1780 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1788 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1789 const FCHAR_T *format, va_list args)
1794 if (PRINTF_PARSE (format, &d, &a) < 0)
1795 /* errno is already set. */
1799 if (d.dir != d.direct_alloc_dir) \
1801 if (a.arg != a.direct_alloc_arg) \
1804 if (PRINTF_FETCHARGS (args, &a) < 0)
1812 size_t buf_neededlength;
1814 TCHAR_T *buf_malloced;
1818 /* Output string accumulator. */
1823 /* Allocate a small buffer that will hold a directive passed to
1824 sprintf or snprintf. */
1826 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1828 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1830 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1831 buf_malloced = NULL;
1836 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1837 if (size_overflow_p (buf_memsize))
1838 goto out_of_memory_1;
1839 buf = (TCHAR_T *) malloc (buf_memsize);
1841 goto out_of_memory_1;
1845 if (resultbuf != NULL)
1848 allocated = *lengthp;
1857 result is either == resultbuf or == NULL or malloc-allocated.
1858 If length > 0, then result != NULL. */
1860 /* Ensures that allocated >= needed. Aborts through a jump to
1861 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1862 #define ENSURE_ALLOCATION(needed) \
1863 if ((needed) > allocated) \
1865 size_t memory_size; \
1868 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1869 if ((needed) > allocated) \
1870 allocated = (needed); \
1871 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1872 if (size_overflow_p (memory_size)) \
1873 goto out_of_memory; \
1874 if (result == resultbuf || result == NULL) \
1875 memory = (DCHAR_T *) malloc (memory_size); \
1877 memory = (DCHAR_T *) realloc (result, memory_size); \
1878 if (memory == NULL) \
1879 goto out_of_memory; \
1880 if (result == resultbuf && length > 0) \
1881 DCHAR_CPY (memory, result, length); \
1885 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1887 if (cp != dp->dir_start)
1889 size_t n = dp->dir_start - cp;
1890 size_t augmented_length = xsum (length, n);
1892 ENSURE_ALLOCATION (augmented_length);
1893 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1894 need that the format string contains only ASCII characters
1895 if FCHAR_T and DCHAR_T are not the same type. */
1896 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1898 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1899 length = augmented_length;
1904 result[length++] = *cp++;
1911 /* Execute a single directive. */
1912 if (dp->conversion == '%')
1914 size_t augmented_length;
1916 if (!(dp->arg_index == ARG_NONE))
1918 augmented_length = xsum (length, 1);
1919 ENSURE_ALLOCATION (augmented_length);
1920 result[length] = '%';
1921 length = augmented_length;
1925 if (!(dp->arg_index != ARG_NONE))
1928 if (dp->conversion == 'n')
1930 switch (a.arg[dp->arg_index].type)
1932 case TYPE_COUNT_SCHAR_POINTER:
1933 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1935 case TYPE_COUNT_SHORT_POINTER:
1936 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1938 case TYPE_COUNT_INT_POINTER:
1939 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1941 case TYPE_COUNT_LONGINT_POINTER:
1942 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1945 case TYPE_COUNT_LONGLONGINT_POINTER:
1946 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1954 /* The unistdio extensions. */
1955 else if (dp->conversion == 'U')
1957 arg_type type = a.arg[dp->arg_index].type;
1958 int flags = dp->flags;
1966 if (dp->width_start != dp->width_end)
1968 if (dp->width_arg_index != ARG_NONE)
1972 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1974 arg = a.arg[dp->width_arg_index].a.a_int;
1978 /* "A negative field width is taken as a '-' flag
1979 followed by a positive field width." */
1986 const FCHAR_T *digitp = dp->width_start;
1989 width = xsum (xtimes (width, 10), *digitp++ - '0');
1990 while (digitp != dp->width_end);
1997 if (dp->precision_start != dp->precision_end)
1999 if (dp->precision_arg_index != ARG_NONE)
2003 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2005 arg = a.arg[dp->precision_arg_index].a.a_int;
2006 /* "A negative precision is taken as if the precision
2016 const FCHAR_T *digitp = dp->precision_start + 1;
2019 while (digitp != dp->precision_end)
2020 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2027 case TYPE_U8_STRING:
2029 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
2030 const uint8_t *arg_end;
2035 /* Use only PRECISION characters, from the left. */
2038 for (; precision > 0; precision--)
2040 int count = u8_strmblen (arg_end);
2045 if (!(result == resultbuf || result == NULL))
2047 if (buf_malloced != NULL)
2048 free (buf_malloced);
2059 /* Use the entire string, and count the number of
2065 int count = u8_strmblen (arg_end);
2070 if (!(result == resultbuf || result == NULL))
2072 if (buf_malloced != NULL)
2073 free (buf_malloced);
2084 /* Use the entire string. */
2085 arg_end = arg + u8_strlen (arg);
2086 /* The number of characters doesn't matter. */
2090 if (characters < width && !(dp->flags & FLAG_LEFT))
2092 size_t n = width - characters;
2093 ENSURE_ALLOCATION (xsum (length, n));
2094 DCHAR_SET (result + length, ' ', n);
2098 # if DCHAR_IS_UINT8_T
2100 size_t n = arg_end - arg;
2101 ENSURE_ALLOCATION (xsum (length, n));
2102 DCHAR_CPY (result + length, arg, n);
2107 DCHAR_T *converted = result + length;
2108 size_t converted_len = allocated - length;
2110 /* Convert from UTF-8 to locale encoding. */
2112 u8_conv_to_encoding (locale_charset (),
2113 iconveh_question_mark,
2114 arg, arg_end - arg, NULL,
2115 converted, &converted_len);
2117 /* Convert from UTF-8 to UTF-16/UTF-32. */
2119 U8_TO_DCHAR (arg, arg_end - arg,
2120 converted, &converted_len);
2122 if (converted == NULL)
2124 int saved_errno = errno;
2125 if (!(result == resultbuf || result == NULL))
2127 if (buf_malloced != NULL)
2128 free (buf_malloced);
2130 errno = saved_errno;
2133 if (converted != result + length)
2135 ENSURE_ALLOCATION (xsum (length, converted_len));
2136 DCHAR_CPY (result + length, converted, converted_len);
2139 length += converted_len;
2143 if (characters < width && (dp->flags & FLAG_LEFT))
2145 size_t n = width - characters;
2146 ENSURE_ALLOCATION (xsum (length, n));
2147 DCHAR_SET (result + length, ' ', n);
2153 case TYPE_U16_STRING:
2155 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
2156 const uint16_t *arg_end;
2161 /* Use only PRECISION characters, from the left. */
2164 for (; precision > 0; precision--)
2166 int count = u16_strmblen (arg_end);
2171 if (!(result == resultbuf || result == NULL))
2173 if (buf_malloced != NULL)
2174 free (buf_malloced);
2185 /* Use the entire string, and count the number of
2191 int count = u16_strmblen (arg_end);
2196 if (!(result == resultbuf || result == NULL))
2198 if (buf_malloced != NULL)
2199 free (buf_malloced);
2210 /* Use the entire string. */
2211 arg_end = arg + u16_strlen (arg);
2212 /* The number of characters doesn't matter. */
2216 if (characters < width && !(dp->flags & FLAG_LEFT))
2218 size_t n = width - characters;
2219 ENSURE_ALLOCATION (xsum (length, n));
2220 DCHAR_SET (result + length, ' ', n);
2224 # if DCHAR_IS_UINT16_T
2226 size_t n = arg_end - arg;
2227 ENSURE_ALLOCATION (xsum (length, n));
2228 DCHAR_CPY (result + length, arg, n);
2233 DCHAR_T *converted = result + length;
2234 size_t converted_len = allocated - length;
2236 /* Convert from UTF-16 to locale encoding. */
2238 u16_conv_to_encoding (locale_charset (),
2239 iconveh_question_mark,
2240 arg, arg_end - arg, NULL,
2241 converted, &converted_len);
2243 /* Convert from UTF-16 to UTF-8/UTF-32. */
2245 U16_TO_DCHAR (arg, arg_end - arg,
2246 converted, &converted_len);
2248 if (converted == NULL)
2250 int saved_errno = errno;
2251 if (!(result == resultbuf || result == NULL))
2253 if (buf_malloced != NULL)
2254 free (buf_malloced);
2256 errno = saved_errno;
2259 if (converted != result + length)
2261 ENSURE_ALLOCATION (xsum (length, converted_len));
2262 DCHAR_CPY (result + length, converted, converted_len);
2265 length += converted_len;
2269 if (characters < width && (dp->flags & FLAG_LEFT))
2271 size_t n = width - characters;
2272 ENSURE_ALLOCATION (xsum (length, n));
2273 DCHAR_SET (result + length, ' ', n);
2279 case TYPE_U32_STRING:
2281 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
2282 const uint32_t *arg_end;
2287 /* Use only PRECISION characters, from the left. */
2290 for (; precision > 0; precision--)
2292 int count = u32_strmblen (arg_end);
2297 if (!(result == resultbuf || result == NULL))
2299 if (buf_malloced != NULL)
2300 free (buf_malloced);
2311 /* Use the entire string, and count the number of
2317 int count = u32_strmblen (arg_end);
2322 if (!(result == resultbuf || result == NULL))
2324 if (buf_malloced != NULL)
2325 free (buf_malloced);
2336 /* Use the entire string. */
2337 arg_end = arg + u32_strlen (arg);
2338 /* The number of characters doesn't matter. */
2342 if (characters < width && !(dp->flags & FLAG_LEFT))
2344 size_t n = width - characters;
2345 ENSURE_ALLOCATION (xsum (length, n));
2346 DCHAR_SET (result + length, ' ', n);
2350 # if DCHAR_IS_UINT32_T
2352 size_t n = arg_end - arg;
2353 ENSURE_ALLOCATION (xsum (length, n));
2354 DCHAR_CPY (result + length, arg, n);
2359 DCHAR_T *converted = result + length;
2360 size_t converted_len = allocated - length;
2362 /* Convert from UTF-32 to locale encoding. */
2364 u32_conv_to_encoding (locale_charset (),
2365 iconveh_question_mark,
2366 arg, arg_end - arg, NULL,
2367 converted, &converted_len);
2369 /* Convert from UTF-32 to UTF-8/UTF-16. */
2371 U32_TO_DCHAR (arg, arg_end - arg,
2372 converted, &converted_len);
2374 if (converted == NULL)
2376 int saved_errno = errno;
2377 if (!(result == resultbuf || result == NULL))
2379 if (buf_malloced != NULL)
2380 free (buf_malloced);
2382 errno = saved_errno;
2385 if (converted != result + length)
2387 ENSURE_ALLOCATION (xsum (length, converted_len));
2388 DCHAR_CPY (result + length, converted, converted_len);
2391 length += converted_len;
2395 if (characters < width && (dp->flags & FLAG_LEFT))
2397 size_t n = width - characters;
2398 ENSURE_ALLOCATION (xsum (length, n));
2399 DCHAR_SET (result + length, ' ', n);
2410 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T
2411 else if (dp->conversion == 's'
2412 # if WIDE_CHAR_VERSION
2413 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2415 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2419 /* The normal handling of the 's' directive below requires
2420 allocating a temporary buffer. The determination of its
2421 length (tmp_length), in the case when a precision is
2422 specified, below requires a conversion between a char[]
2423 string and a wchar_t[] wide string. It could be done, but
2424 we have no guarantee that the implementation of sprintf will
2425 use the exactly same algorithm. Without this guarantee, it
2426 is possible to have buffer overrun bugs. In order to avoid
2427 such bugs, we implement the entire processing of the 's'
2428 directive ourselves. */
2429 int flags = dp->flags;
2437 if (dp->width_start != dp->width_end)
2439 if (dp->width_arg_index != ARG_NONE)
2443 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2445 arg = a.arg[dp->width_arg_index].a.a_int;
2449 /* "A negative field width is taken as a '-' flag
2450 followed by a positive field width." */
2457 const FCHAR_T *digitp = dp->width_start;
2460 width = xsum (xtimes (width, 10), *digitp++ - '0');
2461 while (digitp != dp->width_end);
2468 if (dp->precision_start != dp->precision_end)
2470 if (dp->precision_arg_index != ARG_NONE)
2474 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2476 arg = a.arg[dp->precision_arg_index].a.a_int;
2477 /* "A negative precision is taken as if the precision
2487 const FCHAR_T *digitp = dp->precision_start + 1;
2490 while (digitp != dp->precision_end)
2491 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2496 # if WIDE_CHAR_VERSION
2497 /* %s in vasnwprintf. See the specification of fwprintf. */
2499 const char *arg = a.arg[dp->arg_index].a.a_string;
2500 const char *arg_end;
2505 /* Use only as many bytes as needed to produce PRECISION
2506 wide characters, from the left. */
2509 memset (&state, '\0', sizeof (mbstate_t));
2513 for (; precision > 0; precision--)
2517 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2519 count = mblen (arg_end, MB_CUR_MAX);
2522 /* Found the terminating NUL. */
2526 /* Invalid or incomplete multibyte character. */
2527 if (!(result == resultbuf || result == NULL))
2529 if (buf_malloced != NULL)
2530 free (buf_malloced);
2541 /* Use the entire string, and count the number of wide
2545 memset (&state, '\0', sizeof (mbstate_t));
2553 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2555 count = mblen (arg_end, MB_CUR_MAX);
2558 /* Found the terminating NUL. */
2562 /* Invalid or incomplete multibyte character. */
2563 if (!(result == resultbuf || result == NULL))
2565 if (buf_malloced != NULL)
2566 free (buf_malloced);
2577 /* Use the entire string. */
2578 arg_end = arg + strlen (arg);
2579 /* The number of characters doesn't matter. */
2583 if (characters < width && !(dp->flags & FLAG_LEFT))
2585 size_t n = width - characters;
2586 ENSURE_ALLOCATION (xsum (length, n));
2587 DCHAR_SET (result + length, ' ', n);
2591 if (has_precision || has_width)
2593 /* We know the number of wide characters in advance. */
2597 memset (&state, '\0', sizeof (mbstate_t));
2599 ENSURE_ALLOCATION (xsum (length, characters));
2600 for (remaining = characters; remaining > 0; remaining--)
2605 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2607 count = mbtowc (&wc, arg, arg_end - arg);
2610 /* mbrtowc not consistent with mbrlen, or mbtowc
2611 not consistent with mblen. */
2613 result[length++] = wc;
2616 if (!(arg == arg_end))
2623 memset (&state, '\0', sizeof (mbstate_t));
2625 while (arg < arg_end)
2630 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2632 count = mbtowc (&wc, arg, arg_end - arg);
2635 /* mbrtowc not consistent with mbrlen, or mbtowc
2636 not consistent with mblen. */
2638 ENSURE_ALLOCATION (xsum (length, 1));
2639 result[length++] = wc;
2644 if (characters < width && (dp->flags & FLAG_LEFT))
2646 size_t n = width - characters;
2647 ENSURE_ALLOCATION (xsum (length, n));
2648 DCHAR_SET (result + length, ' ', n);
2653 /* %ls in vasnprintf. See the specification of fprintf. */
2655 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2656 const wchar_t *arg_end;
2658 # if !DCHAR_IS_TCHAR
2659 /* This code assumes that TCHAR_T is 'char'. */
2660 verify (sizeof (TCHAR_T) == 1);
2669 /* Use only as many wide characters as needed to produce
2670 at most PRECISION bytes, from the left. */
2671 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2673 memset (&state, '\0', sizeof (mbstate_t));
2677 while (precision > 0)
2679 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2683 /* Found the terminating null wide character. */
2685 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2686 count = wcrtomb (cbuf, *arg_end, &state);
2688 count = wctomb (cbuf, *arg_end);
2692 /* Cannot convert. */
2693 if (!(result == resultbuf || result == NULL))
2695 if (buf_malloced != NULL)
2696 free (buf_malloced);
2701 if (precision < (unsigned int) count)
2704 characters += count;
2714 /* Use the entire string, and count the number of
2716 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2718 memset (&state, '\0', sizeof (mbstate_t));
2724 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2728 /* Found the terminating null wide character. */
2730 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2731 count = wcrtomb (cbuf, *arg_end, &state);
2733 count = wctomb (cbuf, *arg_end);
2737 /* Cannot convert. */
2738 if (!(result == resultbuf || result == NULL))
2740 if (buf_malloced != NULL)
2741 free (buf_malloced);
2747 characters += count;
2753 /* Use the entire string. */
2754 arg_end = arg + local_wcslen (arg);
2755 /* The number of bytes doesn't matter. */
2760 # if !DCHAR_IS_TCHAR
2761 /* Convert the string into a piece of temporary memory. */
2762 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2766 TCHAR_T *tmpptr = tmpsrc;
2768 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2770 memset (&state, '\0', sizeof (mbstate_t));
2772 for (remaining = characters; remaining > 0; )
2774 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2779 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2780 count = wcrtomb (cbuf, *arg, &state);
2782 count = wctomb (cbuf, *arg);
2785 /* Inconsistency. */
2787 memcpy (tmpptr, cbuf, count);
2792 if (!(arg == arg_end))
2796 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2798 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2799 iconveh_question_mark,
2805 int saved_errno = errno;
2807 if (!(result == resultbuf || result == NULL))
2809 if (buf_malloced != NULL)
2810 free (buf_malloced);
2812 errno = saved_errno;
2820 # if ENABLE_UNISTDIO
2821 /* Outside POSIX, it's preferable to compare the width
2822 against the number of _characters_ of the converted
2824 w = DCHAR_MBSNLEN (result + length, characters);
2826 /* The width is compared against the number of _bytes_
2827 of the converted value, says POSIX. */
2832 /* w doesn't matter. */
2835 if (w < width && !(dp->flags & FLAG_LEFT))
2837 size_t n = width - w;
2838 ENSURE_ALLOCATION (xsum (length, n));
2839 DCHAR_SET (result + length, ' ', n);
2844 if (has_precision || has_width)
2846 /* We know the number of bytes in advance. */
2848 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2850 memset (&state, '\0', sizeof (mbstate_t));
2852 ENSURE_ALLOCATION (xsum (length, characters));
2853 for (remaining = characters; remaining > 0; )
2855 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2860 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2861 count = wcrtomb (cbuf, *arg, &state);
2863 count = wctomb (cbuf, *arg);
2866 /* Inconsistency. */
2868 memcpy (result + length, cbuf, count);
2873 if (!(arg == arg_end))
2878 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2880 memset (&state, '\0', sizeof (mbstate_t));
2882 while (arg < arg_end)
2884 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2889 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2890 count = wcrtomb (cbuf, *arg, &state);
2892 count = wctomb (cbuf, *arg);
2896 /* Cannot convert. */
2897 if (!(result == resultbuf || result == NULL))
2899 if (buf_malloced != NULL)
2900 free (buf_malloced);
2905 ENSURE_ALLOCATION (xsum (length, count));
2906 memcpy (result + length, cbuf, count);
2912 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2913 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2915 length += tmpdst_len;
2918 if (w < width && (dp->flags & FLAG_LEFT))
2920 size_t n = width - w;
2921 ENSURE_ALLOCATION (xsum (length, n));
2922 DCHAR_SET (result + length, ' ', n);
2929 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2930 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2931 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2933 # if NEED_PRINTF_DOUBLE
2934 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2936 # if NEED_PRINTF_LONG_DOUBLE
2937 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2943 arg_type type = a.arg[dp->arg_index].type;
2944 int flags = dp->flags;
2950 DCHAR_T tmpbuf[700];
2956 if (dp->width_start != dp->width_end)
2958 if (dp->width_arg_index != ARG_NONE)
2962 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2964 arg = a.arg[dp->width_arg_index].a.a_int;
2968 /* "A negative field width is taken as a '-' flag
2969 followed by a positive field width." */
2976 const FCHAR_T *digitp = dp->width_start;
2979 width = xsum (xtimes (width, 10), *digitp++ - '0');
2980 while (digitp != dp->width_end);
2986 if (dp->precision_start != dp->precision_end)
2988 if (dp->precision_arg_index != ARG_NONE)
2992 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2994 arg = a.arg[dp->precision_arg_index].a.a_int;
2995 /* "A negative precision is taken as if the precision
3005 const FCHAR_T *digitp = dp->precision_start + 1;
3008 while (digitp != dp->precision_end)
3009 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3014 /* Allocate a temporary buffer of sufficient size. */
3015 if (type == TYPE_LONGDOUBLE)
3017 (unsigned int) ((LDBL_DIG + 1)
3018 * 0.831 /* decimal -> hexadecimal */
3020 + 1; /* turn floor into ceil */
3023 (unsigned int) ((DBL_DIG + 1)
3024 * 0.831 /* decimal -> hexadecimal */
3026 + 1; /* turn floor into ceil */
3027 if (tmp_length < precision)
3028 tmp_length = precision;
3029 /* Account for sign, decimal point etc. */
3030 tmp_length = xsum (tmp_length, 12);
3032 if (tmp_length < width)
3035 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3037 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3041 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3043 if (size_overflow_p (tmp_memsize))
3044 /* Overflow, would lead to out of memory. */
3046 tmp = (DCHAR_T *) malloc (tmp_memsize);
3048 /* Out of memory. */
3054 if (type == TYPE_LONGDOUBLE)
3056 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
3057 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3061 if (dp->conversion == 'A')
3063 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3067 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3073 DECL_LONG_DOUBLE_ROUNDING
3075 BEGIN_LONG_DOUBLE_ROUNDING ();
3077 if (signbit (arg)) /* arg < 0.0L or negative zero */
3085 else if (flags & FLAG_SHOWSIGN)
3087 else if (flags & FLAG_SPACE)
3090 if (arg > 0.0L && arg + arg == arg)
3092 if (dp->conversion == 'A')
3094 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3098 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3104 long double mantissa;
3107 mantissa = printf_frexpl (arg, &exponent);
3115 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
3117 /* Round the mantissa. */
3118 long double tail = mantissa;
3121 for (q = precision; ; q--)
3123 int digit = (int) tail;
3127 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
3136 for (q = precision; q > 0; q--)
3142 *p++ = dp->conversion - 'A' + 'X';
3147 digit = (int) mantissa;
3150 if ((flags & FLAG_ALT)
3151 || mantissa > 0.0L || precision > 0)
3153 *p++ = decimal_point_char ();
3154 /* This loop terminates because we assume
3155 that FLT_RADIX is a power of 2. */
3156 while (mantissa > 0.0L)
3159 digit = (int) mantissa;
3164 : dp->conversion - 10);
3168 while (precision > 0)
3175 *p++ = dp->conversion - 'A' + 'P';
3176 # if WIDE_CHAR_VERSION
3178 static const wchar_t decimal_format[] =
3179 { '%', '+', 'd', '\0' };
3180 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3185 if (sizeof (DCHAR_T) == 1)
3187 sprintf ((char *) p, "%+d", exponent);
3195 sprintf (expbuf, "%+d", exponent);
3196 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3202 END_LONG_DOUBLE_ROUNDING ();
3210 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
3211 double arg = a.arg[dp->arg_index].a.a_double;
3215 if (dp->conversion == 'A')
3217 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3221 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3228 if (signbit (arg)) /* arg < 0.0 or negative zero */
3236 else if (flags & FLAG_SHOWSIGN)
3238 else if (flags & FLAG_SPACE)
3241 if (arg > 0.0 && arg + arg == arg)
3243 if (dp->conversion == 'A')
3245 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3249 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3258 mantissa = printf_frexp (arg, &exponent);
3266 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
3268 /* Round the mantissa. */
3269 double tail = mantissa;
3272 for (q = precision; ; q--)
3274 int digit = (int) tail;
3278 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
3287 for (q = precision; q > 0; q--)
3293 *p++ = dp->conversion - 'A' + 'X';
3298 digit = (int) mantissa;
3301 if ((flags & FLAG_ALT)
3302 || mantissa > 0.0 || precision > 0)
3304 *p++ = decimal_point_char ();
3305 /* This loop terminates because we assume
3306 that FLT_RADIX is a power of 2. */
3307 while (mantissa > 0.0)
3310 digit = (int) mantissa;
3315 : dp->conversion - 10);
3319 while (precision > 0)
3326 *p++ = dp->conversion - 'A' + 'P';
3327 # if WIDE_CHAR_VERSION
3329 static const wchar_t decimal_format[] =
3330 { '%', '+', 'd', '\0' };
3331 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3336 if (sizeof (DCHAR_T) == 1)
3338 sprintf ((char *) p, "%+d", exponent);
3346 sprintf (expbuf, "%+d", exponent);
3347 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3358 /* The generated string now extends from tmp to p, with the
3359 zero padding insertion point being at pad_ptr. */
3364 size_t pad = width - count;
3365 DCHAR_T *end = p + pad;
3367 if (flags & FLAG_LEFT)
3369 /* Pad with spaces on the right. */
3370 for (; pad > 0; pad--)
3373 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3375 /* Pad with zeroes. */
3380 for (; pad > 0; pad--)
3385 /* Pad with spaces on the left. */
3390 for (; pad > 0; pad--)
3399 if (count >= tmp_length)
3400 /* tmp_length was incorrectly calculated - fix the
3404 /* Make room for the result. */
3405 if (count >= allocated - length)
3407 size_t n = xsum (length, count);
3409 ENSURE_ALLOCATION (n);
3412 /* Append the result. */
3413 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3419 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3420 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3421 || dp->conversion == 'e' || dp->conversion == 'E'
3422 || dp->conversion == 'g' || dp->conversion == 'G'
3423 || dp->conversion == 'a' || dp->conversion == 'A')
3425 # if NEED_PRINTF_DOUBLE
3426 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3427 # elif NEED_PRINTF_INFINITE_DOUBLE
3428 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3429 /* The systems (mingw) which produce wrong output
3430 for Inf, -Inf, and NaN also do so for -0.0.
3431 Therefore we treat this case here as well. */
3432 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3434 # if NEED_PRINTF_LONG_DOUBLE
3435 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3436 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3437 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3438 /* Some systems produce wrong output for Inf,
3439 -Inf, and NaN. Some systems in this category
3440 (IRIX 5.3) also do so for -0.0. Therefore we
3441 treat this case here as well. */
3442 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3446 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3447 arg_type type = a.arg[dp->arg_index].type;
3449 int flags = dp->flags;
3455 DCHAR_T tmpbuf[700];
3461 if (dp->width_start != dp->width_end)
3463 if (dp->width_arg_index != ARG_NONE)
3467 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3469 arg = a.arg[dp->width_arg_index].a.a_int;
3473 /* "A negative field width is taken as a '-' flag
3474 followed by a positive field width." */
3481 const FCHAR_T *digitp = dp->width_start;
3484 width = xsum (xtimes (width, 10), *digitp++ - '0');
3485 while (digitp != dp->width_end);
3491 if (dp->precision_start != dp->precision_end)
3493 if (dp->precision_arg_index != ARG_NONE)
3497 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3499 arg = a.arg[dp->precision_arg_index].a.a_int;
3500 /* "A negative precision is taken as if the precision
3510 const FCHAR_T *digitp = dp->precision_start + 1;
3513 while (digitp != dp->precision_end)
3514 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3519 /* POSIX specifies the default precision to be 6 for %f, %F,
3520 %e, %E, but not for %g, %G. Implementations appear to use
3521 the same default precision also for %g, %G. But for %a, %A,
3522 the default precision is 0. */
3524 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3527 /* Allocate a temporary buffer of sufficient size. */
3528 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3529 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3530 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3531 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3532 # elif NEED_PRINTF_LONG_DOUBLE
3533 tmp_length = LDBL_DIG + 1;
3534 # elif NEED_PRINTF_DOUBLE
3535 tmp_length = DBL_DIG + 1;
3539 if (tmp_length < precision)
3540 tmp_length = precision;
3541 # if NEED_PRINTF_LONG_DOUBLE
3542 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3543 if (type == TYPE_LONGDOUBLE)
3545 if (dp->conversion == 'f' || dp->conversion == 'F')
3547 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3548 if (!(isnanl (arg) || arg + arg == arg))
3550 /* arg is finite and nonzero. */
3551 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3552 if (exponent >= 0 && tmp_length < exponent + precision)
3553 tmp_length = exponent + precision;
3557 # if NEED_PRINTF_DOUBLE
3558 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3559 if (type == TYPE_DOUBLE)
3561 if (dp->conversion == 'f' || dp->conversion == 'F')
3563 double arg = a.arg[dp->arg_index].a.a_double;
3564 if (!(isnand (arg) || arg + arg == arg))
3566 /* arg is finite and nonzero. */
3567 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3568 if (exponent >= 0 && tmp_length < exponent + precision)
3569 tmp_length = exponent + precision;
3573 /* Account for sign, decimal point etc. */
3574 tmp_length = xsum (tmp_length, 12);
3576 if (tmp_length < width)
3579 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3581 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3585 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3587 if (size_overflow_p (tmp_memsize))
3588 /* Overflow, would lead to out of memory. */
3590 tmp = (DCHAR_T *) malloc (tmp_memsize);
3592 /* Out of memory. */
3599 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3600 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3601 if (type == TYPE_LONGDOUBLE)
3604 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3608 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3610 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3614 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3620 DECL_LONG_DOUBLE_ROUNDING
3622 BEGIN_LONG_DOUBLE_ROUNDING ();
3624 if (signbit (arg)) /* arg < 0.0L or negative zero */
3632 else if (flags & FLAG_SHOWSIGN)
3634 else if (flags & FLAG_SPACE)
3637 if (arg > 0.0L && arg + arg == arg)
3639 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3641 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3645 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3650 # if NEED_PRINTF_LONG_DOUBLE
3653 if (dp->conversion == 'f' || dp->conversion == 'F')
3659 scale10_round_decimal_long_double (arg, precision);
3662 END_LONG_DOUBLE_ROUNDING ();
3665 ndigits = strlen (digits);
3667 if (ndigits > precision)
3671 *p++ = digits[ndigits];
3673 while (ndigits > precision);
3676 /* Here ndigits <= precision. */
3677 if ((flags & FLAG_ALT) || precision > 0)
3679 *p++ = decimal_point_char ();
3680 for (; precision > ndigits; precision--)
3685 *p++ = digits[ndigits];
3691 else if (dp->conversion == 'e' || dp->conversion == 'E')
3699 if ((flags & FLAG_ALT) || precision > 0)
3701 *p++ = decimal_point_char ();
3702 for (; precision > 0; precision--)
3713 exponent = floorlog10l (arg);
3718 scale10_round_decimal_long_double (arg,
3719 (int)precision - exponent);
3722 END_LONG_DOUBLE_ROUNDING ();
3725 ndigits = strlen (digits);
3727 if (ndigits == precision + 1)
3729 if (ndigits < precision
3730 || ndigits > precision + 2)
3731 /* The exponent was not guessed
3732 precisely enough. */
3735 /* None of two values of exponent is
3736 the right one. Prevent an endless
3740 if (ndigits == precision)
3746 /* Here ndigits = precision+1. */
3747 if (is_borderline (digits, precision))
3749 /* Maybe the exponent guess was too high
3750 and a smaller exponent can be reached
3751 by turning a 10...0 into 9...9x. */
3753 scale10_round_decimal_long_double (arg,
3754 (int)precision - exponent + 1);
3755 if (digits2 == NULL)
3758 END_LONG_DOUBLE_ROUNDING ();
3761 if (strlen (digits2) == precision + 1)
3770 /* Here ndigits = precision+1. */
3772 *p++ = digits[--ndigits];
3773 if ((flags & FLAG_ALT) || precision > 0)
3775 *p++ = decimal_point_char ();
3779 *p++ = digits[ndigits];
3786 *p++ = dp->conversion; /* 'e' or 'E' */
3787 # if WIDE_CHAR_VERSION
3789 static const wchar_t decimal_format[] =
3790 { '%', '+', '.', '2', 'd', '\0' };
3791 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3796 if (sizeof (DCHAR_T) == 1)
3798 sprintf ((char *) p, "%+.2d", exponent);
3806 sprintf (expbuf, "%+.2d", exponent);
3807 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3812 else if (dp->conversion == 'g' || dp->conversion == 'G')
3816 /* precision >= 1. */
3819 /* The exponent is 0, >= -4, < precision.
3820 Use fixed-point notation. */
3822 size_t ndigits = precision;
3823 /* Number of trailing zeroes that have to be
3826 (flags & FLAG_ALT ? 0 : precision - 1);
3830 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3832 *p++ = decimal_point_char ();
3833 while (ndigits > nzeroes)
3849 exponent = floorlog10l (arg);
3854 scale10_round_decimal_long_double (arg,
3855 (int)(precision - 1) - exponent);
3858 END_LONG_DOUBLE_ROUNDING ();
3861 ndigits = strlen (digits);
3863 if (ndigits == precision)
3865 if (ndigits < precision - 1
3866 || ndigits > precision + 1)
3867 /* The exponent was not guessed
3868 precisely enough. */
3871 /* None of two values of exponent is
3872 the right one. Prevent an endless
3876 if (ndigits < precision)
3882 /* Here ndigits = precision. */
3883 if (is_borderline (digits, precision - 1))
3885 /* Maybe the exponent guess was too high
3886 and a smaller exponent can be reached
3887 by turning a 10...0 into 9...9x. */
3889 scale10_round_decimal_long_double (arg,
3890 (int)(precision - 1) - exponent + 1);
3891 if (digits2 == NULL)
3894 END_LONG_DOUBLE_ROUNDING ();
3897 if (strlen (digits2) == precision)
3906 /* Here ndigits = precision. */
3908 /* Determine the number of trailing zeroes
3909 that have to be dropped. */
3911 if ((flags & FLAG_ALT) == 0)
3912 while (nzeroes < ndigits
3913 && digits[nzeroes] == '0')
3916 /* The exponent is now determined. */
3918 && exponent < (long)precision)
3920 /* Fixed-point notation:
3921 max(exponent,0)+1 digits, then the
3922 decimal point, then the remaining
3923 digits without trailing zeroes. */
3926 size_t ecount = exponent + 1;
3927 /* Note: count <= precision = ndigits. */
3928 for (; ecount > 0; ecount--)
3929 *p++ = digits[--ndigits];
3930 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3932 *p++ = decimal_point_char ();
3933 while (ndigits > nzeroes)
3936 *p++ = digits[ndigits];
3942 size_t ecount = -exponent - 1;
3944 *p++ = decimal_point_char ();
3945 for (; ecount > 0; ecount--)
3947 while (ndigits > nzeroes)
3950 *p++ = digits[ndigits];
3956 /* Exponential notation. */
3957 *p++ = digits[--ndigits];
3958 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3960 *p++ = decimal_point_char ();
3961 while (ndigits > nzeroes)
3964 *p++ = digits[ndigits];
3967 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3968 # if WIDE_CHAR_VERSION
3970 static const wchar_t decimal_format[] =
3971 { '%', '+', '.', '2', 'd', '\0' };
3972 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3977 if (sizeof (DCHAR_T) == 1)
3979 sprintf ((char *) p, "%+.2d", exponent);
3987 sprintf (expbuf, "%+.2d", exponent);
3988 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4000 /* arg is finite. */
4006 if (dp->conversion == 'f' || dp->conversion == 'F')
4009 if ((flags & FLAG_ALT) || precision > 0)
4011 *p++ = decimal_point_char ();
4012 for (; precision > 0; precision--)
4016 else if (dp->conversion == 'e' || dp->conversion == 'E')
4019 if ((flags & FLAG_ALT) || precision > 0)
4021 *p++ = decimal_point_char ();
4022 for (; precision > 0; precision--)
4025 *p++ = dp->conversion; /* 'e' or 'E' */
4030 else if (dp->conversion == 'g' || dp->conversion == 'G')
4033 if (flags & FLAG_ALT)
4036 (precision > 0 ? precision - 1 : 0);
4037 *p++ = decimal_point_char ();
4038 for (; ndigits > 0; --ndigits)
4042 else if (dp->conversion == 'a' || dp->conversion == 'A')
4045 *p++ = dp->conversion - 'A' + 'X';
4048 if ((flags & FLAG_ALT) || precision > 0)
4050 *p++ = decimal_point_char ();
4051 for (; precision > 0; precision--)
4054 *p++ = dp->conversion - 'A' + 'P';
4063 END_LONG_DOUBLE_ROUNDING ();
4066 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4070 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4072 double arg = a.arg[dp->arg_index].a.a_double;
4076 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4078 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4082 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4089 if (signbit (arg)) /* arg < 0.0 or negative zero */
4097 else if (flags & FLAG_SHOWSIGN)
4099 else if (flags & FLAG_SPACE)
4102 if (arg > 0.0 && arg + arg == arg)
4104 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4106 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4110 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4115 # if NEED_PRINTF_DOUBLE
4118 if (dp->conversion == 'f' || dp->conversion == 'F')
4124 scale10_round_decimal_double (arg, precision);
4127 ndigits = strlen (digits);
4129 if (ndigits > precision)
4133 *p++ = digits[ndigits];
4135 while (ndigits > precision);
4138 /* Here ndigits <= precision. */
4139 if ((flags & FLAG_ALT) || precision > 0)
4141 *p++ = decimal_point_char ();
4142 for (; precision > ndigits; precision--)
4147 *p++ = digits[ndigits];
4153 else if (dp->conversion == 'e' || dp->conversion == 'E')
4161 if ((flags & FLAG_ALT) || precision > 0)
4163 *p++ = decimal_point_char ();
4164 for (; precision > 0; precision--)
4175 exponent = floorlog10 (arg);
4180 scale10_round_decimal_double (arg,
4181 (int)precision - exponent);
4184 ndigits = strlen (digits);
4186 if (ndigits == precision + 1)
4188 if (ndigits < precision
4189 || ndigits > precision + 2)
4190 /* The exponent was not guessed
4191 precisely enough. */
4194 /* None of two values of exponent is
4195 the right one. Prevent an endless
4199 if (ndigits == precision)
4205 /* Here ndigits = precision+1. */
4206 if (is_borderline (digits, precision))
4208 /* Maybe the exponent guess was too high
4209 and a smaller exponent can be reached
4210 by turning a 10...0 into 9...9x. */
4212 scale10_round_decimal_double (arg,
4213 (int)precision - exponent + 1);
4214 if (digits2 == NULL)
4219 if (strlen (digits2) == precision + 1)
4228 /* Here ndigits = precision+1. */
4230 *p++ = digits[--ndigits];
4231 if ((flags & FLAG_ALT) || precision > 0)
4233 *p++ = decimal_point_char ();
4237 *p++ = digits[ndigits];
4244 *p++ = dp->conversion; /* 'e' or 'E' */
4245 # if WIDE_CHAR_VERSION
4247 static const wchar_t decimal_format[] =
4248 /* Produce the same number of exponent digits
4249 as the native printf implementation. */
4250 # if (defined _WIN32 && FALSE) && ! defined __CYGWIN__
4251 { '%', '+', '.', '3', 'd', '\0' };
4253 { '%', '+', '.', '2', 'd', '\0' };
4255 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4261 static const char decimal_format[] =
4262 /* Produce the same number of exponent digits
4263 as the native printf implementation. */
4264 # if (defined _WIN32 && FALSE) && ! defined __CYGWIN__
4269 if (sizeof (DCHAR_T) == 1)
4271 sprintf ((char *) p, decimal_format, exponent);
4279 sprintf (expbuf, decimal_format, exponent);
4280 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4286 else if (dp->conversion == 'g' || dp->conversion == 'G')
4290 /* precision >= 1. */
4293 /* The exponent is 0, >= -4, < precision.
4294 Use fixed-point notation. */
4296 size_t ndigits = precision;
4297 /* Number of trailing zeroes that have to be
4300 (flags & FLAG_ALT ? 0 : precision - 1);
4304 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4306 *p++ = decimal_point_char ();
4307 while (ndigits > nzeroes)
4323 exponent = floorlog10 (arg);
4328 scale10_round_decimal_double (arg,
4329 (int)(precision - 1) - exponent);
4332 ndigits = strlen (digits);
4334 if (ndigits == precision)
4336 if (ndigits < precision - 1
4337 || ndigits > precision + 1)
4338 /* The exponent was not guessed
4339 precisely enough. */
4342 /* None of two values of exponent is
4343 the right one. Prevent an endless
4347 if (ndigits < precision)
4353 /* Here ndigits = precision. */
4354 if (is_borderline (digits, precision - 1))
4356 /* Maybe the exponent guess was too high
4357 and a smaller exponent can be reached
4358 by turning a 10...0 into 9...9x. */
4360 scale10_round_decimal_double (arg,
4361 (int)(precision - 1) - exponent + 1);
4362 if (digits2 == NULL)
4367 if (strlen (digits2) == precision)
4376 /* Here ndigits = precision. */
4378 /* Determine the number of trailing zeroes
4379 that have to be dropped. */
4381 if ((flags & FLAG_ALT) == 0)
4382 while (nzeroes < ndigits
4383 && digits[nzeroes] == '0')
4386 /* The exponent is now determined. */
4388 && exponent < (long)precision)
4390 /* Fixed-point notation:
4391 max(exponent,0)+1 digits, then the
4392 decimal point, then the remaining
4393 digits without trailing zeroes. */
4396 size_t ecount = exponent + 1;
4397 /* Note: ecount <= precision = ndigits. */
4398 for (; ecount > 0; ecount--)
4399 *p++ = digits[--ndigits];
4400 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4402 *p++ = decimal_point_char ();
4403 while (ndigits > nzeroes)
4406 *p++ = digits[ndigits];
4412 size_t ecount = -exponent - 1;
4414 *p++ = decimal_point_char ();
4415 for (; ecount > 0; ecount--)
4417 while (ndigits > nzeroes)
4420 *p++ = digits[ndigits];
4426 /* Exponential notation. */
4427 *p++ = digits[--ndigits];
4428 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4430 *p++ = decimal_point_char ();
4431 while (ndigits > nzeroes)
4434 *p++ = digits[ndigits];
4437 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4438 # if WIDE_CHAR_VERSION
4440 static const wchar_t decimal_format[] =
4441 /* Produce the same number of exponent digits
4442 as the native printf implementation. */
4443 # if (defined _WIN32 && FALSE) && ! defined __CYGWIN__
4444 { '%', '+', '.', '3', 'd', '\0' };
4446 { '%', '+', '.', '2', 'd', '\0' };
4448 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4454 static const char decimal_format[] =
4455 /* Produce the same number of exponent digits
4456 as the native printf implementation. */
4457 # if (defined _WIN32 && FALSE) && ! defined __CYGWIN__
4462 if (sizeof (DCHAR_T) == 1)
4464 sprintf ((char *) p, decimal_format, exponent);
4472 sprintf (expbuf, decimal_format, exponent);
4473 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4486 /* arg is finite. */
4492 if (dp->conversion == 'f' || dp->conversion == 'F')
4495 if ((flags & FLAG_ALT) || precision > 0)
4497 *p++ = decimal_point_char ();
4498 for (; precision > 0; precision--)
4502 else if (dp->conversion == 'e' || dp->conversion == 'E')
4505 if ((flags & FLAG_ALT) || precision > 0)
4507 *p++ = decimal_point_char ();
4508 for (; precision > 0; precision--)
4511 *p++ = dp->conversion; /* 'e' or 'E' */
4513 /* Produce the same number of exponent digits as
4514 the native printf implementation. */
4515 # if (defined _WIN32 && FALSE) && ! defined __CYGWIN__
4521 else if (dp->conversion == 'g' || dp->conversion == 'G')
4524 if (flags & FLAG_ALT)
4527 (precision > 0 ? precision - 1 : 0);
4528 *p++ = decimal_point_char ();
4529 for (; ndigits > 0; --ndigits)
4541 /* The generated string now extends from tmp to p, with the
4542 zero padding insertion point being at pad_ptr. */
4547 size_t pad = width - count;
4548 DCHAR_T *end = p + pad;
4550 if (flags & FLAG_LEFT)
4552 /* Pad with spaces on the right. */
4553 for (; pad > 0; pad--)
4556 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4558 /* Pad with zeroes. */
4563 for (; pad > 0; pad--)
4568 /* Pad with spaces on the left. */
4573 for (; pad > 0; pad--)
4582 if (count >= tmp_length)
4583 /* tmp_length was incorrectly calculated - fix the
4587 /* Make room for the result. */
4588 if (count >= allocated - length)
4590 size_t n = xsum (length, count);
4592 ENSURE_ALLOCATION (n);
4595 /* Append the result. */
4596 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4604 arg_type type = a.arg[dp->arg_index].type;
4605 int flags = dp->flags;
4606 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4609 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4612 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4616 #if NEED_PRINTF_UNBOUNDED_PRECISION
4619 # define prec_ourselves 0
4621 #if NEED_PRINTF_FLAG_LEFTADJUST
4622 # define pad_ourselves 1
4623 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4626 # define pad_ourselves 0
4629 unsigned int prefix_count;
4630 int prefixes[2] IF_LINT (= { 0 });
4634 TCHAR_T tmpbuf[700];
4638 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4641 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4643 if (dp->width_start != dp->width_end)
4645 if (dp->width_arg_index != ARG_NONE)
4649 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4651 arg = a.arg[dp->width_arg_index].a.a_int;
4655 /* "A negative field width is taken as a '-' flag
4656 followed by a positive field width." */
4663 const FCHAR_T *digitp = dp->width_start;
4666 width = xsum (xtimes (width, 10), *digitp++ - '0');
4667 while (digitp != dp->width_end);
4669 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4675 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4678 if (dp->precision_start != dp->precision_end)
4680 if (dp->precision_arg_index != ARG_NONE)
4684 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4686 arg = a.arg[dp->precision_arg_index].a.a_int;
4687 /* "A negative precision is taken as if the precision
4697 const FCHAR_T *digitp = dp->precision_start + 1;
4700 while (digitp != dp->precision_end)
4701 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4707 /* Decide whether to handle the precision ourselves. */
4708 #if NEED_PRINTF_UNBOUNDED_PRECISION
4709 switch (dp->conversion)
4711 case 'd': case 'i': case 'u':
4713 case 'x': case 'X': case 'p':
4714 prec_ourselves = has_precision && (precision > 0);
4722 /* Decide whether to perform the padding ourselves. */
4723 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4724 switch (dp->conversion)
4726 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4727 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4728 to perform the padding after this conversion. Functions
4729 with unistdio extensions perform the padding based on
4730 character count rather than element count. */
4733 # if NEED_PRINTF_FLAG_ZERO
4734 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4740 pad_ourselves = prec_ourselves;
4746 /* Allocate a temporary buffer of sufficient size for calling
4749 MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
4750 flags, width, has_precision, precision,
4753 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4757 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4759 if (size_overflow_p (tmp_memsize))
4760 /* Overflow, would lead to out of memory. */
4762 tmp = (TCHAR_T *) malloc (tmp_memsize);
4764 /* Out of memory. */
4769 /* Construct the format string for calling snprintf or
4773 #if NEED_PRINTF_FLAG_GROUPING
4774 /* The underlying implementation doesn't support the ' flag.
4775 Produce no grouping characters in this case; this is
4776 acceptable because the grouping is locale dependent. */
4778 if (flags & FLAG_GROUP)
4781 if (flags & FLAG_LEFT)
4783 if (flags & FLAG_SHOWSIGN)
4785 if (flags & FLAG_SPACE)
4787 if (flags & FLAG_ALT)
4789 #if __GLIBC__ >= 2 && !defined __UCLIBC__
4790 if (flags & FLAG_LOCALIZED)
4795 if (flags & FLAG_ZERO)
4797 if (dp->width_start != dp->width_end)
4799 size_t n = dp->width_end - dp->width_start;
4800 /* The width specification is known to consist only
4801 of standard ASCII characters. */
4802 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4804 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4809 const FCHAR_T *mp = dp->width_start;
4816 if (!prec_ourselves)
4818 if (dp->precision_start != dp->precision_end)
4820 size_t n = dp->precision_end - dp->precision_start;
4821 /* The precision specification is known to consist only
4822 of standard ASCII characters. */
4823 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4825 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4830 const FCHAR_T *mp = dp->precision_start;
4841 case TYPE_LONGLONGINT:
4842 case TYPE_ULONGLONGINT:
4843 # if (defined _WIN32 && FALSE) && ! defined __CYGWIN__
4856 case TYPE_WIDE_CHAR:
4859 case TYPE_WIDE_STRING:
4863 case TYPE_LONGDOUBLE:
4869 #if NEED_PRINTF_DIRECTIVE_F
4870 if (dp->conversion == 'F')
4874 *fbp = dp->conversion;
4876 # if ! (((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) \
4877 && !defined __UCLIBC__) \
4878 || (defined __APPLE__ && defined __MACH__) \
4879 || defined __ANDROID__ \
4880 || (defined _WIN32 && ! defined __CYGWIN__))
4885 /* On glibc2 systems from glibc >= 2.3 - probably also older
4886 ones - we know that snprintf's return value conforms to
4887 ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and
4888 gl_SNPRINTF_TRUNCATION_C99 pass.
4889 Therefore we can avoid using %n in this situation.
4890 On glibc2 systems from 2004-10-18 or newer, the use of %n
4891 in format strings in writable memory may crash the program
4892 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4893 in this situation. */
4894 /* On Mac OS X 10.3 or newer, we know that snprintf's return
4895 value conforms to ISO C 99: the tests gl_SNPRINTF_RETVAL_C99
4896 and gl_SNPRINTF_TRUNCATION_C99 pass.
4897 Therefore we can avoid using %n in this situation.
4898 On Mac OS X 10.13 or newer, the use of %n in format strings
4899 in writable memory by default crashes the program, so we
4900 should avoid it in this situation. */
4901 /* On Android, we know that snprintf's return value conforms to
4902 ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and
4903 gl_SNPRINTF_TRUNCATION_C99 pass.
4904 Therefore we can avoid using %n in this situation.
4905 Starting on 2018-03-07, the use of %n in format strings
4906 produces a fatal error (see
4907 <https://android.googlesource.com/platform/bionic/+/41398d03b7e8e0dfb951660ae713e682e9fc0336>),
4908 so we should avoid it. */
4909 /* On native Windows systems (such as mingw), we can avoid using
4911 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4912 snprintf does not write more than the specified number
4913 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4914 '4', '5', '6' into buf, not '4', '5', '\0'.)
4915 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4916 allows us to recognize the case of an insufficient
4917 buffer size: it returns -1 in this case.
4918 On native Windows systems (such as mingw) where the OS is
4919 Windows Vista, the use of %n in format strings by default
4920 crashes the program. See
4921 <https://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4922 <https://msdn.microsoft.com/en-us/library/ms175782.aspx>
4923 So we should avoid %n in this situation. */
4930 /* Construct the arguments for calling snprintf or sprintf. */
4932 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4934 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4936 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4938 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4940 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4942 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4946 /* The SNPRINTF result is appended after result[0..length].
4947 The latter is an array of DCHAR_T; SNPRINTF appends an
4948 array of TCHAR_T to it. This is possible because
4949 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4950 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4951 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4952 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4953 where an snprintf() with maxlen==1 acts like sprintf(). */
4954 ENSURE_ALLOCATION (xsum (length,
4955 (2 + TCHARS_PER_DCHAR - 1)
4956 / TCHARS_PER_DCHAR));
4957 /* Prepare checking whether snprintf returns the count
4959 *(TCHAR_T *) (result + length) = '\0';
4970 size_t maxlen = allocated - length;
4971 /* SNPRINTF can fail if its second argument is
4973 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4974 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4975 maxlen = maxlen * TCHARS_PER_DCHAR;
4976 # define SNPRINTF_BUF(arg) \
4977 switch (prefix_count) \
4980 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4985 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4987 prefixes[0], arg, &count); \
4990 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4992 prefixes[0], prefixes[1], arg, \
4999 # define SNPRINTF_BUF(arg) \
5000 switch (prefix_count) \
5003 count = sprintf (tmp, buf, arg); \
5006 count = sprintf (tmp, buf, prefixes[0], arg); \
5009 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
5022 int arg = a.arg[dp->arg_index].a.a_schar;
5028 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
5034 int arg = a.arg[dp->arg_index].a.a_short;
5040 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
5046 int arg = a.arg[dp->arg_index].a.a_int;
5052 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
5058 long int arg = a.arg[dp->arg_index].a.a_longint;
5064 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
5069 case TYPE_LONGLONGINT:
5071 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
5075 case TYPE_ULONGLONGINT:
5077 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
5084 double arg = a.arg[dp->arg_index].a.a_double;
5088 case TYPE_LONGDOUBLE:
5090 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5096 int arg = a.arg[dp->arg_index].a.a_char;
5101 case TYPE_WIDE_CHAR:
5103 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5110 const char *arg = a.arg[dp->arg_index].a.a_string;
5115 case TYPE_WIDE_STRING:
5117 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5124 void *arg = a.arg[dp->arg_index].a.a_pointer;
5133 /* Portability: Not all implementations of snprintf()
5134 are ISO C 99 compliant. Determine the number of
5135 bytes that snprintf() has produced or would have
5139 /* Verify that snprintf() has NUL-terminated its
5141 if ((unsigned int) count < maxlen
5142 && ((TCHAR_T *) (result + length)) [count] != '\0')
5144 /* Portability hack. */
5145 if (retcount > count)
5150 /* snprintf() doesn't understand the '%n'
5154 /* Don't use the '%n' directive; instead, look
5155 at the snprintf() return value. */
5161 /* Look at the snprintf() return value. */
5164 # if !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF
5165 /* HP-UX 10.20 snprintf() is doubly deficient:
5166 It doesn't understand the '%n' directive,
5167 *and* it returns -1 (rather than the length
5168 that would have been required) when the
5169 buffer is too small.
5170 But a failure at this point can also come
5171 from other reasons than a too small buffer,
5172 such as an invalid wide string argument to
5173 the %ls directive, or possibly an invalid
5174 floating-point argument. */
5176 MAX_ROOM_NEEDED (&a, dp->arg_index,
5177 dp->conversion, type, flags,
5180 precision, pad_ourselves);
5182 if (maxlen < tmp_length)
5184 /* Make more room. But try to do through
5185 this reallocation only once. */
5186 size_t bigger_need =
5189 TCHARS_PER_DCHAR - 1)
5190 / TCHARS_PER_DCHAR);
5191 /* And always grow proportionally.
5192 (There may be several arguments, each
5193 needing a little more room than the
5195 size_t bigger_need2 =
5196 xsum (xtimes (allocated, 2), 12);
5197 if (bigger_need < bigger_need2)
5198 bigger_need = bigger_need2;
5199 ENSURE_ALLOCATION (bigger_need);
5210 /* Attempt to handle failure. */
5213 /* SNPRINTF or sprintf failed. Save and use the errno
5214 that it has set, if any. */
5215 int saved_errno = errno;
5216 if (saved_errno == 0)
5218 if (dp->conversion == 'c' || dp->conversion == 's')
5219 saved_errno = EILSEQ;
5221 saved_errno = EINVAL;
5224 if (!(result == resultbuf || result == NULL))
5226 if (buf_malloced != NULL)
5227 free (buf_malloced);
5230 errno = saved_errno;
5235 /* Handle overflow of the allocated buffer.
5236 If such an overflow occurs, a C99 compliant snprintf()
5237 returns a count >= maxlen. However, a non-compliant
5238 snprintf() function returns only count = maxlen - 1. To
5239 cover both cases, test whether count >= maxlen - 1. */
5240 if ((unsigned int) count + 1 >= maxlen)
5242 /* If maxlen already has attained its allowed maximum,
5243 allocating more memory will not increase maxlen.
5244 Instead of looping, bail out. */
5245 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5249 /* Need at least (count + 1) * sizeof (TCHAR_T)
5250 bytes. (The +1 is for the trailing NUL.)
5251 But ask for (count + 2) * sizeof (TCHAR_T)
5252 bytes, so that in the next round, we likely get
5253 maxlen > (unsigned int) count + 1
5254 and so we don't get here again.
5255 And allocate proportionally, to avoid looping
5256 eternally if snprintf() reports a too small
5260 ((unsigned int) count + 2
5261 + TCHARS_PER_DCHAR - 1)
5262 / TCHARS_PER_DCHAR),
5263 xtimes (allocated, 2));
5265 ENSURE_ALLOCATION (n);
5271 #if NEED_PRINTF_UNBOUNDED_PRECISION
5274 /* Handle the precision. */
5277 (TCHAR_T *) (result + length);
5281 size_t prefix_count;
5285 /* Put the additional zeroes after the sign. */
5287 && (*prec_ptr == '-' || *prec_ptr == '+'
5288 || *prec_ptr == ' '))
5290 /* Put the additional zeroes after the 0x prefix if
5291 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5293 && prec_ptr[0] == '0'
5294 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5297 move = count - prefix_count;
5298 if (precision > move)
5300 /* Insert zeroes. */
5301 size_t insert = precision - move;
5307 (count + insert + TCHARS_PER_DCHAR - 1)
5308 / TCHARS_PER_DCHAR);
5309 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5310 ENSURE_ALLOCATION (n);
5311 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5312 prec_ptr = (TCHAR_T *) (result + length);
5315 prec_end = prec_ptr + count;
5316 prec_ptr += prefix_count;
5318 while (prec_end > prec_ptr)
5321 prec_end[insert] = prec_end[0];
5327 while (prec_end > prec_ptr);
5335 if (count >= tmp_length)
5336 /* tmp_length was incorrectly calculated - fix the
5342 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5343 if (dp->conversion == 'c' || dp->conversion == 's')
5345 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5347 The result string is not certainly ASCII. */
5348 const TCHAR_T *tmpsrc;
5351 /* This code assumes that TCHAR_T is 'char'. */
5352 verify (sizeof (TCHAR_T) == 1);
5354 tmpsrc = (TCHAR_T *) (result + length);
5359 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5360 iconveh_question_mark,
5366 int saved_errno = errno;
5367 if (!(result == resultbuf || result == NULL))
5369 if (buf_malloced != NULL)
5370 free (buf_malloced);
5372 errno = saved_errno;
5375 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5376 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5382 /* The result string is ASCII.
5383 Simple 1:1 conversion. */
5385 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5386 no-op conversion, in-place on the array starting
5387 at (result + length). */
5388 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5391 const TCHAR_T *tmpsrc;
5396 if (result == resultbuf)
5398 tmpsrc = (TCHAR_T *) (result + length);
5399 /* ENSURE_ALLOCATION will not move tmpsrc
5400 (because it's part of resultbuf). */
5401 ENSURE_ALLOCATION (xsum (length, count));
5405 /* ENSURE_ALLOCATION will move the array
5406 (because it uses realloc(). */
5407 ENSURE_ALLOCATION (xsum (length, count));
5408 tmpsrc = (TCHAR_T *) (result + length);
5412 ENSURE_ALLOCATION (xsum (length, count));
5414 tmpdst = result + length;
5415 /* Copy backwards, because of overlapping. */
5418 for (n = count; n > 0; n--)
5419 *--tmpdst = *--tmpsrc;
5424 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5425 /* Make room for the result. */
5426 if (count > allocated - length)
5428 /* Need at least count elements. But allocate
5431 xmax (xsum (length, count), xtimes (allocated, 2));
5433 ENSURE_ALLOCATION (n);
5437 /* Here count <= allocated - length. */
5439 /* Perform padding. */
5440 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5441 if (pad_ourselves && has_width)
5444 # if ENABLE_UNISTDIO
5445 /* Outside POSIX, it's preferable to compare the width
5446 against the number of _characters_ of the converted
5448 w = DCHAR_MBSNLEN (result + length, count);
5450 /* The width is compared against the number of _bytes_
5451 of the converted value, says POSIX. */
5456 size_t pad = width - w;
5458 /* Make room for the result. */
5459 if (xsum (count, pad) > allocated - length)
5461 /* Need at least count + pad elements. But
5462 allocate proportionally. */
5464 xmax (xsum3 (length, count, pad),
5465 xtimes (allocated, 2));
5469 ENSURE_ALLOCATION (n);
5472 ENSURE_ALLOCATION (n);
5475 /* Here count + pad <= allocated - length. */
5478 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5479 DCHAR_T * const rp = result + length;
5481 DCHAR_T * const rp = tmp;
5483 DCHAR_T *p = rp + count;
5484 DCHAR_T *end = p + pad;
5486 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5487 if (dp->conversion == 'c'
5488 || dp->conversion == 's')
5489 /* No zero-padding for string directives. */
5494 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5495 /* No zero-padding of "inf" and "nan". */
5496 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5497 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5500 /* The generated string now extends from rp to p,
5501 with the zero padding insertion point being at
5504 count = count + pad; /* = end - rp */
5506 if (flags & FLAG_LEFT)
5508 /* Pad with spaces on the right. */
5509 for (; pad > 0; pad--)
5512 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5514 /* Pad with zeroes. */
5519 for (; pad > 0; pad--)
5524 /* Pad with spaces on the left. */
5529 for (; pad > 0; pad--)
5537 /* Here still count <= allocated - length. */
5539 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5540 /* The snprintf() result did fit. */
5542 /* Append the sprintf() result. */
5543 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5550 #if NEED_PRINTF_DIRECTIVE_F
5551 if (dp->conversion == 'F')
5553 /* Convert the %f result to upper case for %F. */
5554 DCHAR_T *rp = result + length;
5556 for (rc = count; rc > 0; rc--, rp++)
5557 if (*rp >= 'a' && *rp <= 'z')
5558 *rp = *rp - 'a' + 'A';
5566 #undef pad_ourselves
5567 #undef prec_ourselves
5572 /* Add the final NUL. */
5573 ENSURE_ALLOCATION (xsum (length, 1));
5574 result[length] = '\0';
5576 if (result != resultbuf && length + 1 < allocated)
5578 /* Shrink the allocated memory if possible. */
5581 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5586 if (buf_malloced != NULL)
5587 free (buf_malloced);
5590 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5591 says that snprintf() fails with errno = EOVERFLOW in this case, but
5592 that's only because snprintf() returns an 'int'. This function does
5593 not have this limitation. */
5598 if (!(result == resultbuf || result == NULL))
5600 if (buf_malloced != NULL)
5601 free (buf_malloced);
5608 if (!(result == resultbuf || result == NULL))
5610 if (buf_malloced != NULL)
5611 free (buf_malloced);
5619 #undef MAX_ROOM_NEEDED
5620 #undef TCHARS_PER_DCHAR
5628 #undef DCHAR_IS_TCHAR