1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2021 Free Software Foundation, Inc.
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of the
7 License, or (at your option) any later version.
9 This file 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
15 along 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.
45 ENABLE_UNISTDIO Set to 1 to enable the unistdio extensions.
46 ENABLE_WCHAR_FALLBACK Set to 1 to avoid EILSEQ during conversion of wide
47 characters (wchar_t) and wide character strings
48 (wchar_t[]) to multibyte sequences. The fallback is the
49 hexadecimal escape syntax (\unnnn or \Unnnnnnnn) or,
50 if wchar_t is not Unicode encoded, \wnnnn or \Wnnnnnnnn.
53 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
54 This must come before <config.h> because <config.h> may include
55 <features.h>, and once <features.h> has been included, it's too late. */
57 # define _GNU_SOURCE 1
67 # if WIDE_CHAR_VERSION
68 # include "vasnwprintf.h"
70 # include "vasnprintf.h"
74 #include <locale.h> /* localeconv() */
75 #include <stdio.h> /* snprintf(), sprintf() */
76 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
77 #include <string.h> /* memcpy(), strlen() */
78 #include <errno.h> /* errno */
79 #include <limits.h> /* CHAR_BIT */
80 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
82 # include <langinfo.h>
85 # if WIDE_CHAR_VERSION
86 # include "wprintf-parse.h"
88 # include "printf-parse.h"
92 /* Checked size_t computations. */
95 #include "attribute.h"
98 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
103 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
105 # include "isnand-nolibm.h"
108 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
110 # include "isnanl-nolibm.h"
114 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
116 # include "isnand-nolibm.h"
117 # include "printf-frexp.h"
120 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
122 # include "isnanl-nolibm.h"
123 # include "printf-frexpl.h"
127 /* Default parameters. */
129 # if WIDE_CHAR_VERSION
130 # define VASNPRINTF vasnwprintf
131 # define FCHAR_T wchar_t
132 # define DCHAR_T wchar_t
133 # define TCHAR_T wchar_t
134 # define DCHAR_IS_TCHAR 1
135 # define DIRECTIVE wchar_t_directive
136 # define DIRECTIVES wchar_t_directives
137 # define PRINTF_PARSE wprintf_parse
138 # define DCHAR_CPY wmemcpy
139 # define DCHAR_SET wmemset
141 # define VASNPRINTF vasnprintf
142 # define FCHAR_T char
143 # define DCHAR_T char
144 # define TCHAR_T char
145 # define DCHAR_IS_TCHAR 1
146 # define DIRECTIVE char_directive
147 # define DIRECTIVES char_directives
148 # define PRINTF_PARSE printf_parse
149 # define DCHAR_CPY memcpy
150 # define DCHAR_SET memset
153 #if WIDE_CHAR_VERSION
154 /* TCHAR_T is wchar_t. */
155 # define USE_SNPRINTF 1
156 # if HAVE_DECL__SNWPRINTF
157 /* On Windows, the function swprintf() has a different signature than
158 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
159 instead. The mingw function snwprintf() has fewer bugs than the
160 MSVCRT function _snwprintf(), so prefer that. */
161 # if defined __MINGW32__
162 # define SNPRINTF snwprintf
164 # define SNPRINTF _snwprintf
165 # define USE_MSVC__SNPRINTF 1
169 # define SNPRINTF swprintf
172 /* TCHAR_T is char. */
173 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
174 But don't use it on BeOS, since BeOS snprintf produces no output if the
175 size argument is >= 0x3000000.
176 Also don't use it on Linux libc5, since there snprintf with size = 1
177 writes any output without bounds, like sprintf. */
178 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
179 # define USE_SNPRINTF 1
181 # define USE_SNPRINTF 0
183 # if HAVE_DECL__SNPRINTF
184 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
185 function _snprintf(), so prefer that. */
186 # if defined __MINGW32__
187 # define SNPRINTF snprintf
188 /* Here we need to call the native snprintf, not rpl_snprintf. */
191 /* MSVC versions < 14 did not have snprintf, only _snprintf. */
192 # define SNPRINTF _snprintf
193 # define USE_MSVC__SNPRINTF 1
197 # define SNPRINTF snprintf
198 /* Here we need to call the native snprintf, not rpl_snprintf. */
202 /* Here we need to call the native sprintf, not rpl_sprintf. */
205 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
206 warnings in this file. Use -Dlint to suppress them. */
207 #if defined GCC_LINT || defined lint
208 # define IF_LINT(Code) Code
210 # define IF_LINT(Code) /* empty */
213 /* Avoid some warnings from "gcc -Wshadow".
214 This file doesn't use the exp() and remainder() functions. */
218 #define remainder rem
220 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && !WIDE_CHAR_VERSION
221 # if (HAVE_STRNLEN && !defined _AIX)
222 # define local_strnlen strnlen
224 # ifndef local_strnlen_defined
225 # define local_strnlen_defined 1
227 local_strnlen (const char *string, size_t maxlen)
229 const char *end = memchr (string, '\0', maxlen);
230 return end ? (size_t) (end - string) : maxlen;
236 #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
238 # define local_wcslen wcslen
240 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
241 a dependency towards this library, here is a local substitute.
242 Define this substitute only once, even if this file is included
243 twice in the same compilation unit. */
244 # ifndef local_wcslen_defined
245 # define local_wcslen_defined 1
247 local_wcslen (const wchar_t *s)
251 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
259 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
261 # define local_wcsnlen wcsnlen
263 # ifndef local_wcsnlen_defined
264 # define local_wcsnlen_defined 1
266 local_wcsnlen (const wchar_t *s, size_t maxlen)
270 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
278 #if (((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL) || ENABLE_WCHAR_FALLBACK) && HAVE_WCHAR_T) || (ENABLE_WCHAR_FALLBACK && HAVE_WINT_T)) && !WIDE_CHAR_VERSION
279 # if ENABLE_WCHAR_FALLBACK
281 wctomb_fallback (char *s, wchar_t wc)
283 static char hex[16] = "0123456789ABCDEF";
286 if (sizeof (wchar_t) > 2 && wc > 0xffff)
288 # if __STDC_ISO_10646__ || (__GLIBC__ >= 2) || (defined _WIN32 || defined __CYGWIN__)
293 s[2] = hex[(wc & 0xf0000000U) >> 28];
294 s[3] = hex[(wc & 0xf000000U) >> 24];
295 s[4] = hex[(wc & 0xf00000U) >> 20];
296 s[5] = hex[(wc & 0xf0000U) >> 16];
297 s[6] = hex[(wc & 0xf000U) >> 12];
298 s[7] = hex[(wc & 0xf00U) >> 8];
299 s[8] = hex[(wc & 0xf0U) >> 4];
300 s[9] = hex[wc & 0xfU];
305 # if __STDC_ISO_10646__ || (__GLIBC__ >= 2) || (defined _WIN32 || defined __CYGWIN__)
310 s[2] = hex[(wc & 0xf000U) >> 12];
311 s[3] = hex[(wc & 0xf00U) >> 8];
312 s[4] = hex[(wc & 0xf0U) >> 4];
313 s[5] = hex[wc & 0xfU];
317 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
319 local_wcrtomb (char *s, wchar_t wc, mbstate_t *ps)
321 size_t count = wcrtomb (s, wc, ps);
322 if (count == (size_t)(-1))
323 count = wctomb_fallback (s, wc);
328 local_wctomb (char *s, wchar_t wc)
330 int count = wctomb (s, wc);
332 count = wctomb_fallback (s, wc);
335 # define local_wcrtomb(S, WC, PS) local_wctomb ((S), (WC))
338 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
339 # define local_wcrtomb(S, WC, PS) wcrtomb ((S), (WC), (PS))
341 # define local_wcrtomb(S, WC, PS) wctomb ((S), (WC))
346 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
347 /* Determine the decimal-point character according to the current locale. */
348 # ifndef decimal_point_char_defined
349 # define decimal_point_char_defined 1
351 decimal_point_char (void)
354 /* Determine it in a multithread-safe way. We know nl_langinfo is
355 multithread-safe on glibc systems and Mac OS X systems, but is not required
356 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
357 localeconv() is rarely multithread-safe. */
358 # if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
359 point = nl_langinfo (RADIXCHAR);
362 sprintf (pointbuf, "%#.0f", 1.0);
363 point = &pointbuf[1];
365 point = localeconv () -> decimal_point;
367 /* The decimal point is always a single byte: either '.' or ','. */
368 return (point[0] != '\0' ? point[0] : '.');
373 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
375 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
377 is_infinite_or_zero (double x)
379 return isnand (x) || x + x == x;
384 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
386 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
388 is_infinite_or_zerol (long double x)
390 return isnanl (x) || x + x == x;
395 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
397 /* Converting 'long double' to decimal without rare rounding bugs requires
398 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
399 (and slower) algorithms. */
401 typedef unsigned int mp_limb_t;
402 # define GMP_LIMB_BITS 32
403 verify (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS);
405 typedef unsigned long long mp_twolimb_t;
406 # define GMP_TWOLIMB_BITS 64
407 verify (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS);
409 /* Representation of a bignum >= 0. */
413 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
416 /* Compute the product of two bignums >= 0.
417 Return the allocated memory in case of success, NULL in case of memory
418 allocation failure. */
420 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
427 if (src1.nlimbs <= src2.nlimbs)
441 /* Now 0 <= len1 <= len2. */
444 /* src1 or src2 is zero. */
446 dest->limbs = (mp_limb_t *) malloc (1);
450 /* Here 1 <= len1 <= len2. */
456 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
459 for (k = len2; k > 0; )
461 for (i = 0; i < len1; i++)
463 mp_limb_t digit1 = p1[i];
464 mp_twolimb_t carry = 0;
465 for (j = 0; j < len2; j++)
467 mp_limb_t digit2 = p2[j];
468 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
470 dp[i + j] = (mp_limb_t) carry;
471 carry = carry >> GMP_LIMB_BITS;
473 dp[i + len2] = (mp_limb_t) carry;
476 while (dlen > 0 && dp[dlen - 1] == 0)
484 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
485 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
487 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
489 Return the allocated memory in case of success, NULL in case of memory
490 allocation failure. */
492 divide (mpn_t a, mpn_t b, mpn_t *q)
495 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
496 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
497 If m<n, then q:=0 and r:=a.
498 If m>=n=1, perform a single-precision division:
501 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
502 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
503 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
504 Normalise [q[m-1],...,q[0]], yields q.
505 If m>=n>1, perform a multiple-precision division:
506 We have a/b < beta^(m-n+1).
507 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
508 Shift a and b left by s bits, copying them. r:=a.
509 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
510 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
512 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
513 In case of overflow (q* >= beta) set q* := beta-1.
514 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
515 and c3 := b[n-2] * q*.
516 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
517 occurred. Furthermore 0 <= c3 < beta^2.
518 If there was overflow and
519 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
520 the next test can be skipped.}
521 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
522 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
524 Put r := r - b * q* * beta^j. In detail:
525 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
526 hence: u:=0, for i:=0 to n-1 do
528 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
529 u:=u div beta (+ 1, if carry in subtraction)
531 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
533 the carry u does not overflow.}
534 If a negative carry occurs, put q* := q* - 1
535 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
537 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
538 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
540 The room for q[j] can be allocated at the memory location of r[n+j].
541 Finally, round-to-even:
542 Shift r left by 1 bit.
543 If r > b or if r = b and q[0] is odd, q := q+1.
545 const mp_limb_t *a_ptr = a.limbs;
546 size_t a_len = a.nlimbs;
547 const mp_limb_t *b_ptr = b.limbs;
548 size_t b_len = b.nlimbs;
550 mp_limb_t *tmp_roomptr = NULL;
556 /* Allocate room for a_len+2 digits.
557 (Need a_len+1 digits for the real division and 1 more digit for the
558 final rounding of q.) */
559 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
564 while (a_len > 0 && a_ptr[a_len - 1] == 0)
571 /* Division by zero. */
573 if (b_ptr[b_len - 1] == 0)
579 /* Here m = a_len >= 0 and n = b_len > 0. */
583 /* m<n: trivial case. q=0, r := copy of a. */
586 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
587 q_ptr = roomptr + a_len;
592 /* n=1: single precision division.
593 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
597 mp_limb_t den = b_ptr[0];
598 mp_limb_t remainder = 0;
599 const mp_limb_t *sourceptr = a_ptr + a_len;
600 mp_limb_t *destptr = q_ptr + a_len;
602 for (count = a_len; count > 0; count--)
605 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
606 *--destptr = num / den;
607 remainder = num % den;
609 /* Normalise and store r. */
612 r_ptr[0] = remainder;
619 if (q_ptr[q_len - 1] == 0)
625 /* n>1: multiple precision division.
626 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
627 beta^(m-n-1) <= a/b < beta^(m-n+1). */
631 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
632 /* Determine s = GMP_LIMB_BITS - integer_length (msd).
633 Code copied from gnulib's integer_length.c. */
634 # if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) \
635 || (__clang_major__ >= 4)
636 s = __builtin_clz (msd);
638 # if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT
639 if (GMP_LIMB_BITS <= DBL_MANT_BIT)
641 /* Use 'double' operations.
642 Assumes an IEEE 754 'double' implementation. */
643 # define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)
644 # define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1)
646 ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
647 union { double value; unsigned int word[NWORDS]; } m;
649 /* Use a single integer to floating-point conversion. */
653 - (((m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK)
689 /* 0 <= s < GMP_LIMB_BITS.
690 Copy b, shifting it left by s bits. */
693 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
694 if (tmp_roomptr == NULL)
700 const mp_limb_t *sourceptr = b_ptr;
701 mp_limb_t *destptr = tmp_roomptr;
702 mp_twolimb_t accu = 0;
704 for (count = b_len; count > 0; count--)
706 accu += (mp_twolimb_t) *sourceptr++ << s;
707 *destptr++ = (mp_limb_t) accu;
708 accu = accu >> GMP_LIMB_BITS;
710 /* accu must be zero, since that was how s was determined. */
716 /* Copy a, shifting it left by s bits, yields r.
718 At the beginning: r = roomptr[0..a_len],
719 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
723 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
728 const mp_limb_t *sourceptr = a_ptr;
729 mp_limb_t *destptr = r_ptr;
730 mp_twolimb_t accu = 0;
732 for (count = a_len; count > 0; count--)
734 accu += (mp_twolimb_t) *sourceptr++ << s;
735 *destptr++ = (mp_limb_t) accu;
736 accu = accu >> GMP_LIMB_BITS;
738 *destptr++ = (mp_limb_t) accu;
740 q_ptr = roomptr + b_len;
741 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
743 size_t j = a_len - b_len; /* m-n */
744 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
745 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
746 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
747 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
748 /* Division loop, traversed m-n+1 times.
749 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
754 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
756 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
758 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
759 | r_ptr[j + b_len - 1];
760 q_star = num / b_msd;
765 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
766 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
767 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
768 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
769 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
771 If yes, jump directly to the subtraction loop.
772 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
773 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
774 if (r_ptr[j + b_len] > b_msd
775 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
776 /* r[j+n] >= b[n-1]+1 or
777 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
782 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
784 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
785 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
786 mp_twolimb_t c3 = /* b[n-2] * q* */
787 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
788 /* While c2 < c3, increase c2 and decrease c3.
789 Consider c3-c2. While it is > 0, decrease it by
790 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
791 this can happen only twice. */
794 q_star = q_star - 1; /* q* := q* - 1 */
795 if (c3 - c2 > b_msdd)
796 q_star = q_star - 1; /* q* := q* - 1 */
802 /* Subtract r := r - b * q* * beta^j. */
805 const mp_limb_t *sourceptr = b_ptr;
806 mp_limb_t *destptr = r_ptr + j;
807 mp_twolimb_t carry = 0;
809 for (count = b_len; count > 0; count--)
811 /* Here 0 <= carry <= q*. */
814 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
815 + (mp_limb_t) ~(*destptr);
816 /* Here 0 <= carry <= beta*q* + beta-1. */
817 *destptr++ = ~(mp_limb_t) carry;
818 carry = carry >> GMP_LIMB_BITS; /* <= q* */
820 cr = (mp_limb_t) carry;
822 /* Subtract cr from r_ptr[j + b_len], then forget about
824 if (cr > r_ptr[j + b_len])
826 /* Subtraction gave a carry. */
827 q_star = q_star - 1; /* q* := q* - 1 */
830 const mp_limb_t *sourceptr = b_ptr;
831 mp_limb_t *destptr = r_ptr + j;
834 for (count = b_len; count > 0; count--)
836 mp_limb_t source1 = *sourceptr++;
837 mp_limb_t source2 = *destptr;
838 *destptr++ = source1 + source2 + carry;
841 ? source1 >= (mp_limb_t) ~source2
842 : source1 > (mp_limb_t) ~source2);
845 /* Forget about the carry and about r[j+n]. */
848 /* q* is determined. Store it as q[j]. */
857 if (q_ptr[q_len - 1] == 0)
859 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
860 b is shifted left by s bits. */
861 /* Shift r right by s bits. */
864 mp_limb_t ptr = r_ptr + r_len;
865 mp_twolimb_t accu = 0;
867 for (count = r_len; count > 0; count--)
869 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
870 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
871 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
876 while (r_len > 0 && r_ptr[r_len - 1] == 0)
879 /* Compare r << 1 with b. */
887 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
888 | (i < r_len ? r_ptr[i] << 1 : 0);
889 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
899 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
904 for (i = 0; i < q_len; i++)
905 if (++(q_ptr[i]) != 0)
910 if (tmp_roomptr != NULL)
917 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
919 Destroys the contents of a.
920 Return the allocated memory - containing the decimal digits in low-to-high
921 order, terminated with a NUL character - in case of success, NULL in case
922 of memory allocation failure. */
924 convert_to_decimal (mpn_t a, size_t extra_zeroes)
926 mp_limb_t *a_ptr = a.limbs;
927 size_t a_len = a.nlimbs;
928 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
929 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
930 /* We need extra_zeroes bytes for zeroes, followed by c_len bytes for the
931 digits of a, followed by 1 byte for the terminating NUL. */
932 char *c_ptr = (char *) malloc (xsum (xsum (extra_zeroes, c_len), 1));
936 for (; extra_zeroes > 0; extra_zeroes--)
940 /* Divide a by 10^9, in-place. */
941 mp_limb_t remainder = 0;
942 mp_limb_t *ptr = a_ptr + a_len;
944 for (count = a_len; count > 0; count--)
947 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
948 *ptr = num / 1000000000;
949 remainder = num % 1000000000;
951 /* Store the remainder as 9 decimal digits. */
952 for (count = 9; count > 0; count--)
954 *d_ptr++ = '0' + (remainder % 10);
955 remainder = remainder / 10;
958 if (a_ptr[a_len - 1] == 0)
961 /* Remove leading zeroes. */
962 while (d_ptr > c_ptr && d_ptr[-1] == '0')
964 /* But keep at least one zero. */
967 /* Terminate the string. */
973 # if NEED_PRINTF_LONG_DOUBLE
975 /* Assuming x is finite and >= 0:
976 write x as x = 2^e * m, where m is a bignum.
977 Return the allocated memory in case of success, NULL in case of memory
978 allocation failure. */
980 decode_long_double (long double x, int *ep, mpn_t *mp)
987 /* Allocate memory for result. */
988 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
989 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
992 /* Split into exponential part and mantissa. */
993 y = frexpl (x, &exp);
994 if (!(y >= 0.0L && y < 1.0L))
996 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the
997 latter is an integer. */
998 /* Convert the mantissa (y * 2^LDBL_MANT_BIT) to a sequence of limbs.
999 I'm not sure whether it's safe to cast a 'long double' value between
1000 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1001 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1003 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
1004 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1007 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
1010 if (!(y >= 0.0L && y < 1.0L))
1012 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1015 if (!(y >= 0.0L && y < 1.0L))
1017 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1022 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
1025 if (!(y >= 0.0L && y < 1.0L))
1027 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
1031 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1034 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1037 if (!(y >= 0.0L && y < 1.0L))
1039 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1042 if (!(y >= 0.0L && y < 1.0L))
1044 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1046 # if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
1052 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1055 *ep = exp - LDBL_MANT_BIT;
1061 # if NEED_PRINTF_DOUBLE
1063 /* Assuming x is finite and >= 0:
1064 write x as x = 2^e * m, where m is a bignum.
1065 Return the allocated memory in case of success, NULL in case of memory
1066 allocation failure. */
1068 decode_double (double x, int *ep, mpn_t *mp)
1075 /* Allocate memory for result. */
1076 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
1077 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
1078 if (m.limbs == NULL)
1080 /* Split into exponential part and mantissa. */
1081 y = frexp (x, &exp);
1082 if (!(y >= 0.0 && y < 1.0))
1084 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the
1085 latter is an integer. */
1086 /* Convert the mantissa (y * 2^DBL_MANT_BIT) to a sequence of limbs.
1087 I'm not sure whether it's safe to cast a 'double' value between
1088 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1089 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1091 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
1092 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1095 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
1098 if (!(y >= 0.0 && y < 1.0))
1100 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1103 if (!(y >= 0.0 && y < 1.0))
1105 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1110 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
1113 if (!(y >= 0.0 && y < 1.0))
1115 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
1119 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1122 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1125 if (!(y >= 0.0 && y < 1.0))
1127 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1130 if (!(y >= 0.0 && y < 1.0))
1132 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1137 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1140 *ep = exp - DBL_MANT_BIT;
1146 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1147 Returns the decimal representation of round (x * 10^n).
1148 Return the allocated memory - containing the decimal digits in low-to-high
1149 order, terminated with a NUL character - in case of success, NULL in case
1150 of memory allocation failure. */
1152 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1155 size_t extra_zeroes;
1158 mp_limb_t *pow5_ptr;
1160 unsigned int s_limbs;
1161 unsigned int s_bits;
1169 /* x = 2^e * m, hence
1170 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1171 = round (2^s * 5^n * m). */
1174 /* Factor out a common power of 10 if possible. */
1177 extra_zeroes = (s < n ? s : n);
1181 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1182 Before converting to decimal, we need to compute
1183 z = round (2^s * 5^n * m). */
1184 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1185 sign. 2.322 is slightly larger than log(5)/log(2). */
1186 abs_n = (n >= 0 ? n : -n);
1187 abs_s = (s >= 0 ? s : -s);
1188 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1189 + abs_s / GMP_LIMB_BITS + 1)
1190 * sizeof (mp_limb_t));
1191 if (pow5_ptr == NULL)
1196 /* Initialize with 1. */
1199 /* Multiply with 5^|n|. */
1202 static mp_limb_t const small_pow5[13 + 1] =
1204 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1205 48828125, 244140625, 1220703125
1208 for (n13 = 0; n13 <= abs_n; n13 += 13)
1210 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1212 mp_twolimb_t carry = 0;
1213 for (j = 0; j < pow5_len; j++)
1215 mp_limb_t digit2 = pow5_ptr[j];
1216 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1217 pow5_ptr[j] = (mp_limb_t) carry;
1218 carry = carry >> GMP_LIMB_BITS;
1221 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1224 s_limbs = abs_s / GMP_LIMB_BITS;
1225 s_bits = abs_s % GMP_LIMB_BITS;
1226 if (n >= 0 ? s >= 0 : s <= 0)
1228 /* Multiply with 2^|s|. */
1231 mp_limb_t *ptr = pow5_ptr;
1232 mp_twolimb_t accu = 0;
1234 for (count = pow5_len; count > 0; count--)
1236 accu += (mp_twolimb_t) *ptr << s_bits;
1237 *ptr++ = (mp_limb_t) accu;
1238 accu = accu >> GMP_LIMB_BITS;
1242 *ptr = (mp_limb_t) accu;
1249 for (count = pow5_len; count > 0;)
1252 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1254 for (count = s_limbs; count > 0;)
1257 pow5_ptr[count] = 0;
1259 pow5_len += s_limbs;
1261 pow5.limbs = pow5_ptr;
1262 pow5.nlimbs = pow5_len;
1265 /* Multiply m with pow5. No division needed. */
1266 z_memory = multiply (m, pow5, &z);
1270 /* Divide m by pow5 and round. */
1271 z_memory = divide (m, pow5, &z);
1276 pow5.limbs = pow5_ptr;
1277 pow5.nlimbs = pow5_len;
1281 Multiply m with pow5, then divide by 2^|s|. */
1285 tmp_memory = multiply (m, pow5, &numerator);
1286 if (tmp_memory == NULL)
1292 /* Construct 2^|s|. */
1294 mp_limb_t *ptr = pow5_ptr + pow5_len;
1296 for (i = 0; i < s_limbs; i++)
1298 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1299 denominator.limbs = ptr;
1300 denominator.nlimbs = s_limbs + 1;
1302 z_memory = divide (numerator, denominator, &z);
1308 Multiply m with 2^s, then divide by pow5. */
1311 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1312 * sizeof (mp_limb_t));
1313 if (num_ptr == NULL)
1320 mp_limb_t *destptr = num_ptr;
1323 for (i = 0; i < s_limbs; i++)
1328 const mp_limb_t *sourceptr = m.limbs;
1329 mp_twolimb_t accu = 0;
1331 for (count = m.nlimbs; count > 0; count--)
1333 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1334 *destptr++ = (mp_limb_t) accu;
1335 accu = accu >> GMP_LIMB_BITS;
1338 *destptr++ = (mp_limb_t) accu;
1342 const mp_limb_t *sourceptr = m.limbs;
1344 for (count = m.nlimbs; count > 0; count--)
1345 *destptr++ = *sourceptr++;
1347 numerator.limbs = num_ptr;
1348 numerator.nlimbs = destptr - num_ptr;
1350 z_memory = divide (numerator, pow5, &z);
1357 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1359 if (z_memory == NULL)
1361 digits = convert_to_decimal (z, extra_zeroes);
1366 # if NEED_PRINTF_LONG_DOUBLE
1368 /* Assuming x is finite and >= 0, and n is an integer:
1369 Returns the decimal representation of round (x * 10^n).
1370 Return the allocated memory - containing the decimal digits in low-to-high
1371 order, terminated with a NUL character - in case of success, NULL in case
1372 of memory allocation failure. */
1374 scale10_round_decimal_long_double (long double x, int n)
1378 void *memory = decode_long_double (x, &e, &m);
1379 return scale10_round_decimal_decoded (e, m, memory, n);
1384 # if NEED_PRINTF_DOUBLE
1386 /* Assuming x is finite and >= 0, and n is an integer:
1387 Returns the decimal representation of round (x * 10^n).
1388 Return the allocated memory - containing the decimal digits in low-to-high
1389 order, terminated with a NUL character - in case of success, NULL in case
1390 of memory allocation failure. */
1392 scale10_round_decimal_double (double x, int n)
1396 void *memory = decode_double (x, &e, &m);
1397 return scale10_round_decimal_decoded (e, m, memory, n);
1402 # if NEED_PRINTF_LONG_DOUBLE
1404 /* Assuming x is finite and > 0:
1405 Return an approximation for n with 10^n <= x < 10^(n+1).
1406 The approximation is usually the right n, but may be off by 1 sometimes. */
1408 floorlog10l (long double x)
1415 /* Split into exponential part and mantissa. */
1416 y = frexpl (x, &exp);
1417 if (!(y >= 0.0L && y < 1.0L))
1423 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1425 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1426 exp -= GMP_LIMB_BITS;
1428 if (y < (1.0L / (1 << 16)))
1430 y *= 1.0L * (1 << 16);
1433 if (y < (1.0L / (1 << 8)))
1435 y *= 1.0L * (1 << 8);
1438 if (y < (1.0L / (1 << 4)))
1440 y *= 1.0L * (1 << 4);
1443 if (y < (1.0L / (1 << 2)))
1445 y *= 1.0L * (1 << 2);
1448 if (y < (1.0L / (1 << 1)))
1450 y *= 1.0L * (1 << 1);
1454 if (!(y >= 0.5L && y < 1.0L))
1456 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1459 if (z < 0.70710678118654752444)
1461 z *= 1.4142135623730950488;
1464 if (z < 0.8408964152537145431)
1466 z *= 1.1892071150027210667;
1469 if (z < 0.91700404320467123175)
1471 z *= 1.0905077326652576592;
1474 if (z < 0.9576032806985736469)
1476 z *= 1.0442737824274138403;
1479 /* Now 0.95 <= z <= 1.01. */
1481 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1482 Four terms are enough to get an approximation with error < 10^-7. */
1483 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1484 /* Finally multiply with log(2)/log(10), yields an approximation for
1486 l *= 0.30102999566398119523;
1487 /* Round down to the next integer. */
1488 return (int) l + (l < 0 ? -1 : 0);
1493 # if NEED_PRINTF_DOUBLE
1495 /* Assuming x is finite and > 0:
1496 Return an approximation for n with 10^n <= x < 10^(n+1).
1497 The approximation is usually the right n, but may be off by 1 sometimes. */
1499 floorlog10 (double x)
1506 /* Split into exponential part and mantissa. */
1507 y = frexp (x, &exp);
1508 if (!(y >= 0.0 && y < 1.0))
1514 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1516 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1517 exp -= GMP_LIMB_BITS;
1519 if (y < (1.0 / (1 << 16)))
1521 y *= 1.0 * (1 << 16);
1524 if (y < (1.0 / (1 << 8)))
1526 y *= 1.0 * (1 << 8);
1529 if (y < (1.0 / (1 << 4)))
1531 y *= 1.0 * (1 << 4);
1534 if (y < (1.0 / (1 << 2)))
1536 y *= 1.0 * (1 << 2);
1539 if (y < (1.0 / (1 << 1)))
1541 y *= 1.0 * (1 << 1);
1545 if (!(y >= 0.5 && y < 1.0))
1547 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1550 if (z < 0.70710678118654752444)
1552 z *= 1.4142135623730950488;
1555 if (z < 0.8408964152537145431)
1557 z *= 1.1892071150027210667;
1560 if (z < 0.91700404320467123175)
1562 z *= 1.0905077326652576592;
1565 if (z < 0.9576032806985736469)
1567 z *= 1.0442737824274138403;
1570 /* Now 0.95 <= z <= 1.01. */
1572 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1573 Four terms are enough to get an approximation with error < 10^-7. */
1574 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1575 /* Finally multiply with log(2)/log(10), yields an approximation for
1577 l *= 0.30102999566398119523;
1578 /* Round down to the next integer. */
1579 return (int) l + (l < 0 ? -1 : 0);
1584 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1585 a single '1' digit. */
1587 is_borderline (const char *digits, size_t precision)
1589 for (; precision > 0; precision--, digits++)
1595 return *digits == '\0';
1600 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF
1602 /* Use a different function name, to make it possible that the 'wchar_t'
1603 parametrization and the 'char' parametrization get compiled in the same
1604 translation unit. */
1605 # if WIDE_CHAR_VERSION
1606 # define MAX_ROOM_NEEDED wmax_room_needed
1608 # define MAX_ROOM_NEEDED max_room_needed
1611 /* Returns the number of TCHAR_T units needed as temporary space for the result
1612 of sprintf or SNPRINTF of a single conversion directive. */
1614 MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
1615 arg_type type, int flags, size_t width, int has_precision,
1616 size_t precision, int pad_ourselves)
1622 case 'd': case 'i': case 'u':
1623 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1625 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1626 * 0.30103 /* binary -> decimal */
1628 + 1; /* turn floor into ceil */
1629 else if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1631 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1632 * 0.30103 /* binary -> decimal */
1634 + 1; /* turn floor into ceil */
1637 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1638 * 0.30103 /* binary -> decimal */
1640 + 1; /* turn floor into ceil */
1641 if (tmp_length < precision)
1642 tmp_length = precision;
1643 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1644 tmp_length = xsum (tmp_length, tmp_length);
1645 /* Add 1, to account for a leading sign. */
1646 tmp_length = xsum (tmp_length, 1);
1650 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1652 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1653 * 0.333334 /* binary -> octal */
1655 + 1; /* turn floor into ceil */
1656 else if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1658 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1659 * 0.333334 /* binary -> octal */
1661 + 1; /* turn floor into ceil */
1664 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1665 * 0.333334 /* binary -> octal */
1667 + 1; /* turn floor into ceil */
1668 if (tmp_length < precision)
1669 tmp_length = precision;
1670 /* Add 1, to account for a leading sign. */
1671 tmp_length = xsum (tmp_length, 1);
1675 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1677 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1678 * 0.25 /* binary -> hexadecimal */
1680 + 1; /* turn floor into ceil */
1681 else if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1683 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1684 * 0.25 /* binary -> hexadecimal */
1686 + 1; /* turn floor into ceil */
1689 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1690 * 0.25 /* binary -> hexadecimal */
1692 + 1; /* turn floor into ceil */
1693 if (tmp_length < precision)
1694 tmp_length = precision;
1695 /* Add 2, to account for a leading sign or alternate form. */
1696 tmp_length = xsum (tmp_length, 2);
1700 if (type == TYPE_LONGDOUBLE)
1702 (unsigned int) (LDBL_MAX_EXP
1703 * 0.30103 /* binary -> decimal */
1704 * 2 /* estimate for FLAG_GROUP */
1706 + 1 /* turn floor into ceil */
1707 + 10; /* sign, decimal point etc. */
1710 (unsigned int) (DBL_MAX_EXP
1711 * 0.30103 /* binary -> decimal */
1712 * 2 /* estimate for FLAG_GROUP */
1714 + 1 /* turn floor into ceil */
1715 + 10; /* sign, decimal point etc. */
1716 tmp_length = xsum (tmp_length, precision);
1719 case 'e': case 'E': case 'g': case 'G':
1721 12; /* sign, decimal point, exponent etc. */
1722 tmp_length = xsum (tmp_length, precision);
1726 if (type == TYPE_LONGDOUBLE)
1728 (unsigned int) (LDBL_DIG
1729 * 0.831 /* decimal -> hexadecimal */
1731 + 1; /* turn floor into ceil */
1734 (unsigned int) (DBL_DIG
1735 * 0.831 /* decimal -> hexadecimal */
1737 + 1; /* turn floor into ceil */
1738 if (tmp_length < precision)
1739 tmp_length = precision;
1740 /* Account for sign, decimal point etc. */
1741 tmp_length = xsum (tmp_length, 12);
1745 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
1746 if (type == TYPE_WIDE_CHAR)
1748 tmp_length = MB_CUR_MAX;
1749 # if ENABLE_WCHAR_FALLBACK
1750 if (tmp_length < (sizeof (wchar_t) > 2 ? 10 : 6))
1751 tmp_length = (sizeof (wchar_t) > 2 ? 10 : 6);
1761 if (type == TYPE_WIDE_STRING)
1763 # if WIDE_CHAR_VERSION
1764 /* ISO C says about %ls in fwprintf:
1765 "If the precision is not specified or is greater than the size
1766 of the array, the array shall contain a null wide character."
1767 So if there is a precision, we must not use wcslen. */
1768 const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
1771 tmp_length = local_wcsnlen (arg, precision);
1773 tmp_length = local_wcslen (arg);
1775 /* ISO C says about %ls in fprintf:
1776 "If a precision is specified, no more than that many bytes are
1777 written (including shift sequences, if any), and the array
1778 shall contain a null wide character if, to equal the multibyte
1779 character sequence length given by the precision, the function
1780 would need to access a wide character one past the end of the
1782 So if there is a precision, we must not use wcslen. */
1783 /* This case has already been handled separately in VASNPRINTF. */
1790 # if WIDE_CHAR_VERSION
1791 /* ISO C says about %s in fwprintf:
1792 "If the precision is not specified or is greater than the size
1793 of the converted array, the converted array shall contain a
1794 null wide character."
1795 So if there is a precision, we must not use strlen. */
1796 /* This case has already been handled separately in VASNPRINTF. */
1799 /* ISO C says about %s in fprintf:
1800 "If the precision is not specified or greater than the size of
1801 the array, the array shall contain a null character."
1802 So if there is a precision, we must not use strlen. */
1803 const char *arg = ap->arg[arg_index].a.a_string;
1806 tmp_length = local_strnlen (arg, precision);
1808 tmp_length = strlen (arg);
1815 (unsigned int) (sizeof (void *) * CHAR_BIT
1816 * 0.25 /* binary -> hexadecimal */
1818 + 1 /* turn floor into ceil */
1819 + 2; /* account for leading 0x */
1828 # if ENABLE_UNISTDIO
1829 /* Padding considers the number of characters, therefore the number of
1830 elements after padding may be
1831 > max (tmp_length, width)
1833 <= tmp_length + width. */
1834 tmp_length = xsum (tmp_length, width);
1836 /* Padding considers the number of elements, says POSIX. */
1837 if (tmp_length < width)
1842 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1850 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1851 const FCHAR_T *format, va_list args)
1856 if (PRINTF_PARSE (format, &d, &a) < 0)
1857 /* errno is already set. */
1860 /* Frees the memory allocated by this function. Preserves errno. */
1862 if (d.dir != d.direct_alloc_dir) \
1864 if (a.arg != a.direct_alloc_arg) \
1867 if (PRINTF_FETCHARGS (args, &a) < 0)
1875 size_t buf_neededlength;
1877 TCHAR_T *buf_malloced;
1881 /* Output string accumulator. */
1886 /* Allocate a small buffer that will hold a directive passed to
1887 sprintf or snprintf. */
1889 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1891 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1893 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1894 buf_malloced = NULL;
1899 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1900 if (size_overflow_p (buf_memsize))
1901 goto out_of_memory_1;
1902 buf = (TCHAR_T *) malloc (buf_memsize);
1904 goto out_of_memory_1;
1908 if (resultbuf != NULL)
1911 allocated = *lengthp;
1920 result is either == resultbuf or == NULL or malloc-allocated.
1921 If length > 0, then result != NULL. */
1923 /* Ensures that allocated >= needed. Aborts through a jump to
1924 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1925 #define ENSURE_ALLOCATION_ELSE(needed, oom_statement) \
1926 if ((needed) > allocated) \
1928 size_t memory_size; \
1931 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1932 if ((needed) > allocated) \
1933 allocated = (needed); \
1934 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1935 if (size_overflow_p (memory_size)) \
1937 if (result == resultbuf || result == NULL) \
1938 memory = (DCHAR_T *) malloc (memory_size); \
1940 memory = (DCHAR_T *) realloc (result, memory_size); \
1941 if (memory == NULL) \
1943 if (result == resultbuf && length > 0) \
1944 DCHAR_CPY (memory, result, length); \
1947 #define ENSURE_ALLOCATION(needed) \
1948 ENSURE_ALLOCATION_ELSE((needed), goto out_of_memory; )
1950 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1952 if (cp != dp->dir_start)
1954 size_t n = dp->dir_start - cp;
1955 size_t augmented_length = xsum (length, n);
1957 ENSURE_ALLOCATION (augmented_length);
1958 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1959 need that the format string contains only ASCII characters
1960 if FCHAR_T and DCHAR_T are not the same type. */
1961 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1963 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1964 length = augmented_length;
1969 result[length++] = *cp++;
1976 /* Execute a single directive. */
1977 if (dp->conversion == '%')
1979 size_t augmented_length;
1981 if (!(dp->arg_index == ARG_NONE))
1983 augmented_length = xsum (length, 1);
1984 ENSURE_ALLOCATION (augmented_length);
1985 result[length] = '%';
1986 length = augmented_length;
1990 if (!(dp->arg_index != ARG_NONE))
1993 if (dp->conversion == 'n')
1995 switch (a.arg[dp->arg_index].type)
1997 case TYPE_COUNT_SCHAR_POINTER:
1998 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
2000 case TYPE_COUNT_SHORT_POINTER:
2001 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
2003 case TYPE_COUNT_INT_POINTER:
2004 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
2006 case TYPE_COUNT_LONGINT_POINTER:
2007 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
2009 case TYPE_COUNT_LONGLONGINT_POINTER:
2010 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
2017 /* The unistdio extensions. */
2018 else if (dp->conversion == 'U')
2020 arg_type type = a.arg[dp->arg_index].type;
2021 int flags = dp->flags;
2029 if (dp->width_start != dp->width_end)
2031 if (dp->width_arg_index != ARG_NONE)
2035 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2037 arg = a.arg[dp->width_arg_index].a.a_int;
2041 /* "A negative field width is taken as a '-' flag
2042 followed by a positive field width." */
2049 const FCHAR_T *digitp = dp->width_start;
2052 width = xsum (xtimes (width, 10), *digitp++ - '0');
2053 while (digitp != dp->width_end);
2060 if (dp->precision_start != dp->precision_end)
2062 if (dp->precision_arg_index != ARG_NONE)
2066 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2068 arg = a.arg[dp->precision_arg_index].a.a_int;
2069 /* "A negative precision is taken as if the precision
2079 const FCHAR_T *digitp = dp->precision_start + 1;
2082 while (digitp != dp->precision_end)
2083 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2090 case TYPE_U8_STRING:
2092 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
2093 const uint8_t *arg_end;
2098 /* Use only PRECISION characters, from the left. */
2101 for (; precision > 0; precision--)
2103 int count = u8_strmblen (arg_end);
2108 if (!(result == resultbuf || result == NULL))
2110 if (buf_malloced != NULL)
2111 free (buf_malloced);
2122 /* Use the entire string, and count the number of
2128 int count = u8_strmblen (arg_end);
2133 if (!(result == resultbuf || result == NULL))
2135 if (buf_malloced != NULL)
2136 free (buf_malloced);
2147 /* Use the entire string. */
2148 arg_end = arg + u8_strlen (arg);
2149 /* The number of characters doesn't matter. */
2153 if (characters < width && !(dp->flags & FLAG_LEFT))
2155 size_t n = width - characters;
2156 ENSURE_ALLOCATION (xsum (length, n));
2157 DCHAR_SET (result + length, ' ', n);
2161 # if DCHAR_IS_UINT8_T
2163 size_t n = arg_end - arg;
2164 ENSURE_ALLOCATION (xsum (length, n));
2165 DCHAR_CPY (result + length, arg, n);
2170 DCHAR_T *converted = result + length;
2171 size_t converted_len = allocated - length;
2173 /* Convert from UTF-8 to locale encoding. */
2175 u8_conv_to_encoding (locale_charset (),
2176 iconveh_question_mark,
2177 arg, arg_end - arg, NULL,
2178 converted, &converted_len);
2180 /* Convert from UTF-8 to UTF-16/UTF-32. */
2182 U8_TO_DCHAR (arg, arg_end - arg,
2183 converted, &converted_len);
2185 if (converted == NULL)
2187 if (!(result == resultbuf || result == NULL))
2189 if (buf_malloced != NULL)
2190 free (buf_malloced);
2194 if (converted != result + length)
2196 ENSURE_ALLOCATION_ELSE (xsum (length, converted_len),
2197 { free (converted); goto out_of_memory; });
2198 DCHAR_CPY (result + length, converted, converted_len);
2201 length += converted_len;
2205 if (characters < width && (dp->flags & FLAG_LEFT))
2207 size_t n = width - characters;
2208 ENSURE_ALLOCATION (xsum (length, n));
2209 DCHAR_SET (result + length, ' ', n);
2215 case TYPE_U16_STRING:
2217 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
2218 const uint16_t *arg_end;
2223 /* Use only PRECISION characters, from the left. */
2226 for (; precision > 0; precision--)
2228 int count = u16_strmblen (arg_end);
2233 if (!(result == resultbuf || result == NULL))
2235 if (buf_malloced != NULL)
2236 free (buf_malloced);
2247 /* Use the entire string, and count the number of
2253 int count = u16_strmblen (arg_end);
2258 if (!(result == resultbuf || result == NULL))
2260 if (buf_malloced != NULL)
2261 free (buf_malloced);
2272 /* Use the entire string. */
2273 arg_end = arg + u16_strlen (arg);
2274 /* The number of characters doesn't matter. */
2278 if (characters < width && !(dp->flags & FLAG_LEFT))
2280 size_t n = width - characters;
2281 ENSURE_ALLOCATION (xsum (length, n));
2282 DCHAR_SET (result + length, ' ', n);
2286 # if DCHAR_IS_UINT16_T
2288 size_t n = arg_end - arg;
2289 ENSURE_ALLOCATION (xsum (length, n));
2290 DCHAR_CPY (result + length, arg, n);
2295 DCHAR_T *converted = result + length;
2296 size_t converted_len = allocated - length;
2298 /* Convert from UTF-16 to locale encoding. */
2300 u16_conv_to_encoding (locale_charset (),
2301 iconveh_question_mark,
2302 arg, arg_end - arg, NULL,
2303 converted, &converted_len);
2305 /* Convert from UTF-16 to UTF-8/UTF-32. */
2307 U16_TO_DCHAR (arg, arg_end - arg,
2308 converted, &converted_len);
2310 if (converted == NULL)
2312 if (!(result == resultbuf || result == NULL))
2314 if (buf_malloced != NULL)
2315 free (buf_malloced);
2319 if (converted != result + length)
2321 ENSURE_ALLOCATION_ELSE (xsum (length, converted_len),
2322 { free (converted); goto out_of_memory; });
2323 DCHAR_CPY (result + length, converted, converted_len);
2326 length += converted_len;
2330 if (characters < width && (dp->flags & FLAG_LEFT))
2332 size_t n = width - characters;
2333 ENSURE_ALLOCATION (xsum (length, n));
2334 DCHAR_SET (result + length, ' ', n);
2340 case TYPE_U32_STRING:
2342 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
2343 const uint32_t *arg_end;
2348 /* Use only PRECISION characters, from the left. */
2351 for (; precision > 0; precision--)
2353 int count = u32_strmblen (arg_end);
2358 if (!(result == resultbuf || result == NULL))
2360 if (buf_malloced != NULL)
2361 free (buf_malloced);
2372 /* Use the entire string, and count the number of
2378 int count = u32_strmblen (arg_end);
2383 if (!(result == resultbuf || result == NULL))
2385 if (buf_malloced != NULL)
2386 free (buf_malloced);
2397 /* Use the entire string. */
2398 arg_end = arg + u32_strlen (arg);
2399 /* The number of characters doesn't matter. */
2403 if (characters < width && !(dp->flags & FLAG_LEFT))
2405 size_t n = width - characters;
2406 ENSURE_ALLOCATION (xsum (length, n));
2407 DCHAR_SET (result + length, ' ', n);
2411 # if DCHAR_IS_UINT32_T
2413 size_t n = arg_end - arg;
2414 ENSURE_ALLOCATION (xsum (length, n));
2415 DCHAR_CPY (result + length, arg, n);
2420 DCHAR_T *converted = result + length;
2421 size_t converted_len = allocated - length;
2423 /* Convert from UTF-32 to locale encoding. */
2425 u32_conv_to_encoding (locale_charset (),
2426 iconveh_question_mark,
2427 arg, arg_end - arg, NULL,
2428 converted, &converted_len);
2430 /* Convert from UTF-32 to UTF-8/UTF-16. */
2432 U32_TO_DCHAR (arg, arg_end - arg,
2433 converted, &converted_len);
2435 if (converted == NULL)
2437 if (!(result == resultbuf || result == NULL))
2439 if (buf_malloced != NULL)
2440 free (buf_malloced);
2444 if (converted != result + length)
2446 ENSURE_ALLOCATION_ELSE (xsum (length, converted_len),
2447 { free (converted); goto out_of_memory; });
2448 DCHAR_CPY (result + length, converted, converted_len);
2451 length += converted_len;
2455 if (characters < width && (dp->flags & FLAG_LEFT))
2457 size_t n = width - characters;
2458 ENSURE_ALLOCATION (xsum (length, n));
2459 DCHAR_SET (result + length, ' ', n);
2470 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL) || ENABLE_WCHAR_FALLBACK) && HAVE_WCHAR_T
2471 else if (dp->conversion == 's'
2472 # if WIDE_CHAR_VERSION
2473 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2475 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2479 /* The normal handling of the 's' directive below requires
2480 allocating a temporary buffer. The determination of its
2481 length (tmp_length), in the case when a precision is
2482 specified, below requires a conversion between a char[]
2483 string and a wchar_t[] wide string. It could be done, but
2484 we have no guarantee that the implementation of sprintf will
2485 use the exactly same algorithm. Without this guarantee, it
2486 is possible to have buffer overrun bugs. In order to avoid
2487 such bugs, we implement the entire processing of the 's'
2488 directive ourselves. */
2489 int flags = dp->flags;
2497 if (dp->width_start != dp->width_end)
2499 if (dp->width_arg_index != ARG_NONE)
2503 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2505 arg = a.arg[dp->width_arg_index].a.a_int;
2509 /* "A negative field width is taken as a '-' flag
2510 followed by a positive field width." */
2517 const FCHAR_T *digitp = dp->width_start;
2520 width = xsum (xtimes (width, 10), *digitp++ - '0');
2521 while (digitp != dp->width_end);
2528 if (dp->precision_start != dp->precision_end)
2530 if (dp->precision_arg_index != ARG_NONE)
2534 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2536 arg = a.arg[dp->precision_arg_index].a.a_int;
2537 /* "A negative precision is taken as if the precision
2547 const FCHAR_T *digitp = dp->precision_start + 1;
2550 while (digitp != dp->precision_end)
2551 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2556 # if WIDE_CHAR_VERSION
2557 /* %s in vasnwprintf. See the specification of fwprintf. */
2559 const char *arg = a.arg[dp->arg_index].a.a_string;
2560 const char *arg_end;
2565 /* Use only as many bytes as needed to produce PRECISION
2566 wide characters, from the left. */
2569 memset (&state, '\0', sizeof (mbstate_t));
2573 for (; precision > 0; precision--)
2577 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2579 count = mblen (arg_end, MB_CUR_MAX);
2582 /* Found the terminating NUL. */
2586 /* Invalid or incomplete multibyte character. */
2587 if (!(result == resultbuf || result == NULL))
2589 if (buf_malloced != NULL)
2590 free (buf_malloced);
2601 /* Use the entire string, and count the number of wide
2605 memset (&state, '\0', sizeof (mbstate_t));
2613 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2615 count = mblen (arg_end, MB_CUR_MAX);
2618 /* Found the terminating NUL. */
2622 /* Invalid or incomplete multibyte character. */
2623 if (!(result == resultbuf || result == NULL))
2625 if (buf_malloced != NULL)
2626 free (buf_malloced);
2637 /* Use the entire string. */
2638 arg_end = arg + strlen (arg);
2639 /* The number of characters doesn't matter. */
2643 if (characters < width && !(dp->flags & FLAG_LEFT))
2645 size_t n = width - characters;
2646 ENSURE_ALLOCATION (xsum (length, n));
2647 DCHAR_SET (result + length, ' ', n);
2651 if (has_precision || has_width)
2653 /* We know the number of wide characters in advance. */
2657 memset (&state, '\0', sizeof (mbstate_t));
2659 ENSURE_ALLOCATION (xsum (length, characters));
2660 for (remaining = characters; remaining > 0; remaining--)
2665 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2667 count = mbtowc (&wc, arg, arg_end - arg);
2670 /* mbrtowc not consistent with mbrlen, or mbtowc
2671 not consistent with mblen. */
2673 result[length++] = wc;
2676 if (!(arg == arg_end))
2683 memset (&state, '\0', sizeof (mbstate_t));
2685 while (arg < arg_end)
2690 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2692 count = mbtowc (&wc, arg, arg_end - arg);
2695 /* mbrtowc not consistent with mbrlen, or mbtowc
2696 not consistent with mblen. */
2698 ENSURE_ALLOCATION (xsum (length, 1));
2699 result[length++] = wc;
2704 if (characters < width && (dp->flags & FLAG_LEFT))
2706 size_t n = width - characters;
2707 ENSURE_ALLOCATION (xsum (length, n));
2708 DCHAR_SET (result + length, ' ', n);
2713 /* %ls in vasnprintf. See the specification of fprintf. */
2715 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2716 const wchar_t *arg_end;
2718 # if !DCHAR_IS_TCHAR
2719 /* This code assumes that TCHAR_T is 'char'. */
2720 verify (sizeof (TCHAR_T) == 1);
2729 /* Use only as many wide characters as needed to produce
2730 at most PRECISION bytes, from the left. */
2731 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2733 memset (&state, '\0', sizeof (mbstate_t));
2737 while (precision > 0)
2739 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2743 /* Found the terminating null wide character. */
2745 count = local_wcrtomb (cbuf, *arg_end, &state);
2748 /* Cannot convert. */
2749 if (!(result == resultbuf || result == NULL))
2751 if (buf_malloced != NULL)
2752 free (buf_malloced);
2757 if (precision < (unsigned int) count)
2760 characters += count;
2770 /* Use the entire string, and count the number of
2772 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2774 memset (&state, '\0', sizeof (mbstate_t));
2780 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2784 /* Found the terminating null wide character. */
2786 count = local_wcrtomb (cbuf, *arg_end, &state);
2789 /* Cannot convert. */
2790 if (!(result == resultbuf || result == NULL))
2792 if (buf_malloced != NULL)
2793 free (buf_malloced);
2799 characters += count;
2805 /* Use the entire string. */
2806 arg_end = arg + local_wcslen (arg);
2807 /* The number of bytes doesn't matter. */
2812 # if !DCHAR_IS_TCHAR
2813 /* Convert the string into a piece of temporary memory. */
2814 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2818 TCHAR_T *tmpptr = tmpsrc;
2820 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2822 memset (&state, '\0', sizeof (mbstate_t));
2824 for (remaining = characters; remaining > 0; )
2826 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2831 count = local_wcrtomb (cbuf, *arg, &state);
2833 /* Inconsistency. */
2835 memcpy (tmpptr, cbuf, count);
2840 if (!(arg == arg_end))
2844 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2846 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2847 iconveh_question_mark,
2854 if (!(result == resultbuf || result == NULL))
2856 if (buf_malloced != NULL)
2857 free (buf_malloced);
2866 # if ENABLE_UNISTDIO
2867 /* Outside POSIX, it's preferable to compare the width
2868 against the number of _characters_ of the converted
2870 w = DCHAR_MBSNLEN (result + length, characters);
2872 /* The width is compared against the number of _bytes_
2873 of the converted value, says POSIX. */
2878 /* w doesn't matter. */
2881 if (w < width && !(dp->flags & FLAG_LEFT))
2883 size_t n = width - w;
2884 ENSURE_ALLOCATION (xsum (length, n));
2885 DCHAR_SET (result + length, ' ', n);
2890 if (has_precision || has_width)
2892 /* We know the number of bytes in advance. */
2894 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2896 memset (&state, '\0', sizeof (mbstate_t));
2898 ENSURE_ALLOCATION (xsum (length, characters));
2899 for (remaining = characters; remaining > 0; )
2901 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2906 count = local_wcrtomb (cbuf, *arg, &state);
2908 /* Inconsistency. */
2910 memcpy (result + length, cbuf, count);
2915 if (!(arg == arg_end))
2920 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2922 memset (&state, '\0', sizeof (mbstate_t));
2924 while (arg < arg_end)
2926 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2931 count = local_wcrtomb (cbuf, *arg, &state);
2934 /* Cannot convert. */
2935 if (!(result == resultbuf || result == NULL))
2937 if (buf_malloced != NULL)
2938 free (buf_malloced);
2943 ENSURE_ALLOCATION (xsum (length, count));
2944 memcpy (result + length, cbuf, count);
2950 ENSURE_ALLOCATION_ELSE (xsum (length, tmpdst_len),
2951 { free (tmpdst); goto out_of_memory; });
2952 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2954 length += tmpdst_len;
2957 if (w < width && (dp->flags & FLAG_LEFT))
2959 size_t n = width - w;
2960 ENSURE_ALLOCATION (xsum (length, n));
2961 DCHAR_SET (result + length, ' ', n);
2968 #if ENABLE_WCHAR_FALLBACK && HAVE_WINT_T && !WIDE_CHAR_VERSION
2969 else if (dp->conversion == 'c'
2970 && a.arg[dp->arg_index].type == TYPE_WIDE_CHAR)
2972 /* Implement the 'lc' directive ourselves, in order to provide
2973 the fallback that avoids EILSEQ. */
2974 int flags = dp->flags;
2980 if (dp->width_start != dp->width_end)
2982 if (dp->width_arg_index != ARG_NONE)
2986 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2988 arg = a.arg[dp->width_arg_index].a.a_int;
2992 /* "A negative field width is taken as a '-' flag
2993 followed by a positive field width." */
3000 const FCHAR_T *digitp = dp->width_start;
3003 width = xsum (xtimes (width, 10), *digitp++ - '0');
3004 while (digitp != dp->width_end);
3009 /* %lc in vasnprintf. See the specification of fprintf. */
3011 wchar_t arg = (wchar_t) a.arg[dp->arg_index].a.a_wide_char;
3013 # if !DCHAR_IS_TCHAR
3014 /* This code assumes that TCHAR_T is 'char'. */
3015 verify (sizeof (TCHAR_T) == 1);
3016 TCHAR_T tmpsrc[64]; /* Assume MB_CUR_MAX <= 64. */
3026 /* Count the number of bytes. */
3030 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3032 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3034 memset (&state, '\0', sizeof (mbstate_t));
3037 count = local_wcrtomb (cbuf, arg, &state);
3039 /* Inconsistency. */
3047 /* The number of bytes doesn't matter. */
3052 # if !DCHAR_IS_TCHAR
3053 /* Convert the string into a piece of temporary memory. */
3054 if (characters > 0) /* implies arg != 0 */
3056 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3058 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3060 memset (&state, '\0', sizeof (mbstate_t));
3063 count = local_wcrtomb (cbuf, arg, &state);
3065 /* Inconsistency. */
3067 memcpy (tmpsrc, cbuf, count);
3070 /* Convert from TCHAR_T[] to DCHAR_T[]. */
3072 DCHAR_CONV_FROM_ENCODING (locale_charset (),
3073 iconveh_question_mark,
3079 if (!(result == resultbuf || result == NULL))
3081 if (buf_malloced != NULL)
3082 free (buf_malloced);
3090 # if ENABLE_UNISTDIO
3091 /* Outside POSIX, it's preferable to compare the width
3092 against the number of _characters_ of the converted
3094 w = DCHAR_MBSNLEN (result + length, characters);
3096 /* The width is compared against the number of _bytes_
3097 of the converted value, says POSIX. */
3102 /* w doesn't matter. */
3105 if (w < width && !(dp->flags & FLAG_LEFT))
3107 size_t n = width - w;
3108 ENSURE_ALLOCATION (xsum (length, n));
3109 DCHAR_SET (result + length, ' ', n);
3116 /* We know the number of bytes in advance. */
3117 ENSURE_ALLOCATION (xsum (length, characters));
3118 if (characters > 0) /* implies arg != 0 */
3121 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3123 memset (&state, '\0', sizeof (mbstate_t));
3126 count = local_wcrtomb (result + length, arg, &state);
3128 /* Inconsistency. */
3137 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3139 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3141 memset (&state, '\0', sizeof (mbstate_t));
3144 count = local_wcrtomb (cbuf, arg, &state);
3146 /* Inconsistency. */
3148 ENSURE_ALLOCATION (xsum (length, count));
3149 memcpy (result + length, cbuf, count);
3154 ENSURE_ALLOCATION_ELSE (xsum (length, tmpdst_len),
3155 { free (tmpdst); goto out_of_memory; });
3156 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
3158 length += tmpdst_len;
3161 if (w < width && (dp->flags & FLAG_LEFT))
3163 size_t n = width - w;
3164 ENSURE_ALLOCATION (xsum (length, n));
3165 DCHAR_SET (result + length, ' ', n);
3171 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
3172 else if ((dp->conversion == 'a' || dp->conversion == 'A')
3173 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
3175 # if NEED_PRINTF_DOUBLE
3176 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3178 # if NEED_PRINTF_LONG_DOUBLE
3179 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3185 arg_type type = a.arg[dp->arg_index].type;
3186 int flags = dp->flags;
3192 DCHAR_T tmpbuf[700];
3198 if (dp->width_start != dp->width_end)
3200 if (dp->width_arg_index != ARG_NONE)
3204 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3206 arg = a.arg[dp->width_arg_index].a.a_int;
3210 /* "A negative field width is taken as a '-' flag
3211 followed by a positive field width." */
3218 const FCHAR_T *digitp = dp->width_start;
3221 width = xsum (xtimes (width, 10), *digitp++ - '0');
3222 while (digitp != dp->width_end);
3228 if (dp->precision_start != dp->precision_end)
3230 if (dp->precision_arg_index != ARG_NONE)
3234 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3236 arg = a.arg[dp->precision_arg_index].a.a_int;
3237 /* "A negative precision is taken as if the precision
3247 const FCHAR_T *digitp = dp->precision_start + 1;
3250 while (digitp != dp->precision_end)
3251 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3256 /* Allocate a temporary buffer of sufficient size. */
3257 if (type == TYPE_LONGDOUBLE)
3259 (unsigned int) ((LDBL_DIG + 1)
3260 * 0.831 /* decimal -> hexadecimal */
3262 + 1; /* turn floor into ceil */
3265 (unsigned int) ((DBL_DIG + 1)
3266 * 0.831 /* decimal -> hexadecimal */
3268 + 1; /* turn floor into ceil */
3269 if (tmp_length < precision)
3270 tmp_length = precision;
3271 /* Account for sign, decimal point etc. */
3272 tmp_length = xsum (tmp_length, 12);
3274 if (tmp_length < width)
3277 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3279 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3283 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3285 if (size_overflow_p (tmp_memsize))
3286 /* Overflow, would lead to out of memory. */
3288 tmp = (DCHAR_T *) malloc (tmp_memsize);
3290 /* Out of memory. */
3296 if (type == TYPE_LONGDOUBLE)
3298 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
3299 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3303 if (dp->conversion == 'A')
3305 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3309 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3315 DECL_LONG_DOUBLE_ROUNDING
3317 BEGIN_LONG_DOUBLE_ROUNDING ();
3319 if (signbit (arg)) /* arg < 0.0L or negative zero */
3327 else if (flags & FLAG_SHOWSIGN)
3329 else if (flags & FLAG_SPACE)
3332 if (arg > 0.0L && arg + arg == arg)
3334 if (dp->conversion == 'A')
3336 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3340 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3346 long double mantissa;
3349 mantissa = printf_frexpl (arg, &exponent);
3357 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
3359 /* Round the mantissa. */
3360 long double tail = mantissa;
3363 for (q = precision; ; q--)
3365 int digit = (int) tail;
3369 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
3378 for (q = precision; q > 0; q--)
3384 *p++ = dp->conversion - 'A' + 'X';
3389 digit = (int) mantissa;
3392 if ((flags & FLAG_ALT)
3393 || mantissa > 0.0L || precision > 0)
3395 *p++ = decimal_point_char ();
3396 /* This loop terminates because we assume
3397 that FLT_RADIX is a power of 2. */
3398 while (mantissa > 0.0L)
3401 digit = (int) mantissa;
3406 : dp->conversion - 10);
3410 while (precision > 0)
3417 *p++ = dp->conversion - 'A' + 'P';
3418 # if WIDE_CHAR_VERSION
3420 static const wchar_t decimal_format[] =
3421 { '%', '+', 'd', '\0' };
3422 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3427 if (sizeof (DCHAR_T) == 1)
3429 sprintf ((char *) p, "%+d", exponent);
3437 sprintf (expbuf, "%+d", exponent);
3438 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3444 END_LONG_DOUBLE_ROUNDING ();
3452 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
3453 double arg = a.arg[dp->arg_index].a.a_double;
3457 if (dp->conversion == 'A')
3459 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3463 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3470 if (signbit (arg)) /* arg < 0.0 or negative zero */
3478 else if (flags & FLAG_SHOWSIGN)
3480 else if (flags & FLAG_SPACE)
3483 if (arg > 0.0 && arg + arg == arg)
3485 if (dp->conversion == 'A')
3487 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3491 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3500 mantissa = printf_frexp (arg, &exponent);
3508 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
3510 /* Round the mantissa. */
3511 double tail = mantissa;
3514 for (q = precision; ; q--)
3516 int digit = (int) tail;
3520 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
3529 for (q = precision; q > 0; q--)
3535 *p++ = dp->conversion - 'A' + 'X';
3540 digit = (int) mantissa;
3543 if ((flags & FLAG_ALT)
3544 || mantissa > 0.0 || precision > 0)
3546 *p++ = decimal_point_char ();
3547 /* This loop terminates because we assume
3548 that FLT_RADIX is a power of 2. */
3549 while (mantissa > 0.0)
3552 digit = (int) mantissa;
3557 : dp->conversion - 10);
3561 while (precision > 0)
3568 *p++ = dp->conversion - 'A' + 'P';
3569 # if WIDE_CHAR_VERSION
3571 static const wchar_t decimal_format[] =
3572 { '%', '+', 'd', '\0' };
3573 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3578 if (sizeof (DCHAR_T) == 1)
3580 sprintf ((char *) p, "%+d", exponent);
3588 sprintf (expbuf, "%+d", exponent);
3589 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3600 /* The generated string now extends from tmp to p, with the
3601 zero padding insertion point being at pad_ptr. */
3606 size_t pad = width - count;
3607 DCHAR_T *end = p + pad;
3609 if (flags & FLAG_LEFT)
3611 /* Pad with spaces on the right. */
3612 for (; pad > 0; pad--)
3615 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3617 /* Pad with zeroes. */
3622 for (; pad > 0; pad--)
3627 /* Pad with spaces on the left. */
3632 for (; pad > 0; pad--)
3641 if (count >= tmp_length)
3642 /* tmp_length was incorrectly calculated - fix the
3646 /* Make room for the result. */
3647 if (count >= allocated - length)
3649 size_t n = xsum (length, count);
3651 ENSURE_ALLOCATION (n);
3654 /* Append the result. */
3655 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3661 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3662 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3663 || dp->conversion == 'e' || dp->conversion == 'E'
3664 || dp->conversion == 'g' || dp->conversion == 'G'
3665 || dp->conversion == 'a' || dp->conversion == 'A')
3667 # if NEED_PRINTF_DOUBLE
3668 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3669 # elif NEED_PRINTF_INFINITE_DOUBLE
3670 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3671 /* The systems (mingw) which produce wrong output
3672 for Inf, -Inf, and NaN also do so for -0.0.
3673 Therefore we treat this case here as well. */
3674 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3676 # if NEED_PRINTF_LONG_DOUBLE
3677 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3678 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3679 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3680 /* Some systems produce wrong output for Inf,
3681 -Inf, and NaN. Some systems in this category
3682 (IRIX 5.3) also do so for -0.0. Therefore we
3683 treat this case here as well. */
3684 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3688 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3689 arg_type type = a.arg[dp->arg_index].type;
3691 int flags = dp->flags;
3697 DCHAR_T tmpbuf[700];
3703 if (dp->width_start != dp->width_end)
3705 if (dp->width_arg_index != ARG_NONE)
3709 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3711 arg = a.arg[dp->width_arg_index].a.a_int;
3715 /* "A negative field width is taken as a '-' flag
3716 followed by a positive field width." */
3723 const FCHAR_T *digitp = dp->width_start;
3726 width = xsum (xtimes (width, 10), *digitp++ - '0');
3727 while (digitp != dp->width_end);
3733 if (dp->precision_start != dp->precision_end)
3735 if (dp->precision_arg_index != ARG_NONE)
3739 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3741 arg = a.arg[dp->precision_arg_index].a.a_int;
3742 /* "A negative precision is taken as if the precision
3752 const FCHAR_T *digitp = dp->precision_start + 1;
3755 while (digitp != dp->precision_end)
3756 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3761 /* POSIX specifies the default precision to be 6 for %f, %F,
3762 %e, %E, but not for %g, %G. Implementations appear to use
3763 the same default precision also for %g, %G. But for %a, %A,
3764 the default precision is 0. */
3766 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3769 /* Allocate a temporary buffer of sufficient size. */
3770 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3771 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3772 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3773 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3774 # elif NEED_PRINTF_LONG_DOUBLE
3775 tmp_length = LDBL_DIG + 1;
3776 # elif NEED_PRINTF_DOUBLE
3777 tmp_length = DBL_DIG + 1;
3781 if (tmp_length < precision)
3782 tmp_length = precision;
3783 # if NEED_PRINTF_LONG_DOUBLE
3784 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3785 if (type == TYPE_LONGDOUBLE)
3787 if (dp->conversion == 'f' || dp->conversion == 'F')
3789 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3790 if (!(isnanl (arg) || arg + arg == arg))
3792 /* arg is finite and nonzero. */
3793 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3794 if (exponent >= 0 && tmp_length < exponent + precision)
3795 tmp_length = exponent + precision;
3799 # if NEED_PRINTF_DOUBLE
3800 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3801 if (type == TYPE_DOUBLE)
3803 if (dp->conversion == 'f' || dp->conversion == 'F')
3805 double arg = a.arg[dp->arg_index].a.a_double;
3806 if (!(isnand (arg) || arg + arg == arg))
3808 /* arg is finite and nonzero. */
3809 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3810 if (exponent >= 0 && tmp_length < exponent + precision)
3811 tmp_length = exponent + precision;
3815 /* Account for sign, decimal point etc. */
3816 tmp_length = xsum (tmp_length, 12);
3818 if (tmp_length < width)
3821 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3823 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3827 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3829 if (size_overflow_p (tmp_memsize))
3830 /* Overflow, would lead to out of memory. */
3832 tmp = (DCHAR_T *) malloc (tmp_memsize);
3834 /* Out of memory. */
3841 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3842 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3843 if (type == TYPE_LONGDOUBLE)
3846 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3850 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3852 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3856 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3862 DECL_LONG_DOUBLE_ROUNDING
3864 BEGIN_LONG_DOUBLE_ROUNDING ();
3866 if (signbit (arg)) /* arg < 0.0L or negative zero */
3874 else if (flags & FLAG_SHOWSIGN)
3876 else if (flags & FLAG_SPACE)
3879 if (arg > 0.0L && arg + arg == arg)
3881 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3883 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3887 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3892 # if NEED_PRINTF_LONG_DOUBLE
3895 if (dp->conversion == 'f' || dp->conversion == 'F')
3901 scale10_round_decimal_long_double (arg, precision);
3904 END_LONG_DOUBLE_ROUNDING ();
3907 ndigits = strlen (digits);
3909 if (ndigits > precision)
3913 *p++ = digits[ndigits];
3915 while (ndigits > precision);
3918 /* Here ndigits <= precision. */
3919 if ((flags & FLAG_ALT) || precision > 0)
3921 *p++ = decimal_point_char ();
3922 for (; precision > ndigits; precision--)
3927 *p++ = digits[ndigits];
3933 else if (dp->conversion == 'e' || dp->conversion == 'E')
3941 if ((flags & FLAG_ALT) || precision > 0)
3943 *p++ = decimal_point_char ();
3944 for (; precision > 0; precision--)
3955 exponent = floorlog10l (arg);
3960 scale10_round_decimal_long_double (arg,
3961 (int)precision - exponent);
3964 END_LONG_DOUBLE_ROUNDING ();
3967 ndigits = strlen (digits);
3969 if (ndigits == precision + 1)
3971 if (ndigits < precision
3972 || ndigits > precision + 2)
3973 /* The exponent was not guessed
3974 precisely enough. */
3977 /* None of two values of exponent is
3978 the right one. Prevent an endless
3982 if (ndigits == precision)
3988 /* Here ndigits = precision+1. */
3989 if (is_borderline (digits, precision))
3991 /* Maybe the exponent guess was too high
3992 and a smaller exponent can be reached
3993 by turning a 10...0 into 9...9x. */
3995 scale10_round_decimal_long_double (arg,
3996 (int)precision - exponent + 1);
3997 if (digits2 == NULL)
4000 END_LONG_DOUBLE_ROUNDING ();
4003 if (strlen (digits2) == precision + 1)
4012 /* Here ndigits = precision+1. */
4014 *p++ = digits[--ndigits];
4015 if ((flags & FLAG_ALT) || precision > 0)
4017 *p++ = decimal_point_char ();
4021 *p++ = digits[ndigits];
4028 *p++ = dp->conversion; /* 'e' or 'E' */
4029 # if WIDE_CHAR_VERSION
4031 static const wchar_t decimal_format[] =
4032 { '%', '+', '.', '2', 'd', '\0' };
4033 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4038 if (sizeof (DCHAR_T) == 1)
4040 sprintf ((char *) p, "%+.2d", exponent);
4048 sprintf (expbuf, "%+.2d", exponent);
4049 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4054 else if (dp->conversion == 'g' || dp->conversion == 'G')
4058 /* precision >= 1. */
4061 /* The exponent is 0, >= -4, < precision.
4062 Use fixed-point notation. */
4064 size_t ndigits = precision;
4065 /* Number of trailing zeroes that have to be
4068 (flags & FLAG_ALT ? 0 : precision - 1);
4072 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4074 *p++ = decimal_point_char ();
4075 while (ndigits > nzeroes)
4091 exponent = floorlog10l (arg);
4096 scale10_round_decimal_long_double (arg,
4097 (int)(precision - 1) - exponent);
4100 END_LONG_DOUBLE_ROUNDING ();
4103 ndigits = strlen (digits);
4105 if (ndigits == precision)
4107 if (ndigits < precision - 1
4108 || ndigits > precision + 1)
4109 /* The exponent was not guessed
4110 precisely enough. */
4113 /* None of two values of exponent is
4114 the right one. Prevent an endless
4118 if (ndigits < precision)
4124 /* Here ndigits = precision. */
4125 if (is_borderline (digits, precision - 1))
4127 /* Maybe the exponent guess was too high
4128 and a smaller exponent can be reached
4129 by turning a 10...0 into 9...9x. */
4131 scale10_round_decimal_long_double (arg,
4132 (int)(precision - 1) - exponent + 1);
4133 if (digits2 == NULL)
4136 END_LONG_DOUBLE_ROUNDING ();
4139 if (strlen (digits2) == precision)
4148 /* Here ndigits = precision. */
4150 /* Determine the number of trailing zeroes
4151 that have to be dropped. */
4153 if ((flags & FLAG_ALT) == 0)
4154 while (nzeroes < ndigits
4155 && digits[nzeroes] == '0')
4158 /* The exponent is now determined. */
4160 && exponent < (long)precision)
4162 /* Fixed-point notation:
4163 max(exponent,0)+1 digits, then the
4164 decimal point, then the remaining
4165 digits without trailing zeroes. */
4168 size_t ecount = exponent + 1;
4169 /* Note: count <= precision = ndigits. */
4170 for (; ecount > 0; ecount--)
4171 *p++ = digits[--ndigits];
4172 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4174 *p++ = decimal_point_char ();
4175 while (ndigits > nzeroes)
4178 *p++ = digits[ndigits];
4184 size_t ecount = -exponent - 1;
4186 *p++ = decimal_point_char ();
4187 for (; ecount > 0; ecount--)
4189 while (ndigits > nzeroes)
4192 *p++ = digits[ndigits];
4198 /* Exponential notation. */
4199 *p++ = digits[--ndigits];
4200 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4202 *p++ = decimal_point_char ();
4203 while (ndigits > nzeroes)
4206 *p++ = digits[ndigits];
4209 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4210 # if WIDE_CHAR_VERSION
4212 static const wchar_t decimal_format[] =
4213 { '%', '+', '.', '2', 'd', '\0' };
4214 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4219 if (sizeof (DCHAR_T) == 1)
4221 sprintf ((char *) p, "%+.2d", exponent);
4229 sprintf (expbuf, "%+.2d", exponent);
4230 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4242 /* arg is finite. */
4248 if (dp->conversion == 'f' || dp->conversion == 'F')
4251 if ((flags & FLAG_ALT) || precision > 0)
4253 *p++ = decimal_point_char ();
4254 for (; precision > 0; precision--)
4258 else if (dp->conversion == 'e' || dp->conversion == 'E')
4261 if ((flags & FLAG_ALT) || precision > 0)
4263 *p++ = decimal_point_char ();
4264 for (; precision > 0; precision--)
4267 *p++ = dp->conversion; /* 'e' or 'E' */
4272 else if (dp->conversion == 'g' || dp->conversion == 'G')
4275 if (flags & FLAG_ALT)
4278 (precision > 0 ? precision - 1 : 0);
4279 *p++ = decimal_point_char ();
4280 for (; ndigits > 0; --ndigits)
4284 else if (dp->conversion == 'a' || dp->conversion == 'A')
4287 *p++ = dp->conversion - 'A' + 'X';
4290 if ((flags & FLAG_ALT) || precision > 0)
4292 *p++ = decimal_point_char ();
4293 for (; precision > 0; precision--)
4296 *p++ = dp->conversion - 'A' + 'P';
4305 END_LONG_DOUBLE_ROUNDING ();
4308 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4312 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4314 double arg = a.arg[dp->arg_index].a.a_double;
4318 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4320 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4324 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4331 if (signbit (arg)) /* arg < 0.0 or negative zero */
4339 else if (flags & FLAG_SHOWSIGN)
4341 else if (flags & FLAG_SPACE)
4344 if (arg > 0.0 && arg + arg == arg)
4346 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4348 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4352 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4357 # if NEED_PRINTF_DOUBLE
4360 if (dp->conversion == 'f' || dp->conversion == 'F')
4366 scale10_round_decimal_double (arg, precision);
4369 ndigits = strlen (digits);
4371 if (ndigits > precision)
4375 *p++ = digits[ndigits];
4377 while (ndigits > precision);
4380 /* Here ndigits <= precision. */
4381 if ((flags & FLAG_ALT) || precision > 0)
4383 *p++ = decimal_point_char ();
4384 for (; precision > ndigits; precision--)
4389 *p++ = digits[ndigits];
4395 else if (dp->conversion == 'e' || dp->conversion == 'E')
4403 if ((flags & FLAG_ALT) || precision > 0)
4405 *p++ = decimal_point_char ();
4406 for (; precision > 0; precision--)
4417 exponent = floorlog10 (arg);
4422 scale10_round_decimal_double (arg,
4423 (int)precision - exponent);
4426 ndigits = strlen (digits);
4428 if (ndigits == precision + 1)
4430 if (ndigits < precision
4431 || ndigits > precision + 2)
4432 /* The exponent was not guessed
4433 precisely enough. */
4436 /* None of two values of exponent is
4437 the right one. Prevent an endless
4441 if (ndigits == precision)
4447 /* Here ndigits = precision+1. */
4448 if (is_borderline (digits, precision))
4450 /* Maybe the exponent guess was too high
4451 and a smaller exponent can be reached
4452 by turning a 10...0 into 9...9x. */
4454 scale10_round_decimal_double (arg,
4455 (int)precision - exponent + 1);
4456 if (digits2 == NULL)
4461 if (strlen (digits2) == precision + 1)
4470 /* Here ndigits = precision+1. */
4472 *p++ = digits[--ndigits];
4473 if ((flags & FLAG_ALT) || precision > 0)
4475 *p++ = decimal_point_char ();
4479 *p++ = digits[ndigits];
4486 *p++ = dp->conversion; /* 'e' or 'E' */
4487 # if WIDE_CHAR_VERSION
4489 static const wchar_t decimal_format[] =
4490 /* Produce the same number of exponent digits
4491 as the native printf implementation. */
4492 # if defined _WIN32 && ! defined __CYGWIN__
4493 { '%', '+', '.', '3', 'd', '\0' };
4495 { '%', '+', '.', '2', 'd', '\0' };
4497 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4503 static const char decimal_format[] =
4504 /* Produce the same number of exponent digits
4505 as the native printf implementation. */
4506 # if defined _WIN32 && ! defined __CYGWIN__
4511 if (sizeof (DCHAR_T) == 1)
4513 sprintf ((char *) p, decimal_format, exponent);
4521 sprintf (expbuf, decimal_format, exponent);
4522 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4528 else if (dp->conversion == 'g' || dp->conversion == 'G')
4532 /* precision >= 1. */
4535 /* The exponent is 0, >= -4, < precision.
4536 Use fixed-point notation. */
4538 size_t ndigits = precision;
4539 /* Number of trailing zeroes that have to be
4542 (flags & FLAG_ALT ? 0 : precision - 1);
4546 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4548 *p++ = decimal_point_char ();
4549 while (ndigits > nzeroes)
4565 exponent = floorlog10 (arg);
4570 scale10_round_decimal_double (arg,
4571 (int)(precision - 1) - exponent);
4574 ndigits = strlen (digits);
4576 if (ndigits == precision)
4578 if (ndigits < precision - 1
4579 || ndigits > precision + 1)
4580 /* The exponent was not guessed
4581 precisely enough. */
4584 /* None of two values of exponent is
4585 the right one. Prevent an endless
4589 if (ndigits < precision)
4595 /* Here ndigits = precision. */
4596 if (is_borderline (digits, precision - 1))
4598 /* Maybe the exponent guess was too high
4599 and a smaller exponent can be reached
4600 by turning a 10...0 into 9...9x. */
4602 scale10_round_decimal_double (arg,
4603 (int)(precision - 1) - exponent + 1);
4604 if (digits2 == NULL)
4609 if (strlen (digits2) == precision)
4618 /* Here ndigits = precision. */
4620 /* Determine the number of trailing zeroes
4621 that have to be dropped. */
4623 if ((flags & FLAG_ALT) == 0)
4624 while (nzeroes < ndigits
4625 && digits[nzeroes] == '0')
4628 /* The exponent is now determined. */
4630 && exponent < (long)precision)
4632 /* Fixed-point notation:
4633 max(exponent,0)+1 digits, then the
4634 decimal point, then the remaining
4635 digits without trailing zeroes. */
4638 size_t ecount = exponent + 1;
4639 /* Note: ecount <= precision = ndigits. */
4640 for (; ecount > 0; ecount--)
4641 *p++ = digits[--ndigits];
4642 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4644 *p++ = decimal_point_char ();
4645 while (ndigits > nzeroes)
4648 *p++ = digits[ndigits];
4654 size_t ecount = -exponent - 1;
4656 *p++ = decimal_point_char ();
4657 for (; ecount > 0; ecount--)
4659 while (ndigits > nzeroes)
4662 *p++ = digits[ndigits];
4668 /* Exponential notation. */
4669 *p++ = digits[--ndigits];
4670 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4672 *p++ = decimal_point_char ();
4673 while (ndigits > nzeroes)
4676 *p++ = digits[ndigits];
4679 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4680 # if WIDE_CHAR_VERSION
4682 static const wchar_t decimal_format[] =
4683 /* Produce the same number of exponent digits
4684 as the native printf implementation. */
4685 # if defined _WIN32 && ! defined __CYGWIN__
4686 { '%', '+', '.', '3', 'd', '\0' };
4688 { '%', '+', '.', '2', 'd', '\0' };
4690 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4696 static const char decimal_format[] =
4697 /* Produce the same number of exponent digits
4698 as the native printf implementation. */
4699 # if defined _WIN32 && ! defined __CYGWIN__
4704 if (sizeof (DCHAR_T) == 1)
4706 sprintf ((char *) p, decimal_format, exponent);
4714 sprintf (expbuf, decimal_format, exponent);
4715 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4728 /* arg is finite. */
4734 if (dp->conversion == 'f' || dp->conversion == 'F')
4737 if ((flags & FLAG_ALT) || precision > 0)
4739 *p++ = decimal_point_char ();
4740 for (; precision > 0; precision--)
4744 else if (dp->conversion == 'e' || dp->conversion == 'E')
4747 if ((flags & FLAG_ALT) || precision > 0)
4749 *p++ = decimal_point_char ();
4750 for (; precision > 0; precision--)
4753 *p++ = dp->conversion; /* 'e' or 'E' */
4755 /* Produce the same number of exponent digits as
4756 the native printf implementation. */
4757 # if defined _WIN32 && ! defined __CYGWIN__
4763 else if (dp->conversion == 'g' || dp->conversion == 'G')
4766 if (flags & FLAG_ALT)
4769 (precision > 0 ? precision - 1 : 0);
4770 *p++ = decimal_point_char ();
4771 for (; ndigits > 0; --ndigits)
4783 /* The generated string now extends from tmp to p, with the
4784 zero padding insertion point being at pad_ptr. */
4789 size_t pad = width - count;
4790 DCHAR_T *end = p + pad;
4792 if (flags & FLAG_LEFT)
4794 /* Pad with spaces on the right. */
4795 for (; pad > 0; pad--)
4798 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4800 /* Pad with zeroes. */
4805 for (; pad > 0; pad--)
4810 /* Pad with spaces on the left. */
4815 for (; pad > 0; pad--)
4824 if (count >= tmp_length)
4825 /* tmp_length was incorrectly calculated - fix the
4829 /* Make room for the result. */
4830 if (count >= allocated - length)
4832 size_t n = xsum (length, count);
4834 ENSURE_ALLOCATION (n);
4837 /* Append the result. */
4838 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4846 arg_type type = a.arg[dp->arg_index].type;
4847 int flags = dp->flags;
4848 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4851 #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
4854 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4858 #if NEED_PRINTF_UNBOUNDED_PRECISION
4861 # define prec_ourselves 0
4863 #if NEED_PRINTF_FLAG_LEFTADJUST
4864 # define pad_ourselves 1
4865 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4868 # define pad_ourselves 0
4871 unsigned int prefix_count;
4872 int prefixes[2] IF_LINT (= { 0 });
4876 TCHAR_T tmpbuf[700];
4880 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4883 #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
4885 if (dp->width_start != dp->width_end)
4887 if (dp->width_arg_index != ARG_NONE)
4891 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4893 arg = a.arg[dp->width_arg_index].a.a_int;
4897 /* "A negative field width is taken as a '-' flag
4898 followed by a positive field width." */
4905 const FCHAR_T *digitp = dp->width_start;
4908 width = xsum (xtimes (width, 10), *digitp++ - '0');
4909 while (digitp != dp->width_end);
4911 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4917 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4920 if (dp->precision_start != dp->precision_end)
4922 if (dp->precision_arg_index != ARG_NONE)
4926 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4928 arg = a.arg[dp->precision_arg_index].a.a_int;
4929 /* "A negative precision is taken as if the precision
4939 const FCHAR_T *digitp = dp->precision_start + 1;
4942 while (digitp != dp->precision_end)
4943 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4949 /* Decide whether to handle the precision ourselves. */
4950 #if NEED_PRINTF_UNBOUNDED_PRECISION
4951 switch (dp->conversion)
4953 case 'd': case 'i': case 'u':
4955 case 'x': case 'X': case 'p':
4956 prec_ourselves = has_precision && (precision > 0);
4964 /* Decide whether to perform the padding ourselves. */
4965 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4966 switch (dp->conversion)
4968 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4969 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4970 to perform the padding after this conversion. Functions
4971 with unistdio extensions perform the padding based on
4972 character count rather than element count. */
4975 # if NEED_PRINTF_FLAG_ZERO
4976 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4982 pad_ourselves = prec_ourselves;
4988 /* Allocate a temporary buffer of sufficient size for calling
4991 MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
4992 flags, width, has_precision, precision,
4995 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4999 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
5001 if (size_overflow_p (tmp_memsize))
5002 /* Overflow, would lead to out of memory. */
5004 tmp = (TCHAR_T *) malloc (tmp_memsize);
5006 /* Out of memory. */
5011 /* Construct the format string for calling snprintf or
5015 #if NEED_PRINTF_FLAG_GROUPING
5016 /* The underlying implementation doesn't support the ' flag.
5017 Produce no grouping characters in this case; this is
5018 acceptable because the grouping is locale dependent. */
5020 if (flags & FLAG_GROUP)
5023 if (flags & FLAG_LEFT)
5025 if (flags & FLAG_SHOWSIGN)
5027 if (flags & FLAG_SPACE)
5029 if (flags & FLAG_ALT)
5031 #if __GLIBC__ >= 2 && !defined __UCLIBC__
5032 if (flags & FLAG_LOCALIZED)
5037 if (flags & FLAG_ZERO)
5039 if (dp->width_start != dp->width_end)
5041 size_t n = dp->width_end - dp->width_start;
5042 /* The width specification is known to consist only
5043 of standard ASCII characters. */
5044 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
5046 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
5051 const FCHAR_T *mp = dp->width_start;
5058 if (!prec_ourselves)
5060 if (dp->precision_start != dp->precision_end)
5062 size_t n = dp->precision_end - dp->precision_start;
5063 /* The precision specification is known to consist only
5064 of standard ASCII characters. */
5065 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
5067 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
5072 const FCHAR_T *mp = dp->precision_start;
5082 case TYPE_LONGLONGINT:
5083 case TYPE_ULONGLONGINT:
5084 #if defined _WIN32 && ! defined __CYGWIN__
5096 case TYPE_WIDE_CHAR:
5099 case TYPE_WIDE_STRING:
5103 case TYPE_LONGDOUBLE:
5109 #if NEED_PRINTF_DIRECTIVE_F
5110 if (dp->conversion == 'F')
5114 *fbp = dp->conversion;
5116 # if ((HAVE_SNPRINTF_RETVAL_C99 && HAVE_SNPRINTF_TRUNCATION_C99) \
5117 || ((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) \
5118 && !defined __UCLIBC__) \
5119 || (defined __APPLE__ && defined __MACH__) \
5120 || defined __ANDROID__ \
5121 || (defined _WIN32 && ! defined __CYGWIN__))
5122 /* On systems where we know that snprintf's return value
5123 conforms to ISO C 99 (HAVE_SNPRINTF_RETVAL_C99) and that
5124 snprintf always produces NUL-terminated strings
5125 (HAVE_SNPRINTF_TRUNCATION_C99), it is possible to avoid
5126 using %n. And it is desirable to do so, because more and
5127 more platforms no longer support %n, for "security reasons".
5128 In particular, the following platforms:
5129 - On glibc2 systems from 2004-10-18 or newer, the use of
5130 %n in format strings in writable memory may crash the
5131 program (if compiled with _FORTIFY_SOURCE=2).
5132 - On Mac OS X 10.13 or newer, the use of %n in format
5133 strings in writable memory by default crashes the
5135 - On Android, starting on 2018-03-07, the use of %n in
5136 format strings produces a fatal error (see
5137 <https://android.googlesource.com/platform/bionic/+/41398d03b7e8e0dfb951660ae713e682e9fc0336>).
5138 On these platforms, HAVE_SNPRINTF_RETVAL_C99 and
5139 HAVE_SNPRINTF_TRUNCATION_C99 are 1. We have listed them
5140 explicitly in the condition above, in case of cross-
5141 compilation (just to be sure). */
5142 /* On native Windows systems (such as mingw), we can avoid using
5144 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
5145 snprintf does not write more than the specified number
5146 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
5147 '4', '5', '6' into buf, not '4', '5', '\0'.)
5148 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
5149 allows us to recognize the case of an insufficient
5150 buffer size: it returns -1 in this case.
5151 On native Windows systems (such as mingw) where the OS is
5152 Windows Vista, the use of %n in format strings by default
5153 crashes the program. See
5154 <https://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
5155 <https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/set-printf-count-output>
5156 So we should avoid %n in this situation. */
5158 # else /* AIX <= 5.1, HP-UX, IRIX, OSF/1, Solaris <= 9, BeOS */
5167 /* Construct the arguments for calling snprintf or sprintf. */
5169 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
5171 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
5173 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
5175 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
5177 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
5179 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
5183 /* The SNPRINTF result is appended after result[0..length].
5184 The latter is an array of DCHAR_T; SNPRINTF appends an
5185 array of TCHAR_T to it. This is possible because
5186 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
5187 alignof (TCHAR_T) <= alignof (DCHAR_T). */
5188 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
5189 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
5190 where an snprintf() with maxlen==1 acts like sprintf(). */
5191 ENSURE_ALLOCATION (xsum (length,
5192 (2 + TCHARS_PER_DCHAR - 1)
5193 / TCHARS_PER_DCHAR));
5194 /* Prepare checking whether snprintf returns the count
5196 *(TCHAR_T *) (result + length) = '\0';
5207 size_t maxlen = allocated - length;
5208 /* SNPRINTF can fail if its second argument is
5210 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
5211 maxlen = INT_MAX / TCHARS_PER_DCHAR;
5212 maxlen = maxlen * TCHARS_PER_DCHAR;
5213 # define SNPRINTF_BUF(arg) \
5214 switch (prefix_count) \
5217 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
5222 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
5224 prefixes[0], arg, &count); \
5227 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
5229 prefixes[0], prefixes[1], arg, \
5236 # define SNPRINTF_BUF(arg) \
5237 switch (prefix_count) \
5240 count = sprintf (tmp, buf, arg); \
5243 count = sprintf (tmp, buf, prefixes[0], arg); \
5246 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
5259 int arg = a.arg[dp->arg_index].a.a_schar;
5265 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
5271 int arg = a.arg[dp->arg_index].a.a_short;
5277 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
5283 int arg = a.arg[dp->arg_index].a.a_int;
5289 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
5295 long int arg = a.arg[dp->arg_index].a.a_longint;
5301 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
5305 case TYPE_LONGLONGINT:
5307 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
5311 case TYPE_ULONGLONGINT:
5313 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
5319 double arg = a.arg[dp->arg_index].a.a_double;
5323 case TYPE_LONGDOUBLE:
5325 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5331 int arg = a.arg[dp->arg_index].a.a_char;
5336 case TYPE_WIDE_CHAR:
5338 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5345 const char *arg = a.arg[dp->arg_index].a.a_string;
5350 case TYPE_WIDE_STRING:
5352 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5359 void *arg = a.arg[dp->arg_index].a.a_pointer;
5368 /* Portability: Not all implementations of snprintf()
5369 are ISO C 99 compliant. Determine the number of
5370 bytes that snprintf() has produced or would have
5374 /* Verify that snprintf() has NUL-terminated its
5376 if ((unsigned int) count < maxlen
5377 && ((TCHAR_T *) (result + length)) [count] != '\0')
5379 /* Portability hack. */
5380 if (retcount > count)
5385 /* snprintf() doesn't understand the '%n'
5389 /* Don't use the '%n' directive; instead, look
5390 at the snprintf() return value. */
5396 /* Look at the snprintf() return value. */
5399 # if !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF
5400 /* HP-UX 10.20 snprintf() is doubly deficient:
5401 It doesn't understand the '%n' directive,
5402 *and* it returns -1 (rather than the length
5403 that would have been required) when the
5404 buffer is too small.
5405 But a failure at this point can also come
5406 from other reasons than a too small buffer,
5407 such as an invalid wide string argument to
5408 the %ls directive, or possibly an invalid
5409 floating-point argument. */
5411 MAX_ROOM_NEEDED (&a, dp->arg_index,
5412 dp->conversion, type, flags,
5415 precision, pad_ourselves);
5417 if (maxlen < tmp_length)
5419 /* Make more room. But try to do through
5420 this reallocation only once. */
5421 size_t bigger_need =
5424 TCHARS_PER_DCHAR - 1)
5425 / TCHARS_PER_DCHAR);
5426 /* And always grow proportionally.
5427 (There may be several arguments, each
5428 needing a little more room than the
5430 size_t bigger_need2 =
5431 xsum (xtimes (allocated, 2), 12);
5432 if (bigger_need < bigger_need2)
5433 bigger_need = bigger_need2;
5434 ENSURE_ALLOCATION (bigger_need);
5445 /* Attempt to handle failure. */
5448 /* SNPRINTF or sprintf failed. Use the errno that it
5452 if (dp->conversion == 'c' || dp->conversion == 's')
5458 if (!(result == resultbuf || result == NULL))
5460 if (buf_malloced != NULL)
5461 free (buf_malloced);
5468 /* Handle overflow of the allocated buffer.
5469 If such an overflow occurs, a C99 compliant snprintf()
5470 returns a count >= maxlen. However, a non-compliant
5471 snprintf() function returns only count = maxlen - 1. To
5472 cover both cases, test whether count >= maxlen - 1. */
5473 if ((unsigned int) count + 1 >= maxlen)
5475 /* If maxlen already has attained its allowed maximum,
5476 allocating more memory will not increase maxlen.
5477 Instead of looping, bail out. */
5478 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5482 /* Need at least (count + 1) * sizeof (TCHAR_T)
5483 bytes. (The +1 is for the trailing NUL.)
5484 But ask for (count + 2) * sizeof (TCHAR_T)
5485 bytes, so that in the next round, we likely get
5486 maxlen > (unsigned int) count + 1
5487 and so we don't get here again.
5488 And allocate proportionally, to avoid looping
5489 eternally if snprintf() reports a too small
5493 ((unsigned int) count + 2
5494 + TCHARS_PER_DCHAR - 1)
5495 / TCHARS_PER_DCHAR),
5496 xtimes (allocated, 2));
5498 ENSURE_ALLOCATION (n);
5504 #if NEED_PRINTF_UNBOUNDED_PRECISION
5507 /* Handle the precision. */
5510 (TCHAR_T *) (result + length);
5514 size_t prefix_count;
5518 /* Put the additional zeroes after the sign. */
5520 && (*prec_ptr == '-' || *prec_ptr == '+'
5521 || *prec_ptr == ' '))
5523 /* Put the additional zeroes after the 0x prefix if
5524 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5526 && prec_ptr[0] == '0'
5527 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5530 move = count - prefix_count;
5531 if (precision > move)
5533 /* Insert zeroes. */
5534 size_t insert = precision - move;
5540 (count + insert + TCHARS_PER_DCHAR - 1)
5541 / TCHARS_PER_DCHAR);
5542 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5543 ENSURE_ALLOCATION (n);
5544 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5545 prec_ptr = (TCHAR_T *) (result + length);
5548 prec_end = prec_ptr + count;
5549 prec_ptr += prefix_count;
5551 while (prec_end > prec_ptr)
5554 prec_end[insert] = prec_end[0];
5560 while (prec_end > prec_ptr);
5568 if (count >= tmp_length)
5569 /* tmp_length was incorrectly calculated - fix the
5575 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5576 if (dp->conversion == 'c' || dp->conversion == 's')
5578 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5580 The result string is not certainly ASCII. */
5581 const TCHAR_T *tmpsrc;
5584 /* This code assumes that TCHAR_T is 'char'. */
5585 verify (sizeof (TCHAR_T) == 1);
5587 tmpsrc = (TCHAR_T *) (result + length);
5592 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5593 iconveh_question_mark,
5599 if (!(result == resultbuf || result == NULL))
5601 if (buf_malloced != NULL)
5602 free (buf_malloced);
5606 ENSURE_ALLOCATION_ELSE (xsum (length, tmpdst_len),
5607 { free (tmpdst); goto out_of_memory; });
5608 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5614 /* The result string is ASCII.
5615 Simple 1:1 conversion. */
5617 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5618 no-op conversion, in-place on the array starting
5619 at (result + length). */
5620 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5623 const TCHAR_T *tmpsrc;
5628 if (result == resultbuf)
5630 tmpsrc = (TCHAR_T *) (result + length);
5631 /* ENSURE_ALLOCATION will not move tmpsrc
5632 (because it's part of resultbuf). */
5633 ENSURE_ALLOCATION (xsum (length, count));
5637 /* ENSURE_ALLOCATION will move the array
5638 (because it uses realloc(). */
5639 ENSURE_ALLOCATION (xsum (length, count));
5640 tmpsrc = (TCHAR_T *) (result + length);
5644 ENSURE_ALLOCATION (xsum (length, count));
5646 tmpdst = result + length;
5647 /* Copy backwards, because of overlapping. */
5650 for (n = count; n > 0; n--)
5651 *--tmpdst = *--tmpsrc;
5656 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5657 /* Make room for the result. */
5658 if (count > allocated - length)
5660 /* Need at least count elements. But allocate
5663 xmax (xsum (length, count), xtimes (allocated, 2));
5665 ENSURE_ALLOCATION (n);
5669 /* Here count <= allocated - length. */
5671 /* Perform padding. */
5672 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5673 if (pad_ourselves && has_width)
5676 # if ENABLE_UNISTDIO
5677 /* Outside POSIX, it's preferable to compare the width
5678 against the number of _characters_ of the converted
5680 w = DCHAR_MBSNLEN (result + length, count);
5682 /* The width is compared against the number of _bytes_
5683 of the converted value, says POSIX. */
5688 size_t pad = width - w;
5690 /* Make room for the result. */
5691 if (xsum (count, pad) > allocated - length)
5693 /* Need at least count + pad elements. But
5694 allocate proportionally. */
5696 xmax (xsum3 (length, count, pad),
5697 xtimes (allocated, 2));
5701 ENSURE_ALLOCATION (n);
5704 ENSURE_ALLOCATION (n);
5707 /* Here count + pad <= allocated - length. */
5710 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5711 DCHAR_T * const rp = result + length;
5713 DCHAR_T * const rp = tmp;
5715 DCHAR_T *p = rp + count;
5716 DCHAR_T *end = p + pad;
5718 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5719 if (dp->conversion == 'c'
5720 || dp->conversion == 's')
5721 /* No zero-padding for string directives. */
5726 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5727 /* No zero-padding of "inf" and "nan". */
5728 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5729 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5732 /* The generated string now extends from rp to p,
5733 with the zero padding insertion point being at
5736 count = count + pad; /* = end - rp */
5738 if (flags & FLAG_LEFT)
5740 /* Pad with spaces on the right. */
5741 for (; pad > 0; pad--)
5744 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5746 /* Pad with zeroes. */
5751 for (; pad > 0; pad--)
5756 /* Pad with spaces on the left. */
5761 for (; pad > 0; pad--)
5769 /* Here still count <= allocated - length. */
5771 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5772 /* The snprintf() result did fit. */
5774 /* Append the sprintf() result. */
5775 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5782 #if NEED_PRINTF_DIRECTIVE_F
5783 if (dp->conversion == 'F')
5785 /* Convert the %f result to upper case for %F. */
5786 DCHAR_T *rp = result + length;
5788 for (rc = count; rc > 0; rc--, rp++)
5789 if (*rp >= 'a' && *rp <= 'z')
5790 *rp = *rp - 'a' + 'A';
5798 #undef pad_ourselves
5799 #undef prec_ourselves
5804 /* Add the final NUL. */
5805 ENSURE_ALLOCATION (xsum (length, 1));
5806 result[length] = '\0';
5808 if (result != resultbuf && length + 1 < allocated)
5810 /* Shrink the allocated memory if possible. */
5813 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5818 if (buf_malloced != NULL)
5819 free (buf_malloced);
5822 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5823 says that snprintf() fails with errno = EOVERFLOW in this case, but
5824 that's only because snprintf() returns an 'int'. This function does
5825 not have this limitation. */
5830 if (!(result == resultbuf || result == NULL))
5832 if (buf_malloced != NULL)
5833 free (buf_malloced);
5840 if (!(result == resultbuf || result == NULL))
5842 if (buf_malloced != NULL)
5843 free (buf_malloced);
5851 #undef MAX_ROOM_NEEDED
5852 #undef TCHARS_PER_DCHAR
5860 #undef DCHAR_IS_TCHAR