1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2020 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, see <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
69 # if WIDE_CHAR_VERSION
70 # include "vasnwprintf.h"
72 # include "vasnprintf.h"
76 #include <locale.h> /* localeconv() */
77 #include <stdio.h> /* snprintf(), sprintf() */
78 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
79 #include <string.h> /* memcpy(), strlen() */
80 #include <errno.h> /* errno */
81 #include <limits.h> /* CHAR_BIT */
82 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
84 # include <langinfo.h>
87 # if WIDE_CHAR_VERSION
88 # include "wprintf-parse.h"
90 # include "printf-parse.h"
94 /* Checked size_t computations. */
97 #include "attribute.h"
100 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
105 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
107 # include "isnand-nolibm.h"
110 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
112 # include "isnanl-nolibm.h"
116 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
118 # include "isnand-nolibm.h"
119 # include "printf-frexp.h"
122 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
124 # include "isnanl-nolibm.h"
125 # include "printf-frexpl.h"
129 /* Default parameters. */
131 # if WIDE_CHAR_VERSION
132 # define VASNPRINTF vasnwprintf
133 # define FCHAR_T wchar_t
134 # define DCHAR_T wchar_t
135 # define TCHAR_T wchar_t
136 # define DCHAR_IS_TCHAR 1
137 # define DIRECTIVE wchar_t_directive
138 # define DIRECTIVES wchar_t_directives
139 # define PRINTF_PARSE wprintf_parse
140 # define DCHAR_CPY wmemcpy
141 # define DCHAR_SET wmemset
143 # define VASNPRINTF vasnprintf
144 # define FCHAR_T char
145 # define DCHAR_T char
146 # define TCHAR_T char
147 # define DCHAR_IS_TCHAR 1
148 # define DIRECTIVE char_directive
149 # define DIRECTIVES char_directives
150 # define PRINTF_PARSE printf_parse
151 # define DCHAR_CPY memcpy
152 # define DCHAR_SET memset
155 #if WIDE_CHAR_VERSION
156 /* TCHAR_T is wchar_t. */
157 # define USE_SNPRINTF 1
158 # if HAVE_DECL__SNWPRINTF
159 /* On Windows, the function swprintf() has a different signature than
160 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
161 instead. The mingw function snwprintf() has fewer bugs than the
162 MSVCRT function _snwprintf(), so prefer that. */
163 # if defined __MINGW32__
164 # define SNPRINTF snwprintf
166 # define SNPRINTF _snwprintf
167 # define USE_MSVC__SNPRINTF 1
171 # define SNPRINTF swprintf
174 /* TCHAR_T is char. */
175 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
176 But don't use it on BeOS, since BeOS snprintf produces no output if the
177 size argument is >= 0x3000000.
178 Also don't use it on Linux libc5, since there snprintf with size = 1
179 writes any output without bounds, like sprintf. */
180 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
181 # define USE_SNPRINTF 1
183 # define USE_SNPRINTF 0
185 # if HAVE_DECL__SNPRINTF
186 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
187 function _snprintf(), so prefer that. */
188 # if defined __MINGW32__
189 # define SNPRINTF snprintf
190 /* Here we need to call the native snprintf, not rpl_snprintf. */
193 /* MSVC versions < 14 did not have snprintf, only _snprintf. */
194 # define SNPRINTF _snprintf
195 # define USE_MSVC__SNPRINTF 1
199 # define SNPRINTF snprintf
200 /* Here we need to call the native snprintf, not rpl_snprintf. */
204 /* Here we need to call the native sprintf, not rpl_sprintf. */
207 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
208 warnings in this file. Use -Dlint to suppress them. */
209 #if defined GCC_LINT || defined lint
210 # define IF_LINT(Code) Code
212 # define IF_LINT(Code) /* empty */
215 /* Avoid some warnings from "gcc -Wshadow".
216 This file doesn't use the exp() and remainder() functions. */
220 #define remainder rem
222 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && !WIDE_CHAR_VERSION
223 # if (HAVE_STRNLEN && !defined _AIX)
224 # define local_strnlen strnlen
226 # ifndef local_strnlen_defined
227 # define local_strnlen_defined 1
229 local_strnlen (const char *string
, size_t maxlen
)
231 const char *end
= memchr (string
, '\0', maxlen
);
232 return end
? (size_t) (end
- string
) : maxlen
;
238 #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
240 # define local_wcslen wcslen
242 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
243 a dependency towards this library, here is a local substitute.
244 Define this substitute only once, even if this file is included
245 twice in the same compilation unit. */
246 # ifndef local_wcslen_defined
247 # define local_wcslen_defined 1
249 local_wcslen (const wchar_t *s
)
253 for (ptr
= s
; *ptr
!= (wchar_t) 0; ptr
++)
261 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
263 # define local_wcsnlen wcsnlen
265 # ifndef local_wcsnlen_defined
266 # define local_wcsnlen_defined 1
268 local_wcsnlen (const wchar_t *s
, size_t maxlen
)
272 for (ptr
= s
; maxlen
> 0 && *ptr
!= (wchar_t) 0; ptr
++, maxlen
--)
280 #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
281 # if ENABLE_WCHAR_FALLBACK
283 wctomb_fallback (char *s
, wchar_t wc
)
285 static char hex
[16] = "0123456789ABCDEF";
288 if (sizeof (wchar_t) > 2 && wc
> 0xffff)
290 # if __STDC_ISO_10646__ || (__GLIBC__ >= 2) || (defined _WIN32 || defined __CYGWIN__)
295 s
[2] = hex
[(wc
& 0xf0000000U
) >> 28];
296 s
[3] = hex
[(wc
& 0xf000000U
) >> 24];
297 s
[4] = hex
[(wc
& 0xf00000U
) >> 20];
298 s
[5] = hex
[(wc
& 0xf0000U
) >> 16];
299 s
[6] = hex
[(wc
& 0xf000U
) >> 12];
300 s
[7] = hex
[(wc
& 0xf00U
) >> 8];
301 s
[8] = hex
[(wc
& 0xf0U
) >> 4];
302 s
[9] = hex
[wc
& 0xfU
];
307 # if __STDC_ISO_10646__ || (__GLIBC__ >= 2) || (defined _WIN32 || defined __CYGWIN__)
312 s
[2] = hex
[(wc
& 0xf000U
) >> 12];
313 s
[3] = hex
[(wc
& 0xf00U
) >> 8];
314 s
[4] = hex
[(wc
& 0xf0U
) >> 4];
315 s
[5] = hex
[wc
& 0xfU
];
319 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
321 local_wcrtomb (char *s
, wchar_t wc
, mbstate_t *ps
)
323 size_t count
= wcrtomb (s
, wc
, ps
);
324 if (count
== (size_t)(-1))
325 count
= wctomb_fallback (s
, wc
);
330 local_wctomb (char *s
, wchar_t wc
)
332 int count
= wctomb (s
, wc
);
334 count
= wctomb_fallback (s
, wc
);
337 # define local_wcrtomb(S, WC, PS) local_wctomb ((S), (WC))
340 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
341 # define local_wcrtomb(S, WC, PS) wcrtomb ((S), (WC), (PS))
343 # define local_wcrtomb(S, WC, PS) wctomb ((S), (WC))
348 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
349 /* Determine the decimal-point character according to the current locale. */
350 # ifndef decimal_point_char_defined
351 # define decimal_point_char_defined 1
353 decimal_point_char (void)
356 /* Determine it in a multithread-safe way. We know nl_langinfo is
357 multithread-safe on glibc systems and Mac OS X systems, but is not required
358 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
359 localeconv() is rarely multithread-safe. */
360 # if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
361 point
= nl_langinfo (RADIXCHAR
);
364 sprintf (pointbuf
, "%#.0f", 1.0);
365 point
= &pointbuf
[1];
367 point
= localeconv () -> decimal_point
;
369 /* The decimal point is always a single byte: either '.' or ','. */
370 return (point
[0] != '\0' ? point
[0] : '.');
375 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
377 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
379 is_infinite_or_zero (double x
)
381 return isnand (x
) || x
+ x
== x
;
386 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
388 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
390 is_infinite_or_zerol (long double x
)
392 return isnanl (x
) || x
+ x
== x
;
397 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
399 /* Converting 'long double' to decimal without rare rounding bugs requires
400 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
401 (and slower) algorithms. */
403 typedef unsigned int mp_limb_t
;
404 # define GMP_LIMB_BITS 32
405 verify (sizeof (mp_limb_t
) * CHAR_BIT
== GMP_LIMB_BITS
);
407 typedef unsigned long long mp_twolimb_t
;
408 # define GMP_TWOLIMB_BITS 64
409 verify (sizeof (mp_twolimb_t
) * CHAR_BIT
== GMP_TWOLIMB_BITS
);
411 /* Representation of a bignum >= 0. */
415 mp_limb_t
*limbs
; /* Bits in little-endian order, allocated with malloc(). */
418 /* Compute the product of two bignums >= 0.
419 Return the allocated memory in case of success, NULL in case of memory
420 allocation failure. */
422 multiply (mpn_t src1
, mpn_t src2
, mpn_t
*dest
)
429 if (src1
.nlimbs
<= src2
.nlimbs
)
443 /* Now 0 <= len1 <= len2. */
446 /* src1 or src2 is zero. */
448 dest
->limbs
= (mp_limb_t
*) malloc (1);
452 /* Here 1 <= len1 <= len2. */
458 dp
= (mp_limb_t
*) malloc (dlen
* sizeof (mp_limb_t
));
461 for (k
= len2
; k
> 0; )
463 for (i
= 0; i
< len1
; i
++)
465 mp_limb_t digit1
= p1
[i
];
466 mp_twolimb_t carry
= 0;
467 for (j
= 0; j
< len2
; j
++)
469 mp_limb_t digit2
= p2
[j
];
470 carry
+= (mp_twolimb_t
) digit1
* (mp_twolimb_t
) digit2
;
472 dp
[i
+ j
] = (mp_limb_t
) carry
;
473 carry
= carry
>> GMP_LIMB_BITS
;
475 dp
[i
+ len2
] = (mp_limb_t
) carry
;
478 while (dlen
> 0 && dp
[dlen
- 1] == 0)
486 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
487 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
489 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
491 Return the allocated memory in case of success, NULL in case of memory
492 allocation failure. */
494 divide (mpn_t a
, mpn_t b
, mpn_t
*q
)
497 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
498 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
499 If m<n, then q:=0 and r:=a.
500 If m>=n=1, perform a single-precision division:
503 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
504 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
505 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
506 Normalise [q[m-1],...,q[0]], yields q.
507 If m>=n>1, perform a multiple-precision division:
508 We have a/b < beta^(m-n+1).
509 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
510 Shift a and b left by s bits, copying them. r:=a.
511 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
512 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
514 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
515 In case of overflow (q* >= beta) set q* := beta-1.
516 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
517 and c3 := b[n-2] * q*.
518 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
519 occurred. Furthermore 0 <= c3 < beta^2.
520 If there was overflow and
521 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
522 the next test can be skipped.}
523 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
524 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
526 Put r := r - b * q* * beta^j. In detail:
527 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
528 hence: u:=0, for i:=0 to n-1 do
530 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
531 u:=u div beta (+ 1, if carry in subtraction)
533 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
535 the carry u does not overflow.}
536 If a negative carry occurs, put q* := q* - 1
537 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
539 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
540 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
542 The room for q[j] can be allocated at the memory location of r[n+j].
543 Finally, round-to-even:
544 Shift r left by 1 bit.
545 If r > b or if r = b and q[0] is odd, q := q+1.
547 const mp_limb_t
*a_ptr
= a
.limbs
;
548 size_t a_len
= a
.nlimbs
;
549 const mp_limb_t
*b_ptr
= b
.limbs
;
550 size_t b_len
= b
.nlimbs
;
552 mp_limb_t
*tmp_roomptr
= NULL
;
558 /* Allocate room for a_len+2 digits.
559 (Need a_len+1 digits for the real division and 1 more digit for the
560 final rounding of q.) */
561 roomptr
= (mp_limb_t
*) malloc ((a_len
+ 2) * sizeof (mp_limb_t
));
566 while (a_len
> 0 && a_ptr
[a_len
- 1] == 0)
573 /* Division by zero. */
575 if (b_ptr
[b_len
- 1] == 0)
581 /* Here m = a_len >= 0 and n = b_len > 0. */
585 /* m<n: trivial case. q=0, r := copy of a. */
588 memcpy (r_ptr
, a_ptr
, a_len
* sizeof (mp_limb_t
));
589 q_ptr
= roomptr
+ a_len
;
594 /* n=1: single precision division.
595 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
599 mp_limb_t den
= b_ptr
[0];
600 mp_limb_t remainder
= 0;
601 const mp_limb_t
*sourceptr
= a_ptr
+ a_len
;
602 mp_limb_t
*destptr
= q_ptr
+ a_len
;
604 for (count
= a_len
; count
> 0; count
--)
607 ((mp_twolimb_t
) remainder
<< GMP_LIMB_BITS
) | *--sourceptr
;
608 *--destptr
= num
/ den
;
609 remainder
= num
% den
;
611 /* Normalise and store r. */
614 r_ptr
[0] = remainder
;
621 if (q_ptr
[q_len
- 1] == 0)
627 /* n>1: multiple precision division.
628 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
629 beta^(m-n-1) <= a/b < beta^(m-n+1). */
633 mp_limb_t msd
= b_ptr
[b_len
- 1]; /* = b[n-1], > 0 */
634 /* Determine s = GMP_LIMB_BITS - integer_length (msd).
635 Code copied from gnulib's integer_length.c. */
636 # if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) \
637 || (__clang_major__ >= 4)
638 s
= __builtin_clz (msd
);
640 # if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT
641 if (GMP_LIMB_BITS
<= DBL_MANT_BIT
)
643 /* Use 'double' operations.
644 Assumes an IEEE 754 'double' implementation. */
645 # define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)
646 # define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1)
648 ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
649 union { double value
; unsigned int word
[NWORDS
]; } m
;
651 /* Use a single integer to floating-point conversion. */
655 - (((m
.word
[DBL_EXPBIT0_WORD
] >> DBL_EXPBIT0_BIT
) & DBL_EXP_MASK
)
691 /* 0 <= s < GMP_LIMB_BITS.
692 Copy b, shifting it left by s bits. */
695 tmp_roomptr
= (mp_limb_t
*) malloc (b_len
* sizeof (mp_limb_t
));
696 if (tmp_roomptr
== NULL
)
702 const mp_limb_t
*sourceptr
= b_ptr
;
703 mp_limb_t
*destptr
= tmp_roomptr
;
704 mp_twolimb_t accu
= 0;
706 for (count
= b_len
; count
> 0; count
--)
708 accu
+= (mp_twolimb_t
) *sourceptr
++ << s
;
709 *destptr
++ = (mp_limb_t
) accu
;
710 accu
= accu
>> GMP_LIMB_BITS
;
712 /* accu must be zero, since that was how s was determined. */
718 /* Copy a, shifting it left by s bits, yields r.
720 At the beginning: r = roomptr[0..a_len],
721 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
725 memcpy (r_ptr
, a_ptr
, a_len
* sizeof (mp_limb_t
));
730 const mp_limb_t
*sourceptr
= a_ptr
;
731 mp_limb_t
*destptr
= r_ptr
;
732 mp_twolimb_t accu
= 0;
734 for (count
= a_len
; count
> 0; count
--)
736 accu
+= (mp_twolimb_t
) *sourceptr
++ << s
;
737 *destptr
++ = (mp_limb_t
) accu
;
738 accu
= accu
>> GMP_LIMB_BITS
;
740 *destptr
++ = (mp_limb_t
) accu
;
742 q_ptr
= roomptr
+ b_len
;
743 q_len
= a_len
- b_len
+ 1; /* q will have m-n+1 limbs */
745 size_t j
= a_len
- b_len
; /* m-n */
746 mp_limb_t b_msd
= b_ptr
[b_len
- 1]; /* b[n-1] */
747 mp_limb_t b_2msd
= b_ptr
[b_len
- 2]; /* b[n-2] */
748 mp_twolimb_t b_msdd
= /* b[n-1]*beta+b[n-2] */
749 ((mp_twolimb_t
) b_msd
<< GMP_LIMB_BITS
) | b_2msd
;
750 /* Division loop, traversed m-n+1 times.
751 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
756 if (r_ptr
[j
+ b_len
] < b_msd
) /* r[j+n] < b[n-1] ? */
758 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
760 ((mp_twolimb_t
) r_ptr
[j
+ b_len
] << GMP_LIMB_BITS
)
761 | r_ptr
[j
+ b_len
- 1];
762 q_star
= num
/ b_msd
;
767 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
768 q_star
= (mp_limb_t
)~(mp_limb_t
)0; /* q* = beta-1 */
769 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
770 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
771 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
773 If yes, jump directly to the subtraction loop.
774 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
775 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
776 if (r_ptr
[j
+ b_len
] > b_msd
777 || (c1
= r_ptr
[j
+ b_len
- 1] + b_msd
) < b_msd
)
778 /* r[j+n] >= b[n-1]+1 or
779 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
784 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
786 mp_twolimb_t c2
= /* c1*beta+r[j+n-2] */
787 ((mp_twolimb_t
) c1
<< GMP_LIMB_BITS
) | r_ptr
[j
+ b_len
- 2];
788 mp_twolimb_t c3
= /* b[n-2] * q* */
789 (mp_twolimb_t
) b_2msd
* (mp_twolimb_t
) q_star
;
790 /* While c2 < c3, increase c2 and decrease c3.
791 Consider c3-c2. While it is > 0, decrease it by
792 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
793 this can happen only twice. */
796 q_star
= q_star
- 1; /* q* := q* - 1 */
797 if (c3
- c2
> b_msdd
)
798 q_star
= q_star
- 1; /* q* := q* - 1 */
804 /* Subtract r := r - b * q* * beta^j. */
807 const mp_limb_t
*sourceptr
= b_ptr
;
808 mp_limb_t
*destptr
= r_ptr
+ j
;
809 mp_twolimb_t carry
= 0;
811 for (count
= b_len
; count
> 0; count
--)
813 /* Here 0 <= carry <= q*. */
816 + (mp_twolimb_t
) q_star
* (mp_twolimb_t
) *sourceptr
++
817 + (mp_limb_t
) ~(*destptr
);
818 /* Here 0 <= carry <= beta*q* + beta-1. */
819 *destptr
++ = ~(mp_limb_t
) carry
;
820 carry
= carry
>> GMP_LIMB_BITS
; /* <= q* */
822 cr
= (mp_limb_t
) carry
;
824 /* Subtract cr from r_ptr[j + b_len], then forget about
826 if (cr
> r_ptr
[j
+ b_len
])
828 /* Subtraction gave a carry. */
829 q_star
= q_star
- 1; /* q* := q* - 1 */
832 const mp_limb_t
*sourceptr
= b_ptr
;
833 mp_limb_t
*destptr
= r_ptr
+ j
;
836 for (count
= b_len
; count
> 0; count
--)
838 mp_limb_t source1
= *sourceptr
++;
839 mp_limb_t source2
= *destptr
;
840 *destptr
++ = source1
+ source2
+ carry
;
843 ? source1
>= (mp_limb_t
) ~source2
844 : source1
> (mp_limb_t
) ~source2
);
847 /* Forget about the carry and about r[j+n]. */
850 /* q* is determined. Store it as q[j]. */
859 if (q_ptr
[q_len
- 1] == 0)
861 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
862 b is shifted left by s bits. */
863 /* Shift r right by s bits. */
866 mp_limb_t ptr
= r_ptr
+ r_len
;
867 mp_twolimb_t accu
= 0;
869 for (count
= r_len
; count
> 0; count
--)
871 accu
= (mp_twolimb_t
) (mp_limb_t
) accu
<< GMP_LIMB_BITS
;
872 accu
+= (mp_twolimb_t
) *--ptr
<< (GMP_LIMB_BITS
- s
);
873 *ptr
= (mp_limb_t
) (accu
>> GMP_LIMB_BITS
);
878 while (r_len
> 0 && r_ptr
[r_len
- 1] == 0)
881 /* Compare r << 1 with b. */
889 (i
<= r_len
&& i
> 0 ? r_ptr
[i
- 1] >> (GMP_LIMB_BITS
- 1) : 0)
890 | (i
< r_len
? r_ptr
[i
] << 1 : 0);
891 mp_limb_t b_i
= (i
< b_len
? b_ptr
[i
] : 0);
901 if (q_len
> 0 && ((q_ptr
[0] & 1) != 0))
906 for (i
= 0; i
< q_len
; i
++)
907 if (++(q_ptr
[i
]) != 0)
912 if (tmp_roomptr
!= NULL
)
919 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
921 Destroys the contents of a.
922 Return the allocated memory - containing the decimal digits in low-to-high
923 order, terminated with a NUL character - in case of success, NULL in case
924 of memory allocation failure. */
926 convert_to_decimal (mpn_t a
, size_t extra_zeroes
)
928 mp_limb_t
*a_ptr
= a
.limbs
;
929 size_t a_len
= a
.nlimbs
;
930 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
931 size_t c_len
= 9 * ((size_t)(a_len
* (GMP_LIMB_BITS
* 0.03345f
)) + 1);
932 /* We need extra_zeroes bytes for zeroes, followed by c_len bytes for the
933 digits of a, followed by 1 byte for the terminating NUL. */
934 char *c_ptr
= (char *) malloc (xsum (xsum (extra_zeroes
, c_len
), 1));
938 for (; extra_zeroes
> 0; extra_zeroes
--)
942 /* Divide a by 10^9, in-place. */
943 mp_limb_t remainder
= 0;
944 mp_limb_t
*ptr
= a_ptr
+ a_len
;
946 for (count
= a_len
; count
> 0; count
--)
949 ((mp_twolimb_t
) remainder
<< GMP_LIMB_BITS
) | *--ptr
;
950 *ptr
= num
/ 1000000000;
951 remainder
= num
% 1000000000;
953 /* Store the remainder as 9 decimal digits. */
954 for (count
= 9; count
> 0; count
--)
956 *d_ptr
++ = '0' + (remainder
% 10);
957 remainder
= remainder
/ 10;
960 if (a_ptr
[a_len
- 1] == 0)
963 /* Remove leading zeroes. */
964 while (d_ptr
> c_ptr
&& d_ptr
[-1] == '0')
966 /* But keep at least one zero. */
969 /* Terminate the string. */
975 # if NEED_PRINTF_LONG_DOUBLE
977 /* Assuming x is finite and >= 0:
978 write x as x = 2^e * m, where m is a bignum.
979 Return the allocated memory in case of success, NULL in case of memory
980 allocation failure. */
982 decode_long_double (long double x
, int *ep
, mpn_t
*mp
)
989 /* Allocate memory for result. */
990 m
.nlimbs
= (LDBL_MANT_BIT
+ GMP_LIMB_BITS
- 1) / GMP_LIMB_BITS
;
991 m
.limbs
= (mp_limb_t
*) malloc (m
.nlimbs
* sizeof (mp_limb_t
));
994 /* Split into exponential part and mantissa. */
995 y
= frexpl (x
, &exp
);
996 if (!(y
>= 0.0L && y
< 1.0L))
998 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the
999 latter is an integer. */
1000 /* Convert the mantissa (y * 2^LDBL_MANT_BIT) to a sequence of limbs.
1001 I'm not sure whether it's safe to cast a 'long double' value between
1002 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1003 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1005 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
1006 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1009 y
*= (mp_limb_t
) 1 << (LDBL_MANT_BIT
% (GMP_LIMB_BITS
/ 2));
1012 if (!(y
>= 0.0L && y
< 1.0L))
1014 y
*= (mp_limb_t
) 1 << (GMP_LIMB_BITS
/ 2);
1017 if (!(y
>= 0.0L && y
< 1.0L))
1019 m
.limbs
[LDBL_MANT_BIT
/ GMP_LIMB_BITS
] = (hi
<< (GMP_LIMB_BITS
/ 2)) | lo
;
1024 y
*= (mp_limb_t
) 1 << (LDBL_MANT_BIT
% GMP_LIMB_BITS
);
1027 if (!(y
>= 0.0L && y
< 1.0L))
1029 m
.limbs
[LDBL_MANT_BIT
/ GMP_LIMB_BITS
] = d
;
1033 for (i
= LDBL_MANT_BIT
/ GMP_LIMB_BITS
; i
> 0; )
1036 y
*= (mp_limb_t
) 1 << (GMP_LIMB_BITS
/ 2);
1039 if (!(y
>= 0.0L && y
< 1.0L))
1041 y
*= (mp_limb_t
) 1 << (GMP_LIMB_BITS
/ 2);
1044 if (!(y
>= 0.0L && y
< 1.0L))
1046 m
.limbs
[--i
] = (hi
<< (GMP_LIMB_BITS
/ 2)) | lo
;
1048 # if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
1054 while (m
.nlimbs
> 0 && m
.limbs
[m
.nlimbs
- 1] == 0)
1057 *ep
= exp
- LDBL_MANT_BIT
;
1063 # if NEED_PRINTF_DOUBLE
1065 /* Assuming x is finite and >= 0:
1066 write x as x = 2^e * m, where m is a bignum.
1067 Return the allocated memory in case of success, NULL in case of memory
1068 allocation failure. */
1070 decode_double (double x
, int *ep
, mpn_t
*mp
)
1077 /* Allocate memory for result. */
1078 m
.nlimbs
= (DBL_MANT_BIT
+ GMP_LIMB_BITS
- 1) / GMP_LIMB_BITS
;
1079 m
.limbs
= (mp_limb_t
*) malloc (m
.nlimbs
* sizeof (mp_limb_t
));
1080 if (m
.limbs
== NULL
)
1082 /* Split into exponential part and mantissa. */
1083 y
= frexp (x
, &exp
);
1084 if (!(y
>= 0.0 && y
< 1.0))
1086 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the
1087 latter is an integer. */
1088 /* Convert the mantissa (y * 2^DBL_MANT_BIT) to a sequence of limbs.
1089 I'm not sure whether it's safe to cast a 'double' value between
1090 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1091 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1093 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
1094 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1097 y
*= (mp_limb_t
) 1 << (DBL_MANT_BIT
% (GMP_LIMB_BITS
/ 2));
1100 if (!(y
>= 0.0 && y
< 1.0))
1102 y
*= (mp_limb_t
) 1 << (GMP_LIMB_BITS
/ 2);
1105 if (!(y
>= 0.0 && y
< 1.0))
1107 m
.limbs
[DBL_MANT_BIT
/ GMP_LIMB_BITS
] = (hi
<< (GMP_LIMB_BITS
/ 2)) | lo
;
1112 y
*= (mp_limb_t
) 1 << (DBL_MANT_BIT
% GMP_LIMB_BITS
);
1115 if (!(y
>= 0.0 && y
< 1.0))
1117 m
.limbs
[DBL_MANT_BIT
/ GMP_LIMB_BITS
] = d
;
1121 for (i
= DBL_MANT_BIT
/ GMP_LIMB_BITS
; i
> 0; )
1124 y
*= (mp_limb_t
) 1 << (GMP_LIMB_BITS
/ 2);
1127 if (!(y
>= 0.0 && y
< 1.0))
1129 y
*= (mp_limb_t
) 1 << (GMP_LIMB_BITS
/ 2);
1132 if (!(y
>= 0.0 && y
< 1.0))
1134 m
.limbs
[--i
] = (hi
<< (GMP_LIMB_BITS
/ 2)) | lo
;
1139 while (m
.nlimbs
> 0 && m
.limbs
[m
.nlimbs
- 1] == 0)
1142 *ep
= exp
- DBL_MANT_BIT
;
1148 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1149 Returns the decimal representation of round (x * 10^n).
1150 Return the allocated memory - containing the decimal digits in low-to-high
1151 order, terminated with a NUL character - in case of success, NULL in case
1152 of memory allocation failure. */
1154 scale10_round_decimal_decoded (int e
, mpn_t m
, void *memory
, int n
)
1157 size_t extra_zeroes
;
1160 mp_limb_t
*pow5_ptr
;
1162 unsigned int s_limbs
;
1163 unsigned int s_bits
;
1171 /* x = 2^e * m, hence
1172 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1173 = round (2^s * 5^n * m). */
1176 /* Factor out a common power of 10 if possible. */
1179 extra_zeroes
= (s
< n
? s
: n
);
1183 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1184 Before converting to decimal, we need to compute
1185 z = round (2^s * 5^n * m). */
1186 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1187 sign. 2.322 is slightly larger than log(5)/log(2). */
1188 abs_n
= (n
>= 0 ? n
: -n
);
1189 abs_s
= (s
>= 0 ? s
: -s
);
1190 pow5_ptr
= (mp_limb_t
*) malloc (((int)(abs_n
* (2.322f
/ GMP_LIMB_BITS
)) + 1
1191 + abs_s
/ GMP_LIMB_BITS
+ 1)
1192 * sizeof (mp_limb_t
));
1193 if (pow5_ptr
== NULL
)
1198 /* Initialize with 1. */
1201 /* Multiply with 5^|n|. */
1204 static mp_limb_t
const small_pow5
[13 + 1] =
1206 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1207 48828125, 244140625, 1220703125
1210 for (n13
= 0; n13
<= abs_n
; n13
+= 13)
1212 mp_limb_t digit1
= small_pow5
[n13
+ 13 <= abs_n
? 13 : abs_n
- n13
];
1214 mp_twolimb_t carry
= 0;
1215 for (j
= 0; j
< pow5_len
; j
++)
1217 mp_limb_t digit2
= pow5_ptr
[j
];
1218 carry
+= (mp_twolimb_t
) digit1
* (mp_twolimb_t
) digit2
;
1219 pow5_ptr
[j
] = (mp_limb_t
) carry
;
1220 carry
= carry
>> GMP_LIMB_BITS
;
1223 pow5_ptr
[pow5_len
++] = (mp_limb_t
) carry
;
1226 s_limbs
= abs_s
/ GMP_LIMB_BITS
;
1227 s_bits
= abs_s
% GMP_LIMB_BITS
;
1228 if (n
>= 0 ? s
>= 0 : s
<= 0)
1230 /* Multiply with 2^|s|. */
1233 mp_limb_t
*ptr
= pow5_ptr
;
1234 mp_twolimb_t accu
= 0;
1236 for (count
= pow5_len
; count
> 0; count
--)
1238 accu
+= (mp_twolimb_t
) *ptr
<< s_bits
;
1239 *ptr
++ = (mp_limb_t
) accu
;
1240 accu
= accu
>> GMP_LIMB_BITS
;
1244 *ptr
= (mp_limb_t
) accu
;
1251 for (count
= pow5_len
; count
> 0;)
1254 pow5_ptr
[s_limbs
+ count
] = pow5_ptr
[count
];
1256 for (count
= s_limbs
; count
> 0;)
1259 pow5_ptr
[count
] = 0;
1261 pow5_len
+= s_limbs
;
1263 pow5
.limbs
= pow5_ptr
;
1264 pow5
.nlimbs
= pow5_len
;
1267 /* Multiply m with pow5. No division needed. */
1268 z_memory
= multiply (m
, pow5
, &z
);
1272 /* Divide m by pow5 and round. */
1273 z_memory
= divide (m
, pow5
, &z
);
1278 pow5
.limbs
= pow5_ptr
;
1279 pow5
.nlimbs
= pow5_len
;
1283 Multiply m with pow5, then divide by 2^|s|. */
1287 tmp_memory
= multiply (m
, pow5
, &numerator
);
1288 if (tmp_memory
== NULL
)
1294 /* Construct 2^|s|. */
1296 mp_limb_t
*ptr
= pow5_ptr
+ pow5_len
;
1298 for (i
= 0; i
< s_limbs
; i
++)
1300 ptr
[s_limbs
] = (mp_limb_t
) 1 << s_bits
;
1301 denominator
.limbs
= ptr
;
1302 denominator
.nlimbs
= s_limbs
+ 1;
1304 z_memory
= divide (numerator
, denominator
, &z
);
1310 Multiply m with 2^s, then divide by pow5. */
1313 num_ptr
= (mp_limb_t
*) malloc ((m
.nlimbs
+ s_limbs
+ 1)
1314 * sizeof (mp_limb_t
));
1315 if (num_ptr
== NULL
)
1322 mp_limb_t
*destptr
= num_ptr
;
1325 for (i
= 0; i
< s_limbs
; i
++)
1330 const mp_limb_t
*sourceptr
= m
.limbs
;
1331 mp_twolimb_t accu
= 0;
1333 for (count
= m
.nlimbs
; count
> 0; count
--)
1335 accu
+= (mp_twolimb_t
) *sourceptr
++ << s_bits
;
1336 *destptr
++ = (mp_limb_t
) accu
;
1337 accu
= accu
>> GMP_LIMB_BITS
;
1340 *destptr
++ = (mp_limb_t
) accu
;
1344 const mp_limb_t
*sourceptr
= m
.limbs
;
1346 for (count
= m
.nlimbs
; count
> 0; count
--)
1347 *destptr
++ = *sourceptr
++;
1349 numerator
.limbs
= num_ptr
;
1350 numerator
.nlimbs
= destptr
- num_ptr
;
1352 z_memory
= divide (numerator
, pow5
, &z
);
1359 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1361 if (z_memory
== NULL
)
1363 digits
= convert_to_decimal (z
, extra_zeroes
);
1368 # if NEED_PRINTF_LONG_DOUBLE
1370 /* Assuming x is finite and >= 0, and n is an integer:
1371 Returns the decimal representation of round (x * 10^n).
1372 Return the allocated memory - containing the decimal digits in low-to-high
1373 order, terminated with a NUL character - in case of success, NULL in case
1374 of memory allocation failure. */
1376 scale10_round_decimal_long_double (long double x
, int n
)
1380 void *memory
= decode_long_double (x
, &e
, &m
);
1381 return scale10_round_decimal_decoded (e
, m
, memory
, n
);
1386 # if NEED_PRINTF_DOUBLE
1388 /* Assuming x is finite and >= 0, and n is an integer:
1389 Returns the decimal representation of round (x * 10^n).
1390 Return the allocated memory - containing the decimal digits in low-to-high
1391 order, terminated with a NUL character - in case of success, NULL in case
1392 of memory allocation failure. */
1394 scale10_round_decimal_double (double x
, int n
)
1398 void *memory
= decode_double (x
, &e
, &m
);
1399 return scale10_round_decimal_decoded (e
, m
, memory
, n
);
1404 # if NEED_PRINTF_LONG_DOUBLE
1406 /* Assuming x is finite and > 0:
1407 Return an approximation for n with 10^n <= x < 10^(n+1).
1408 The approximation is usually the right n, but may be off by 1 sometimes. */
1410 floorlog10l (long double x
)
1417 /* Split into exponential part and mantissa. */
1418 y
= frexpl (x
, &exp
);
1419 if (!(y
>= 0.0L && y
< 1.0L))
1425 while (y
< (1.0L / (1 << (GMP_LIMB_BITS
/ 2)) / (1 << (GMP_LIMB_BITS
/ 2))))
1427 y
*= 1.0L * (1 << (GMP_LIMB_BITS
/ 2)) * (1 << (GMP_LIMB_BITS
/ 2));
1428 exp
-= GMP_LIMB_BITS
;
1430 if (y
< (1.0L / (1 << 16)))
1432 y
*= 1.0L * (1 << 16);
1435 if (y
< (1.0L / (1 << 8)))
1437 y
*= 1.0L * (1 << 8);
1440 if (y
< (1.0L / (1 << 4)))
1442 y
*= 1.0L * (1 << 4);
1445 if (y
< (1.0L / (1 << 2)))
1447 y
*= 1.0L * (1 << 2);
1450 if (y
< (1.0L / (1 << 1)))
1452 y
*= 1.0L * (1 << 1);
1456 if (!(y
>= 0.5L && y
< 1.0L))
1458 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1461 if (z
< 0.70710678118654752444)
1463 z
*= 1.4142135623730950488;
1466 if (z
< 0.8408964152537145431)
1468 z
*= 1.1892071150027210667;
1471 if (z
< 0.91700404320467123175)
1473 z
*= 1.0905077326652576592;
1476 if (z
< 0.9576032806985736469)
1478 z
*= 1.0442737824274138403;
1481 /* Now 0.95 <= z <= 1.01. */
1483 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1484 Four terms are enough to get an approximation with error < 10^-7. */
1485 l
-= 1.4426950408889634074 * z
* (1.0 + z
* (0.5 + z
* ((1.0 / 3) + z
* 0.25)));
1486 /* Finally multiply with log(2)/log(10), yields an approximation for
1488 l
*= 0.30102999566398119523;
1489 /* Round down to the next integer. */
1490 return (int) l
+ (l
< 0 ? -1 : 0);
1495 # if NEED_PRINTF_DOUBLE
1497 /* Assuming x is finite and > 0:
1498 Return an approximation for n with 10^n <= x < 10^(n+1).
1499 The approximation is usually the right n, but may be off by 1 sometimes. */
1501 floorlog10 (double x
)
1508 /* Split into exponential part and mantissa. */
1509 y
= frexp (x
, &exp
);
1510 if (!(y
>= 0.0 && y
< 1.0))
1516 while (y
< (1.0 / (1 << (GMP_LIMB_BITS
/ 2)) / (1 << (GMP_LIMB_BITS
/ 2))))
1518 y
*= 1.0 * (1 << (GMP_LIMB_BITS
/ 2)) * (1 << (GMP_LIMB_BITS
/ 2));
1519 exp
-= GMP_LIMB_BITS
;
1521 if (y
< (1.0 / (1 << 16)))
1523 y
*= 1.0 * (1 << 16);
1526 if (y
< (1.0 / (1 << 8)))
1528 y
*= 1.0 * (1 << 8);
1531 if (y
< (1.0 / (1 << 4)))
1533 y
*= 1.0 * (1 << 4);
1536 if (y
< (1.0 / (1 << 2)))
1538 y
*= 1.0 * (1 << 2);
1541 if (y
< (1.0 / (1 << 1)))
1543 y
*= 1.0 * (1 << 1);
1547 if (!(y
>= 0.5 && y
< 1.0))
1549 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1552 if (z
< 0.70710678118654752444)
1554 z
*= 1.4142135623730950488;
1557 if (z
< 0.8408964152537145431)
1559 z
*= 1.1892071150027210667;
1562 if (z
< 0.91700404320467123175)
1564 z
*= 1.0905077326652576592;
1567 if (z
< 0.9576032806985736469)
1569 z
*= 1.0442737824274138403;
1572 /* Now 0.95 <= z <= 1.01. */
1574 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1575 Four terms are enough to get an approximation with error < 10^-7. */
1576 l
-= 1.4426950408889634074 * z
* (1.0 + z
* (0.5 + z
* ((1.0 / 3) + z
* 0.25)));
1577 /* Finally multiply with log(2)/log(10), yields an approximation for
1579 l
*= 0.30102999566398119523;
1580 /* Round down to the next integer. */
1581 return (int) l
+ (l
< 0 ? -1 : 0);
1586 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1587 a single '1' digit. */
1589 is_borderline (const char *digits
, size_t precision
)
1591 for (; precision
> 0; precision
--, digits
++)
1597 return *digits
== '\0';
1602 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF
1604 /* Use a different function name, to make it possible that the 'wchar_t'
1605 parametrization and the 'char' parametrization get compiled in the same
1606 translation unit. */
1607 # if WIDE_CHAR_VERSION
1608 # define MAX_ROOM_NEEDED wmax_room_needed
1610 # define MAX_ROOM_NEEDED max_room_needed
1613 /* Returns the number of TCHAR_T units needed as temporary space for the result
1614 of sprintf or SNPRINTF of a single conversion directive. */
1616 MAX_ROOM_NEEDED (const arguments
*ap
, size_t arg_index
, FCHAR_T conversion
,
1617 arg_type type
, int flags
, size_t width
, int has_precision
,
1618 size_t precision
, int pad_ourselves
)
1624 case 'd': case 'i': case 'u':
1625 if (type
== TYPE_LONGLONGINT
|| type
== TYPE_ULONGLONGINT
)
1627 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1628 * 0.30103 /* binary -> decimal */
1630 + 1; /* turn floor into ceil */
1631 else if (type
== TYPE_LONGINT
|| type
== TYPE_ULONGINT
)
1633 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1634 * 0.30103 /* binary -> decimal */
1636 + 1; /* turn floor into ceil */
1639 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1640 * 0.30103 /* binary -> decimal */
1642 + 1; /* turn floor into ceil */
1643 if (tmp_length
< precision
)
1644 tmp_length
= precision
;
1645 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1646 tmp_length
= xsum (tmp_length
, tmp_length
);
1647 /* Add 1, to account for a leading sign. */
1648 tmp_length
= xsum (tmp_length
, 1);
1652 if (type
== TYPE_LONGLONGINT
|| type
== TYPE_ULONGLONGINT
)
1654 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1655 * 0.333334 /* binary -> octal */
1657 + 1; /* turn floor into ceil */
1658 else if (type
== TYPE_LONGINT
|| type
== TYPE_ULONGINT
)
1660 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1661 * 0.333334 /* binary -> octal */
1663 + 1; /* turn floor into ceil */
1666 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1667 * 0.333334 /* binary -> octal */
1669 + 1; /* turn floor into ceil */
1670 if (tmp_length
< precision
)
1671 tmp_length
= precision
;
1672 /* Add 1, to account for a leading sign. */
1673 tmp_length
= xsum (tmp_length
, 1);
1677 if (type
== TYPE_LONGLONGINT
|| type
== TYPE_ULONGLONGINT
)
1679 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1680 * 0.25 /* binary -> hexadecimal */
1682 + 1; /* turn floor into ceil */
1683 else if (type
== TYPE_LONGINT
|| type
== TYPE_ULONGINT
)
1685 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1686 * 0.25 /* binary -> hexadecimal */
1688 + 1; /* turn floor into ceil */
1691 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1692 * 0.25 /* binary -> hexadecimal */
1694 + 1; /* turn floor into ceil */
1695 if (tmp_length
< precision
)
1696 tmp_length
= precision
;
1697 /* Add 2, to account for a leading sign or alternate form. */
1698 tmp_length
= xsum (tmp_length
, 2);
1702 if (type
== TYPE_LONGDOUBLE
)
1704 (unsigned int) (LDBL_MAX_EXP
1705 * 0.30103 /* binary -> decimal */
1706 * 2 /* estimate for FLAG_GROUP */
1708 + 1 /* turn floor into ceil */
1709 + 10; /* sign, decimal point etc. */
1712 (unsigned int) (DBL_MAX_EXP
1713 * 0.30103 /* binary -> decimal */
1714 * 2 /* estimate for FLAG_GROUP */
1716 + 1 /* turn floor into ceil */
1717 + 10; /* sign, decimal point etc. */
1718 tmp_length
= xsum (tmp_length
, precision
);
1721 case 'e': case 'E': case 'g': case 'G':
1723 12; /* sign, decimal point, exponent etc. */
1724 tmp_length
= xsum (tmp_length
, precision
);
1728 if (type
== TYPE_LONGDOUBLE
)
1730 (unsigned int) (LDBL_DIG
1731 * 0.831 /* decimal -> hexadecimal */
1733 + 1; /* turn floor into ceil */
1736 (unsigned int) (DBL_DIG
1737 * 0.831 /* decimal -> hexadecimal */
1739 + 1; /* turn floor into ceil */
1740 if (tmp_length
< precision
)
1741 tmp_length
= precision
;
1742 /* Account for sign, decimal point etc. */
1743 tmp_length
= xsum (tmp_length
, 12);
1747 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
1748 if (type
== TYPE_WIDE_CHAR
)
1750 tmp_length
= MB_CUR_MAX
;
1751 # if ENABLE_WCHAR_FALLBACK
1752 if (tmp_length
< (sizeof (wchar_t) > 2 ? 10 : 6))
1753 tmp_length
= (sizeof (wchar_t) > 2 ? 10 : 6);
1763 if (type
== TYPE_WIDE_STRING
)
1765 # if WIDE_CHAR_VERSION
1766 /* ISO C says about %ls in fwprintf:
1767 "If the precision is not specified or is greater than the size
1768 of the array, the array shall contain a null wide character."
1769 So if there is a precision, we must not use wcslen. */
1770 const wchar_t *arg
= ap
->arg
[arg_index
].a
.a_wide_string
;
1773 tmp_length
= local_wcsnlen (arg
, precision
);
1775 tmp_length
= local_wcslen (arg
);
1777 /* ISO C says about %ls in fprintf:
1778 "If a precision is specified, no more than that many bytes are
1779 written (including shift sequences, if any), and the array
1780 shall contain a null wide character if, to equal the multibyte
1781 character sequence length given by the precision, the function
1782 would need to access a wide character one past the end of the
1784 So if there is a precision, we must not use wcslen. */
1785 /* This case has already been handled separately in VASNPRINTF. */
1792 # if WIDE_CHAR_VERSION
1793 /* ISO C says about %s in fwprintf:
1794 "If the precision is not specified or is greater than the size
1795 of the converted array, the converted array shall contain a
1796 null wide character."
1797 So if there is a precision, we must not use strlen. */
1798 /* This case has already been handled separately in VASNPRINTF. */
1801 /* ISO C says about %s in fprintf:
1802 "If the precision is not specified or greater than the size of
1803 the array, the array shall contain a null character."
1804 So if there is a precision, we must not use strlen. */
1805 const char *arg
= ap
->arg
[arg_index
].a
.a_string
;
1808 tmp_length
= local_strnlen (arg
, precision
);
1810 tmp_length
= strlen (arg
);
1817 (unsigned int) (sizeof (void *) * CHAR_BIT
1818 * 0.25 /* binary -> hexadecimal */
1820 + 1 /* turn floor into ceil */
1821 + 2; /* account for leading 0x */
1830 # if ENABLE_UNISTDIO
1831 /* Padding considers the number of characters, therefore the number of
1832 elements after padding may be
1833 > max (tmp_length, width)
1835 <= tmp_length + width. */
1836 tmp_length
= xsum (tmp_length
, width
);
1838 /* Padding considers the number of elements, says POSIX. */
1839 if (tmp_length
< width
)
1844 tmp_length
= xsum (tmp_length
, 1); /* account for trailing NUL */
1852 VASNPRINTF (DCHAR_T
*resultbuf
, size_t *lengthp
,
1853 const FCHAR_T
*format
, va_list args
)
1858 if (PRINTF_PARSE (format
, &d
, &a
) < 0)
1859 /* errno is already set. */
1863 if (d.dir != d.direct_alloc_dir) \
1865 if (a.arg != a.direct_alloc_arg) \
1868 if (PRINTF_FETCHARGS (args
, &a
) < 0)
1876 size_t buf_neededlength
;
1878 TCHAR_T
*buf_malloced
;
1882 /* Output string accumulator. */
1887 /* Allocate a small buffer that will hold a directive passed to
1888 sprintf or snprintf. */
1890 xsum4 (7, d
.max_width_length
, d
.max_precision_length
, 6);
1892 if (buf_neededlength
< 4000 / sizeof (TCHAR_T
))
1894 buf
= (TCHAR_T
*) alloca (buf_neededlength
* sizeof (TCHAR_T
));
1895 buf_malloced
= NULL
;
1900 size_t buf_memsize
= xtimes (buf_neededlength
, sizeof (TCHAR_T
));
1901 if (size_overflow_p (buf_memsize
))
1902 goto out_of_memory_1
;
1903 buf
= (TCHAR_T
*) malloc (buf_memsize
);
1905 goto out_of_memory_1
;
1909 if (resultbuf
!= NULL
)
1912 allocated
= *lengthp
;
1921 result is either == resultbuf or == NULL or malloc-allocated.
1922 If length > 0, then result != NULL. */
1924 /* Ensures that allocated >= needed. Aborts through a jump to
1925 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1926 #define ENSURE_ALLOCATION(needed) \
1927 if ((needed) > allocated) \
1929 size_t memory_size; \
1932 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1933 if ((needed) > allocated) \
1934 allocated = (needed); \
1935 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1936 if (size_overflow_p (memory_size)) \
1937 goto out_of_memory; \
1938 if (result == resultbuf || result == NULL) \
1939 memory = (DCHAR_T *) malloc (memory_size); \
1941 memory = (DCHAR_T *) realloc (result, memory_size); \
1942 if (memory == NULL) \
1943 goto out_of_memory; \
1944 if (result == resultbuf && length > 0) \
1945 DCHAR_CPY (memory, result, length); \
1949 for (cp
= format
, i
= 0, dp
= &d
.dir
[0]; ; cp
= dp
->dir_end
, i
++, dp
++)
1951 if (cp
!= dp
->dir_start
)
1953 size_t n
= dp
->dir_start
- cp
;
1954 size_t augmented_length
= xsum (length
, n
);
1956 ENSURE_ALLOCATION (augmented_length
);
1957 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1958 need that the format string contains only ASCII characters
1959 if FCHAR_T and DCHAR_T are not the same type. */
1960 if (sizeof (FCHAR_T
) == sizeof (DCHAR_T
))
1962 DCHAR_CPY (result
+ length
, (const DCHAR_T
*) cp
, n
);
1963 length
= augmented_length
;
1968 result
[length
++] = *cp
++;
1975 /* Execute a single directive. */
1976 if (dp
->conversion
== '%')
1978 size_t augmented_length
;
1980 if (!(dp
->arg_index
== ARG_NONE
))
1982 augmented_length
= xsum (length
, 1);
1983 ENSURE_ALLOCATION (augmented_length
);
1984 result
[length
] = '%';
1985 length
= augmented_length
;
1989 if (!(dp
->arg_index
!= ARG_NONE
))
1992 if (dp
->conversion
== 'n')
1994 switch (a
.arg
[dp
->arg_index
].type
)
1996 case TYPE_COUNT_SCHAR_POINTER
:
1997 *a
.arg
[dp
->arg_index
].a
.a_count_schar_pointer
= length
;
1999 case TYPE_COUNT_SHORT_POINTER
:
2000 *a
.arg
[dp
->arg_index
].a
.a_count_short_pointer
= length
;
2002 case TYPE_COUNT_INT_POINTER
:
2003 *a
.arg
[dp
->arg_index
].a
.a_count_int_pointer
= length
;
2005 case TYPE_COUNT_LONGINT_POINTER
:
2006 *a
.arg
[dp
->arg_index
].a
.a_count_longint_pointer
= length
;
2008 case TYPE_COUNT_LONGLONGINT_POINTER
:
2009 *a
.arg
[dp
->arg_index
].a
.a_count_longlongint_pointer
= length
;
2016 /* The unistdio extensions. */
2017 else if (dp
->conversion
== 'U')
2019 arg_type type
= a
.arg
[dp
->arg_index
].type
;
2020 int flags
= dp
->flags
;
2028 if (dp
->width_start
!= dp
->width_end
)
2030 if (dp
->width_arg_index
!= ARG_NONE
)
2034 if (!(a
.arg
[dp
->width_arg_index
].type
== TYPE_INT
))
2036 arg
= a
.arg
[dp
->width_arg_index
].a
.a_int
;
2040 /* "A negative field width is taken as a '-' flag
2041 followed by a positive field width." */
2048 const FCHAR_T
*digitp
= dp
->width_start
;
2051 width
= xsum (xtimes (width
, 10), *digitp
++ - '0');
2052 while (digitp
!= dp
->width_end
);
2059 if (dp
->precision_start
!= dp
->precision_end
)
2061 if (dp
->precision_arg_index
!= ARG_NONE
)
2065 if (!(a
.arg
[dp
->precision_arg_index
].type
== TYPE_INT
))
2067 arg
= a
.arg
[dp
->precision_arg_index
].a
.a_int
;
2068 /* "A negative precision is taken as if the precision
2078 const FCHAR_T
*digitp
= dp
->precision_start
+ 1;
2081 while (digitp
!= dp
->precision_end
)
2082 precision
= xsum (xtimes (precision
, 10), *digitp
++ - '0');
2089 case TYPE_U8_STRING
:
2091 const uint8_t *arg
= a
.arg
[dp
->arg_index
].a
.a_u8_string
;
2092 const uint8_t *arg_end
;
2097 /* Use only PRECISION characters, from the left. */
2100 for (; precision
> 0; precision
--)
2102 int count
= u8_strmblen (arg_end
);
2107 if (!(result
== resultbuf
|| result
== NULL
))
2109 if (buf_malloced
!= NULL
)
2110 free (buf_malloced
);
2121 /* Use the entire string, and count the number of
2127 int count
= u8_strmblen (arg_end
);
2132 if (!(result
== resultbuf
|| result
== NULL
))
2134 if (buf_malloced
!= NULL
)
2135 free (buf_malloced
);
2146 /* Use the entire string. */
2147 arg_end
= arg
+ u8_strlen (arg
);
2148 /* The number of characters doesn't matter. */
2152 if (characters
< width
&& !(dp
->flags
& FLAG_LEFT
))
2154 size_t n
= width
- characters
;
2155 ENSURE_ALLOCATION (xsum (length
, n
));
2156 DCHAR_SET (result
+ length
, ' ', n
);
2160 # if DCHAR_IS_UINT8_T
2162 size_t n
= arg_end
- arg
;
2163 ENSURE_ALLOCATION (xsum (length
, n
));
2164 DCHAR_CPY (result
+ length
, arg
, n
);
2169 DCHAR_T
*converted
= result
+ length
;
2170 size_t converted_len
= allocated
- length
;
2172 /* Convert from UTF-8 to locale encoding. */
2174 u8_conv_to_encoding (locale_charset (),
2175 iconveh_question_mark
,
2176 arg
, arg_end
- arg
, NULL
,
2177 converted
, &converted_len
);
2179 /* Convert from UTF-8 to UTF-16/UTF-32. */
2181 U8_TO_DCHAR (arg
, arg_end
- arg
,
2182 converted
, &converted_len
);
2184 if (converted
== NULL
)
2186 int saved_errno
= errno
;
2187 if (!(result
== resultbuf
|| result
== NULL
))
2189 if (buf_malloced
!= NULL
)
2190 free (buf_malloced
);
2192 errno
= saved_errno
;
2195 if (converted
!= result
+ length
)
2197 ENSURE_ALLOCATION (xsum (length
, converted_len
));
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 int saved_errno
= errno
;
2313 if (!(result
== resultbuf
|| result
== NULL
))
2315 if (buf_malloced
!= NULL
)
2316 free (buf_malloced
);
2318 errno
= saved_errno
;
2321 if (converted
!= result
+ length
)
2323 ENSURE_ALLOCATION (xsum (length
, converted_len
));
2324 DCHAR_CPY (result
+ length
, converted
, converted_len
);
2327 length
+= converted_len
;
2331 if (characters
< width
&& (dp
->flags
& FLAG_LEFT
))
2333 size_t n
= width
- characters
;
2334 ENSURE_ALLOCATION (xsum (length
, n
));
2335 DCHAR_SET (result
+ length
, ' ', n
);
2341 case TYPE_U32_STRING
:
2343 const uint32_t *arg
= a
.arg
[dp
->arg_index
].a
.a_u32_string
;
2344 const uint32_t *arg_end
;
2349 /* Use only PRECISION characters, from the left. */
2352 for (; precision
> 0; precision
--)
2354 int count
= u32_strmblen (arg_end
);
2359 if (!(result
== resultbuf
|| result
== NULL
))
2361 if (buf_malloced
!= NULL
)
2362 free (buf_malloced
);
2373 /* Use the entire string, and count the number of
2379 int count
= u32_strmblen (arg_end
);
2384 if (!(result
== resultbuf
|| result
== NULL
))
2386 if (buf_malloced
!= NULL
)
2387 free (buf_malloced
);
2398 /* Use the entire string. */
2399 arg_end
= arg
+ u32_strlen (arg
);
2400 /* The number of characters doesn't matter. */
2404 if (characters
< width
&& !(dp
->flags
& FLAG_LEFT
))
2406 size_t n
= width
- characters
;
2407 ENSURE_ALLOCATION (xsum (length
, n
));
2408 DCHAR_SET (result
+ length
, ' ', n
);
2412 # if DCHAR_IS_UINT32_T
2414 size_t n
= arg_end
- arg
;
2415 ENSURE_ALLOCATION (xsum (length
, n
));
2416 DCHAR_CPY (result
+ length
, arg
, n
);
2421 DCHAR_T
*converted
= result
+ length
;
2422 size_t converted_len
= allocated
- length
;
2424 /* Convert from UTF-32 to locale encoding. */
2426 u32_conv_to_encoding (locale_charset (),
2427 iconveh_question_mark
,
2428 arg
, arg_end
- arg
, NULL
,
2429 converted
, &converted_len
);
2431 /* Convert from UTF-32 to UTF-8/UTF-16. */
2433 U32_TO_DCHAR (arg
, arg_end
- arg
,
2434 converted
, &converted_len
);
2436 if (converted
== NULL
)
2438 int saved_errno
= errno
;
2439 if (!(result
== resultbuf
|| result
== NULL
))
2441 if (buf_malloced
!= NULL
)
2442 free (buf_malloced
);
2444 errno
= saved_errno
;
2447 if (converted
!= result
+ length
)
2449 ENSURE_ALLOCATION (xsum (length
, converted_len
));
2450 DCHAR_CPY (result
+ length
, converted
, converted_len
);
2453 length
+= converted_len
;
2457 if (characters
< width
&& (dp
->flags
& FLAG_LEFT
))
2459 size_t n
= width
- characters
;
2460 ENSURE_ALLOCATION (xsum (length
, n
));
2461 DCHAR_SET (result
+ length
, ' ', n
);
2472 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL) || ENABLE_WCHAR_FALLBACK) && HAVE_WCHAR_T
2473 else if (dp
->conversion
== 's'
2474 # if WIDE_CHAR_VERSION
2475 && a
.arg
[dp
->arg_index
].type
!= TYPE_WIDE_STRING
2477 && a
.arg
[dp
->arg_index
].type
== TYPE_WIDE_STRING
2481 /* The normal handling of the 's' directive below requires
2482 allocating a temporary buffer. The determination of its
2483 length (tmp_length), in the case when a precision is
2484 specified, below requires a conversion between a char[]
2485 string and a wchar_t[] wide string. It could be done, but
2486 we have no guarantee that the implementation of sprintf will
2487 use the exactly same algorithm. Without this guarantee, it
2488 is possible to have buffer overrun bugs. In order to avoid
2489 such bugs, we implement the entire processing of the 's'
2490 directive ourselves. */
2491 int flags
= dp
->flags
;
2499 if (dp
->width_start
!= dp
->width_end
)
2501 if (dp
->width_arg_index
!= ARG_NONE
)
2505 if (!(a
.arg
[dp
->width_arg_index
].type
== TYPE_INT
))
2507 arg
= a
.arg
[dp
->width_arg_index
].a
.a_int
;
2511 /* "A negative field width is taken as a '-' flag
2512 followed by a positive field width." */
2519 const FCHAR_T
*digitp
= dp
->width_start
;
2522 width
= xsum (xtimes (width
, 10), *digitp
++ - '0');
2523 while (digitp
!= dp
->width_end
);
2530 if (dp
->precision_start
!= dp
->precision_end
)
2532 if (dp
->precision_arg_index
!= ARG_NONE
)
2536 if (!(a
.arg
[dp
->precision_arg_index
].type
== TYPE_INT
))
2538 arg
= a
.arg
[dp
->precision_arg_index
].a
.a_int
;
2539 /* "A negative precision is taken as if the precision
2549 const FCHAR_T
*digitp
= dp
->precision_start
+ 1;
2552 while (digitp
!= dp
->precision_end
)
2553 precision
= xsum (xtimes (precision
, 10), *digitp
++ - '0');
2558 # if WIDE_CHAR_VERSION
2559 /* %s in vasnwprintf. See the specification of fwprintf. */
2561 const char *arg
= a
.arg
[dp
->arg_index
].a
.a_string
;
2562 const char *arg_end
;
2567 /* Use only as many bytes as needed to produce PRECISION
2568 wide characters, from the left. */
2571 memset (&state
, '\0', sizeof (mbstate_t));
2575 for (; precision
> 0; precision
--)
2579 count
= mbrlen (arg_end
, MB_CUR_MAX
, &state
);
2581 count
= mblen (arg_end
, MB_CUR_MAX
);
2584 /* Found the terminating NUL. */
2588 /* Invalid or incomplete multibyte character. */
2589 if (!(result
== resultbuf
|| result
== NULL
))
2591 if (buf_malloced
!= NULL
)
2592 free (buf_malloced
);
2603 /* Use the entire string, and count the number of wide
2607 memset (&state
, '\0', sizeof (mbstate_t));
2615 count
= mbrlen (arg_end
, MB_CUR_MAX
, &state
);
2617 count
= mblen (arg_end
, MB_CUR_MAX
);
2620 /* Found the terminating NUL. */
2624 /* Invalid or incomplete multibyte character. */
2625 if (!(result
== resultbuf
|| result
== NULL
))
2627 if (buf_malloced
!= NULL
)
2628 free (buf_malloced
);
2639 /* Use the entire string. */
2640 arg_end
= arg
+ strlen (arg
);
2641 /* The number of characters doesn't matter. */
2645 if (characters
< width
&& !(dp
->flags
& FLAG_LEFT
))
2647 size_t n
= width
- characters
;
2648 ENSURE_ALLOCATION (xsum (length
, n
));
2649 DCHAR_SET (result
+ length
, ' ', n
);
2653 if (has_precision
|| has_width
)
2655 /* We know the number of wide characters in advance. */
2659 memset (&state
, '\0', sizeof (mbstate_t));
2661 ENSURE_ALLOCATION (xsum (length
, characters
));
2662 for (remaining
= characters
; remaining
> 0; remaining
--)
2667 count
= mbrtowc (&wc
, arg
, arg_end
- arg
, &state
);
2669 count
= mbtowc (&wc
, arg
, arg_end
- arg
);
2672 /* mbrtowc not consistent with mbrlen, or mbtowc
2673 not consistent with mblen. */
2675 result
[length
++] = wc
;
2678 if (!(arg
== arg_end
))
2685 memset (&state
, '\0', sizeof (mbstate_t));
2687 while (arg
< arg_end
)
2692 count
= mbrtowc (&wc
, arg
, arg_end
- arg
, &state
);
2694 count
= mbtowc (&wc
, arg
, arg_end
- arg
);
2697 /* mbrtowc not consistent with mbrlen, or mbtowc
2698 not consistent with mblen. */
2700 ENSURE_ALLOCATION (xsum (length
, 1));
2701 result
[length
++] = wc
;
2706 if (characters
< width
&& (dp
->flags
& FLAG_LEFT
))
2708 size_t n
= width
- characters
;
2709 ENSURE_ALLOCATION (xsum (length
, n
));
2710 DCHAR_SET (result
+ length
, ' ', n
);
2715 /* %ls in vasnprintf. See the specification of fprintf. */
2717 const wchar_t *arg
= a
.arg
[dp
->arg_index
].a
.a_wide_string
;
2718 const wchar_t *arg_end
;
2720 # if !DCHAR_IS_TCHAR
2721 /* This code assumes that TCHAR_T is 'char'. */
2722 verify (sizeof (TCHAR_T
) == 1);
2731 /* Use only as many wide characters as needed to produce
2732 at most PRECISION bytes, from the left. */
2733 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2735 memset (&state
, '\0', sizeof (mbstate_t));
2739 while (precision
> 0)
2741 char cbuf
[64]; /* Assume MB_CUR_MAX <= 64. */
2745 /* Found the terminating null wide character. */
2747 count
= local_wcrtomb (cbuf
, *arg_end
, &state
);
2750 /* Cannot convert. */
2751 if (!(result
== resultbuf
|| result
== NULL
))
2753 if (buf_malloced
!= NULL
)
2754 free (buf_malloced
);
2759 if (precision
< (unsigned int) count
)
2762 characters
+= count
;
2772 /* Use the entire string, and count the number of
2774 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2776 memset (&state
, '\0', sizeof (mbstate_t));
2782 char cbuf
[64]; /* Assume MB_CUR_MAX <= 64. */
2786 /* Found the terminating null wide character. */
2788 count
= local_wcrtomb (cbuf
, *arg_end
, &state
);
2791 /* Cannot convert. */
2792 if (!(result
== resultbuf
|| result
== NULL
))
2794 if (buf_malloced
!= NULL
)
2795 free (buf_malloced
);
2801 characters
+= count
;
2807 /* Use the entire string. */
2808 arg_end
= arg
+ local_wcslen (arg
);
2809 /* The number of bytes doesn't matter. */
2814 # if !DCHAR_IS_TCHAR
2815 /* Convert the string into a piece of temporary memory. */
2816 tmpsrc
= (TCHAR_T
*) malloc (characters
* sizeof (TCHAR_T
));
2820 TCHAR_T
*tmpptr
= tmpsrc
;
2822 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2824 memset (&state
, '\0', sizeof (mbstate_t));
2826 for (remaining
= characters
; remaining
> 0; )
2828 char cbuf
[64]; /* Assume MB_CUR_MAX <= 64. */
2833 count
= local_wcrtomb (cbuf
, *arg
, &state
);
2835 /* Inconsistency. */
2837 memcpy (tmpptr
, cbuf
, count
);
2842 if (!(arg
== arg_end
))
2846 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2848 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2849 iconveh_question_mark
,
2855 int saved_errno
= errno
;
2857 if (!(result
== resultbuf
|| result
== NULL
))
2859 if (buf_malloced
!= NULL
)
2860 free (buf_malloced
);
2862 errno
= saved_errno
;
2870 # if ENABLE_UNISTDIO
2871 /* Outside POSIX, it's preferable to compare the width
2872 against the number of _characters_ of the converted
2874 w
= DCHAR_MBSNLEN (result
+ length
, characters
);
2876 /* The width is compared against the number of _bytes_
2877 of the converted value, says POSIX. */
2882 /* w doesn't matter. */
2885 if (w
< width
&& !(dp
->flags
& FLAG_LEFT
))
2887 size_t n
= width
- w
;
2888 ENSURE_ALLOCATION (xsum (length
, n
));
2889 DCHAR_SET (result
+ length
, ' ', n
);
2894 if (has_precision
|| has_width
)
2896 /* We know the number of bytes in advance. */
2898 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2900 memset (&state
, '\0', sizeof (mbstate_t));
2902 ENSURE_ALLOCATION (xsum (length
, characters
));
2903 for (remaining
= characters
; remaining
> 0; )
2905 char cbuf
[64]; /* Assume MB_CUR_MAX <= 64. */
2910 count
= local_wcrtomb (cbuf
, *arg
, &state
);
2912 /* Inconsistency. */
2914 memcpy (result
+ length
, cbuf
, count
);
2919 if (!(arg
== arg_end
))
2924 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2926 memset (&state
, '\0', sizeof (mbstate_t));
2928 while (arg
< arg_end
)
2930 char cbuf
[64]; /* Assume MB_CUR_MAX <= 64. */
2935 count
= local_wcrtomb (cbuf
, *arg
, &state
);
2938 /* Cannot convert. */
2939 if (!(result
== resultbuf
|| result
== NULL
))
2941 if (buf_malloced
!= NULL
)
2942 free (buf_malloced
);
2947 ENSURE_ALLOCATION (xsum (length
, count
));
2948 memcpy (result
+ length
, cbuf
, count
);
2954 ENSURE_ALLOCATION (xsum (length
, tmpdst_len
));
2955 DCHAR_CPY (result
+ length
, tmpdst
, tmpdst_len
);
2957 length
+= tmpdst_len
;
2960 if (w
< width
&& (dp
->flags
& FLAG_LEFT
))
2962 size_t n
= width
- w
;
2963 ENSURE_ALLOCATION (xsum (length
, n
));
2964 DCHAR_SET (result
+ length
, ' ', n
);
2971 #if ENABLE_WCHAR_FALLBACK && HAVE_WINT_T && !WIDE_CHAR_VERSION
2972 else if (dp
->conversion
== 'c'
2973 && a
.arg
[dp
->arg_index
].type
== TYPE_WIDE_CHAR
)
2975 /* Implement the 'lc' directive ourselves, in order to provide
2976 the fallback that avoids EILSEQ. */
2977 int flags
= dp
->flags
;
2983 if (dp
->width_start
!= dp
->width_end
)
2985 if (dp
->width_arg_index
!= ARG_NONE
)
2989 if (!(a
.arg
[dp
->width_arg_index
].type
== TYPE_INT
))
2991 arg
= a
.arg
[dp
->width_arg_index
].a
.a_int
;
2995 /* "A negative field width is taken as a '-' flag
2996 followed by a positive field width." */
3003 const FCHAR_T
*digitp
= dp
->width_start
;
3006 width
= xsum (xtimes (width
, 10), *digitp
++ - '0');
3007 while (digitp
!= dp
->width_end
);
3012 /* %lc in vasnprintf. See the specification of fprintf. */
3014 wchar_t arg
= (wchar_t) a
.arg
[dp
->arg_index
].a
.a_wide_char
;
3016 # if !DCHAR_IS_TCHAR
3017 /* This code assumes that TCHAR_T is 'char'. */
3018 verify (sizeof (TCHAR_T
) == 1);
3019 TCHAR_T tmpsrc
[64]; /* Assume MB_CUR_MAX <= 64. */
3029 /* Count the number of bytes. */
3033 char cbuf
[64]; /* Assume MB_CUR_MAX <= 64. */
3035 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3037 memset (&state
, '\0', sizeof (mbstate_t));
3040 count
= local_wcrtomb (cbuf
, arg
, &state
);
3042 /* Inconsistency. */
3050 /* The number of bytes doesn't matter. */
3055 # if !DCHAR_IS_TCHAR
3056 /* Convert the string into a piece of temporary memory. */
3057 if (characters
> 0) /* implies arg != 0 */
3059 char cbuf
[64]; /* Assume MB_CUR_MAX <= 64. */
3061 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3063 memset (&state
, '\0', sizeof (mbstate_t));
3066 count
= local_wcrtomb (cbuf
, arg
, &state
);
3068 /* Inconsistency. */
3070 memcpy (tmpsrc
, cbuf
, count
);
3073 /* Convert from TCHAR_T[] to DCHAR_T[]. */
3075 DCHAR_CONV_FROM_ENCODING (locale_charset (),
3076 iconveh_question_mark
,
3082 int saved_errno
= errno
;
3083 if (!(result
== resultbuf
|| result
== NULL
))
3085 if (buf_malloced
!= NULL
)
3086 free (buf_malloced
);
3088 errno
= saved_errno
;
3095 # if ENABLE_UNISTDIO
3096 /* Outside POSIX, it's preferable to compare the width
3097 against the number of _characters_ of the converted
3099 w
= DCHAR_MBSNLEN (result
+ length
, characters
);
3101 /* The width is compared against the number of _bytes_
3102 of the converted value, says POSIX. */
3107 /* w doesn't matter. */
3110 if (w
< width
&& !(dp
->flags
& FLAG_LEFT
))
3112 size_t n
= width
- w
;
3113 ENSURE_ALLOCATION (xsum (length
, n
));
3114 DCHAR_SET (result
+ length
, ' ', n
);
3121 /* We know the number of bytes in advance. */
3122 ENSURE_ALLOCATION (xsum (length
, characters
));
3123 if (characters
> 0) /* implies arg != 0 */
3126 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3128 memset (&state
, '\0', sizeof (mbstate_t));
3131 count
= local_wcrtomb (result
+ length
, arg
, &state
);
3133 /* Inconsistency. */
3142 char cbuf
[64]; /* Assume MB_CUR_MAX <= 64. */
3144 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3146 memset (&state
, '\0', sizeof (mbstate_t));
3149 count
= local_wcrtomb (cbuf
, arg
, &state
);
3151 /* Inconsistency. */
3153 ENSURE_ALLOCATION (xsum (length
, count
));
3154 memcpy (result
+ length
, cbuf
, count
);
3159 ENSURE_ALLOCATION (xsum (length
, tmpdst_len
));
3160 DCHAR_CPY (result
+ length
, tmpdst
, tmpdst_len
);
3162 length
+= tmpdst_len
;
3165 if (w
< width
&& (dp
->flags
& FLAG_LEFT
))
3167 size_t n
= width
- w
;
3168 ENSURE_ALLOCATION (xsum (length
, n
));
3169 DCHAR_SET (result
+ length
, ' ', n
);
3175 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
3176 else if ((dp
->conversion
== 'a' || dp
->conversion
== 'A')
3177 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
3179 # if NEED_PRINTF_DOUBLE
3180 || a
.arg
[dp
->arg_index
].type
== TYPE_DOUBLE
3182 # if NEED_PRINTF_LONG_DOUBLE
3183 || a
.arg
[dp
->arg_index
].type
== TYPE_LONGDOUBLE
3189 arg_type type
= a
.arg
[dp
->arg_index
].type
;
3190 int flags
= dp
->flags
;
3196 DCHAR_T tmpbuf
[700];
3202 if (dp
->width_start
!= dp
->width_end
)
3204 if (dp
->width_arg_index
!= ARG_NONE
)
3208 if (!(a
.arg
[dp
->width_arg_index
].type
== TYPE_INT
))
3210 arg
= a
.arg
[dp
->width_arg_index
].a
.a_int
;
3214 /* "A negative field width is taken as a '-' flag
3215 followed by a positive field width." */
3222 const FCHAR_T
*digitp
= dp
->width_start
;
3225 width
= xsum (xtimes (width
, 10), *digitp
++ - '0');
3226 while (digitp
!= dp
->width_end
);
3232 if (dp
->precision_start
!= dp
->precision_end
)
3234 if (dp
->precision_arg_index
!= ARG_NONE
)
3238 if (!(a
.arg
[dp
->precision_arg_index
].type
== TYPE_INT
))
3240 arg
= a
.arg
[dp
->precision_arg_index
].a
.a_int
;
3241 /* "A negative precision is taken as if the precision
3251 const FCHAR_T
*digitp
= dp
->precision_start
+ 1;
3254 while (digitp
!= dp
->precision_end
)
3255 precision
= xsum (xtimes (precision
, 10), *digitp
++ - '0');
3260 /* Allocate a temporary buffer of sufficient size. */
3261 if (type
== TYPE_LONGDOUBLE
)
3263 (unsigned int) ((LDBL_DIG
+ 1)
3264 * 0.831 /* decimal -> hexadecimal */
3266 + 1; /* turn floor into ceil */
3269 (unsigned int) ((DBL_DIG
+ 1)
3270 * 0.831 /* decimal -> hexadecimal */
3272 + 1; /* turn floor into ceil */
3273 if (tmp_length
< precision
)
3274 tmp_length
= precision
;
3275 /* Account for sign, decimal point etc. */
3276 tmp_length
= xsum (tmp_length
, 12);
3278 if (tmp_length
< width
)
3281 tmp_length
= xsum (tmp_length
, 1); /* account for trailing NUL */
3283 if (tmp_length
<= sizeof (tmpbuf
) / sizeof (DCHAR_T
))
3287 size_t tmp_memsize
= xtimes (tmp_length
, sizeof (DCHAR_T
));
3289 if (size_overflow_p (tmp_memsize
))
3290 /* Overflow, would lead to out of memory. */
3292 tmp
= (DCHAR_T
*) malloc (tmp_memsize
);
3294 /* Out of memory. */
3300 if (type
== TYPE_LONGDOUBLE
)
3302 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
3303 long double arg
= a
.arg
[dp
->arg_index
].a
.a_longdouble
;
3307 if (dp
->conversion
== 'A')
3309 *p
++ = 'N'; *p
++ = 'A'; *p
++ = 'N';
3313 *p
++ = 'n'; *p
++ = 'a'; *p
++ = 'n';
3319 DECL_LONG_DOUBLE_ROUNDING
3321 BEGIN_LONG_DOUBLE_ROUNDING ();
3323 if (signbit (arg
)) /* arg < 0.0L or negative zero */
3331 else if (flags
& FLAG_SHOWSIGN
)
3333 else if (flags
& FLAG_SPACE
)
3336 if (arg
> 0.0L && arg
+ arg
== arg
)
3338 if (dp
->conversion
== 'A')
3340 *p
++ = 'I'; *p
++ = 'N'; *p
++ = 'F';
3344 *p
++ = 'i'; *p
++ = 'n'; *p
++ = 'f';
3350 long double mantissa
;
3353 mantissa
= printf_frexpl (arg
, &exponent
);
3361 && precision
< (unsigned int) ((LDBL_DIG
+ 1) * 0.831) + 1)
3363 /* Round the mantissa. */
3364 long double tail
= mantissa
;
3367 for (q
= precision
; ; q
--)
3369 int digit
= (int) tail
;
3373 if (digit
& 1 ? tail
>= 0.5L : tail
> 0.5L)
3382 for (q
= precision
; q
> 0; q
--)
3388 *p
++ = dp
->conversion
- 'A' + 'X';
3393 digit
= (int) mantissa
;
3396 if ((flags
& FLAG_ALT
)
3397 || mantissa
> 0.0L || precision
> 0)
3399 *p
++ = decimal_point_char ();
3400 /* This loop terminates because we assume
3401 that FLT_RADIX is a power of 2. */
3402 while (mantissa
> 0.0L)
3405 digit
= (int) mantissa
;
3410 : dp
->conversion
- 10);
3414 while (precision
> 0)
3421 *p
++ = dp
->conversion
- 'A' + 'P';
3422 # if WIDE_CHAR_VERSION
3424 static const wchar_t decimal_format
[] =
3425 { '%', '+', 'd', '\0' };
3426 SNPRINTF (p
, 6 + 1, decimal_format
, exponent
);
3431 if (sizeof (DCHAR_T
) == 1)
3433 sprintf ((char *) p
, "%+d", exponent
);
3441 sprintf (expbuf
, "%+d", exponent
);
3442 for (ep
= expbuf
; (*p
= *ep
) != '\0'; ep
++)
3448 END_LONG_DOUBLE_ROUNDING ();
3456 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
3457 double arg
= a
.arg
[dp
->arg_index
].a
.a_double
;
3461 if (dp
->conversion
== 'A')
3463 *p
++ = 'N'; *p
++ = 'A'; *p
++ = 'N';
3467 *p
++ = 'n'; *p
++ = 'a'; *p
++ = 'n';
3474 if (signbit (arg
)) /* arg < 0.0 or negative zero */
3482 else if (flags
& FLAG_SHOWSIGN
)
3484 else if (flags
& FLAG_SPACE
)
3487 if (arg
> 0.0 && arg
+ arg
== arg
)
3489 if (dp
->conversion
== 'A')
3491 *p
++ = 'I'; *p
++ = 'N'; *p
++ = 'F';
3495 *p
++ = 'i'; *p
++ = 'n'; *p
++ = 'f';
3504 mantissa
= printf_frexp (arg
, &exponent
);
3512 && precision
< (unsigned int) ((DBL_DIG
+ 1) * 0.831) + 1)
3514 /* Round the mantissa. */
3515 double tail
= mantissa
;
3518 for (q
= precision
; ; q
--)
3520 int digit
= (int) tail
;
3524 if (digit
& 1 ? tail
>= 0.5 : tail
> 0.5)
3533 for (q
= precision
; q
> 0; q
--)
3539 *p
++ = dp
->conversion
- 'A' + 'X';
3544 digit
= (int) mantissa
;
3547 if ((flags
& FLAG_ALT
)
3548 || mantissa
> 0.0 || precision
> 0)
3550 *p
++ = decimal_point_char ();
3551 /* This loop terminates because we assume
3552 that FLT_RADIX is a power of 2. */
3553 while (mantissa
> 0.0)
3556 digit
= (int) mantissa
;
3561 : dp
->conversion
- 10);
3565 while (precision
> 0)
3572 *p
++ = dp
->conversion
- 'A' + 'P';
3573 # if WIDE_CHAR_VERSION
3575 static const wchar_t decimal_format
[] =
3576 { '%', '+', 'd', '\0' };
3577 SNPRINTF (p
, 6 + 1, decimal_format
, exponent
);
3582 if (sizeof (DCHAR_T
) == 1)
3584 sprintf ((char *) p
, "%+d", exponent
);
3592 sprintf (expbuf
, "%+d", exponent
);
3593 for (ep
= expbuf
; (*p
= *ep
) != '\0'; ep
++)
3604 /* The generated string now extends from tmp to p, with the
3605 zero padding insertion point being at pad_ptr. */
3610 size_t pad
= width
- count
;
3611 DCHAR_T
*end
= p
+ pad
;
3613 if (flags
& FLAG_LEFT
)
3615 /* Pad with spaces on the right. */
3616 for (; pad
> 0; pad
--)
3619 else if ((flags
& FLAG_ZERO
) && pad_ptr
!= NULL
)
3621 /* Pad with zeroes. */
3626 for (; pad
> 0; pad
--)
3631 /* Pad with spaces on the left. */
3636 for (; pad
> 0; pad
--)
3645 if (count
>= tmp_length
)
3646 /* tmp_length was incorrectly calculated - fix the
3650 /* Make room for the result. */
3651 if (count
>= allocated
- length
)
3653 size_t n
= xsum (length
, count
);
3655 ENSURE_ALLOCATION (n
);
3658 /* Append the result. */
3659 memcpy (result
+ length
, tmp
, count
* sizeof (DCHAR_T
));
3665 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3666 else if ((dp
->conversion
== 'f' || dp
->conversion
== 'F'
3667 || dp
->conversion
== 'e' || dp
->conversion
== 'E'
3668 || dp
->conversion
== 'g' || dp
->conversion
== 'G'
3669 || dp
->conversion
== 'a' || dp
->conversion
== 'A')
3671 # if NEED_PRINTF_DOUBLE
3672 || a
.arg
[dp
->arg_index
].type
== TYPE_DOUBLE
3673 # elif NEED_PRINTF_INFINITE_DOUBLE
3674 || (a
.arg
[dp
->arg_index
].type
== TYPE_DOUBLE
3675 /* The systems (mingw) which produce wrong output
3676 for Inf, -Inf, and NaN also do so for -0.0.
3677 Therefore we treat this case here as well. */
3678 && is_infinite_or_zero (a
.arg
[dp
->arg_index
].a
.a_double
))
3680 # if NEED_PRINTF_LONG_DOUBLE
3681 || a
.arg
[dp
->arg_index
].type
== TYPE_LONGDOUBLE
3682 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3683 || (a
.arg
[dp
->arg_index
].type
== TYPE_LONGDOUBLE
3684 /* Some systems produce wrong output for Inf,
3685 -Inf, and NaN. Some systems in this category
3686 (IRIX 5.3) also do so for -0.0. Therefore we
3687 treat this case here as well. */
3688 && is_infinite_or_zerol (a
.arg
[dp
->arg_index
].a
.a_longdouble
))
3692 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3693 arg_type type
= a
.arg
[dp
->arg_index
].type
;
3695 int flags
= dp
->flags
;
3701 DCHAR_T tmpbuf
[700];
3707 if (dp
->width_start
!= dp
->width_end
)
3709 if (dp
->width_arg_index
!= ARG_NONE
)
3713 if (!(a
.arg
[dp
->width_arg_index
].type
== TYPE_INT
))
3715 arg
= a
.arg
[dp
->width_arg_index
].a
.a_int
;
3719 /* "A negative field width is taken as a '-' flag
3720 followed by a positive field width." */
3727 const FCHAR_T
*digitp
= dp
->width_start
;
3730 width
= xsum (xtimes (width
, 10), *digitp
++ - '0');
3731 while (digitp
!= dp
->width_end
);
3737 if (dp
->precision_start
!= dp
->precision_end
)
3739 if (dp
->precision_arg_index
!= ARG_NONE
)
3743 if (!(a
.arg
[dp
->precision_arg_index
].type
== TYPE_INT
))
3745 arg
= a
.arg
[dp
->precision_arg_index
].a
.a_int
;
3746 /* "A negative precision is taken as if the precision
3756 const FCHAR_T
*digitp
= dp
->precision_start
+ 1;
3759 while (digitp
!= dp
->precision_end
)
3760 precision
= xsum (xtimes (precision
, 10), *digitp
++ - '0');
3765 /* POSIX specifies the default precision to be 6 for %f, %F,
3766 %e, %E, but not for %g, %G. Implementations appear to use
3767 the same default precision also for %g, %G. But for %a, %A,
3768 the default precision is 0. */
3770 if (!(dp
->conversion
== 'a' || dp
->conversion
== 'A'))
3773 /* Allocate a temporary buffer of sufficient size. */
3774 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3775 tmp_length
= (type
== TYPE_LONGDOUBLE
? LDBL_DIG
+ 1 : DBL_DIG
+ 1);
3776 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3777 tmp_length
= (type
== TYPE_LONGDOUBLE
? LDBL_DIG
+ 1 : 0);
3778 # elif NEED_PRINTF_LONG_DOUBLE
3779 tmp_length
= LDBL_DIG
+ 1;
3780 # elif NEED_PRINTF_DOUBLE
3781 tmp_length
= DBL_DIG
+ 1;
3785 if (tmp_length
< precision
)
3786 tmp_length
= precision
;
3787 # if NEED_PRINTF_LONG_DOUBLE
3788 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3789 if (type
== TYPE_LONGDOUBLE
)
3791 if (dp
->conversion
== 'f' || dp
->conversion
== 'F')
3793 long double arg
= a
.arg
[dp
->arg_index
].a
.a_longdouble
;
3794 if (!(isnanl (arg
) || arg
+ arg
== arg
))
3796 /* arg is finite and nonzero. */
3797 int exponent
= floorlog10l (arg
< 0 ? -arg
: arg
);
3798 if (exponent
>= 0 && tmp_length
< exponent
+ precision
)
3799 tmp_length
= exponent
+ precision
;
3803 # if NEED_PRINTF_DOUBLE
3804 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3805 if (type
== TYPE_DOUBLE
)
3807 if (dp
->conversion
== 'f' || dp
->conversion
== 'F')
3809 double arg
= a
.arg
[dp
->arg_index
].a
.a_double
;
3810 if (!(isnand (arg
) || arg
+ arg
== arg
))
3812 /* arg is finite and nonzero. */
3813 int exponent
= floorlog10 (arg
< 0 ? -arg
: arg
);
3814 if (exponent
>= 0 && tmp_length
< exponent
+ precision
)
3815 tmp_length
= exponent
+ precision
;
3819 /* Account for sign, decimal point etc. */
3820 tmp_length
= xsum (tmp_length
, 12);
3822 if (tmp_length
< width
)
3825 tmp_length
= xsum (tmp_length
, 1); /* account for trailing NUL */
3827 if (tmp_length
<= sizeof (tmpbuf
) / sizeof (DCHAR_T
))
3831 size_t tmp_memsize
= xtimes (tmp_length
, sizeof (DCHAR_T
));
3833 if (size_overflow_p (tmp_memsize
))
3834 /* Overflow, would lead to out of memory. */
3836 tmp
= (DCHAR_T
*) malloc (tmp_memsize
);
3838 /* Out of memory. */
3845 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3846 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3847 if (type
== TYPE_LONGDOUBLE
)
3850 long double arg
= a
.arg
[dp
->arg_index
].a
.a_longdouble
;
3854 if (dp
->conversion
>= 'A' && dp
->conversion
<= 'Z')
3856 *p
++ = 'N'; *p
++ = 'A'; *p
++ = 'N';
3860 *p
++ = 'n'; *p
++ = 'a'; *p
++ = 'n';
3866 DECL_LONG_DOUBLE_ROUNDING
3868 BEGIN_LONG_DOUBLE_ROUNDING ();
3870 if (signbit (arg
)) /* arg < 0.0L or negative zero */
3878 else if (flags
& FLAG_SHOWSIGN
)
3880 else if (flags
& FLAG_SPACE
)
3883 if (arg
> 0.0L && arg
+ arg
== arg
)
3885 if (dp
->conversion
>= 'A' && dp
->conversion
<= 'Z')
3887 *p
++ = 'I'; *p
++ = 'N'; *p
++ = 'F';
3891 *p
++ = 'i'; *p
++ = 'n'; *p
++ = 'f';
3896 # if NEED_PRINTF_LONG_DOUBLE
3899 if (dp
->conversion
== 'f' || dp
->conversion
== 'F')
3905 scale10_round_decimal_long_double (arg
, precision
);
3908 END_LONG_DOUBLE_ROUNDING ();
3911 ndigits
= strlen (digits
);
3913 if (ndigits
> precision
)
3917 *p
++ = digits
[ndigits
];
3919 while (ndigits
> precision
);
3922 /* Here ndigits <= precision. */
3923 if ((flags
& FLAG_ALT
) || precision
> 0)
3925 *p
++ = decimal_point_char ();
3926 for (; precision
> ndigits
; precision
--)
3931 *p
++ = digits
[ndigits
];
3937 else if (dp
->conversion
== 'e' || dp
->conversion
== 'E')
3945 if ((flags
& FLAG_ALT
) || precision
> 0)
3947 *p
++ = decimal_point_char ();
3948 for (; precision
> 0; precision
--)
3959 exponent
= floorlog10l (arg
);
3964 scale10_round_decimal_long_double (arg
,
3965 (int)precision
- exponent
);
3968 END_LONG_DOUBLE_ROUNDING ();
3971 ndigits
= strlen (digits
);
3973 if (ndigits
== precision
+ 1)
3975 if (ndigits
< precision
3976 || ndigits
> precision
+ 2)
3977 /* The exponent was not guessed
3978 precisely enough. */
3981 /* None of two values of exponent is
3982 the right one. Prevent an endless
3986 if (ndigits
== precision
)
3992 /* Here ndigits = precision+1. */
3993 if (is_borderline (digits
, precision
))
3995 /* Maybe the exponent guess was too high
3996 and a smaller exponent can be reached
3997 by turning a 10...0 into 9...9x. */
3999 scale10_round_decimal_long_double (arg
,
4000 (int)precision
- exponent
+ 1);
4001 if (digits2
== NULL
)
4004 END_LONG_DOUBLE_ROUNDING ();
4007 if (strlen (digits2
) == precision
+ 1)
4016 /* Here ndigits = precision+1. */
4018 *p
++ = digits
[--ndigits
];
4019 if ((flags
& FLAG_ALT
) || precision
> 0)
4021 *p
++ = decimal_point_char ();
4025 *p
++ = digits
[ndigits
];
4032 *p
++ = dp
->conversion
; /* 'e' or 'E' */
4033 # if WIDE_CHAR_VERSION
4035 static const wchar_t decimal_format
[] =
4036 { '%', '+', '.', '2', 'd', '\0' };
4037 SNPRINTF (p
, 6 + 1, decimal_format
, exponent
);
4042 if (sizeof (DCHAR_T
) == 1)
4044 sprintf ((char *) p
, "%+.2d", exponent
);
4052 sprintf (expbuf
, "%+.2d", exponent
);
4053 for (ep
= expbuf
; (*p
= *ep
) != '\0'; ep
++)
4058 else if (dp
->conversion
== 'g' || dp
->conversion
== 'G')
4062 /* precision >= 1. */
4065 /* The exponent is 0, >= -4, < precision.
4066 Use fixed-point notation. */
4068 size_t ndigits
= precision
;
4069 /* Number of trailing zeroes that have to be
4072 (flags
& FLAG_ALT
? 0 : precision
- 1);
4076 if ((flags
& FLAG_ALT
) || ndigits
> nzeroes
)
4078 *p
++ = decimal_point_char ();
4079 while (ndigits
> nzeroes
)
4095 exponent
= floorlog10l (arg
);
4100 scale10_round_decimal_long_double (arg
,
4101 (int)(precision
- 1) - exponent
);
4104 END_LONG_DOUBLE_ROUNDING ();
4107 ndigits
= strlen (digits
);
4109 if (ndigits
== precision
)
4111 if (ndigits
< precision
- 1
4112 || ndigits
> precision
+ 1)
4113 /* The exponent was not guessed
4114 precisely enough. */
4117 /* None of two values of exponent is
4118 the right one. Prevent an endless
4122 if (ndigits
< precision
)
4128 /* Here ndigits = precision. */
4129 if (is_borderline (digits
, precision
- 1))
4131 /* Maybe the exponent guess was too high
4132 and a smaller exponent can be reached
4133 by turning a 10...0 into 9...9x. */
4135 scale10_round_decimal_long_double (arg
,
4136 (int)(precision
- 1) - exponent
+ 1);
4137 if (digits2
== NULL
)
4140 END_LONG_DOUBLE_ROUNDING ();
4143 if (strlen (digits2
) == precision
)
4152 /* Here ndigits = precision. */
4154 /* Determine the number of trailing zeroes
4155 that have to be dropped. */
4157 if ((flags
& FLAG_ALT
) == 0)
4158 while (nzeroes
< ndigits
4159 && digits
[nzeroes
] == '0')
4162 /* The exponent is now determined. */
4164 && exponent
< (long)precision
)
4166 /* Fixed-point notation:
4167 max(exponent,0)+1 digits, then the
4168 decimal point, then the remaining
4169 digits without trailing zeroes. */
4172 size_t ecount
= exponent
+ 1;
4173 /* Note: count <= precision = ndigits. */
4174 for (; ecount
> 0; ecount
--)
4175 *p
++ = digits
[--ndigits
];
4176 if ((flags
& FLAG_ALT
) || ndigits
> nzeroes
)
4178 *p
++ = decimal_point_char ();
4179 while (ndigits
> nzeroes
)
4182 *p
++ = digits
[ndigits
];
4188 size_t ecount
= -exponent
- 1;
4190 *p
++ = decimal_point_char ();
4191 for (; ecount
> 0; ecount
--)
4193 while (ndigits
> nzeroes
)
4196 *p
++ = digits
[ndigits
];
4202 /* Exponential notation. */
4203 *p
++ = digits
[--ndigits
];
4204 if ((flags
& FLAG_ALT
) || ndigits
> nzeroes
)
4206 *p
++ = decimal_point_char ();
4207 while (ndigits
> nzeroes
)
4210 *p
++ = digits
[ndigits
];
4213 *p
++ = dp
->conversion
- 'G' + 'E'; /* 'e' or 'E' */
4214 # if WIDE_CHAR_VERSION
4216 static const wchar_t decimal_format
[] =
4217 { '%', '+', '.', '2', 'd', '\0' };
4218 SNPRINTF (p
, 6 + 1, decimal_format
, exponent
);
4223 if (sizeof (DCHAR_T
) == 1)
4225 sprintf ((char *) p
, "%+.2d", exponent
);
4233 sprintf (expbuf
, "%+.2d", exponent
);
4234 for (ep
= expbuf
; (*p
= *ep
) != '\0'; ep
++)
4246 /* arg is finite. */
4252 if (dp
->conversion
== 'f' || dp
->conversion
== 'F')
4255 if ((flags
& FLAG_ALT
) || precision
> 0)
4257 *p
++ = decimal_point_char ();
4258 for (; precision
> 0; precision
--)
4262 else if (dp
->conversion
== 'e' || dp
->conversion
== 'E')
4265 if ((flags
& FLAG_ALT
) || precision
> 0)
4267 *p
++ = decimal_point_char ();
4268 for (; precision
> 0; precision
--)
4271 *p
++ = dp
->conversion
; /* 'e' or 'E' */
4276 else if (dp
->conversion
== 'g' || dp
->conversion
== 'G')
4279 if (flags
& FLAG_ALT
)
4282 (precision
> 0 ? precision
- 1 : 0);
4283 *p
++ = decimal_point_char ();
4284 for (; ndigits
> 0; --ndigits
)
4288 else if (dp
->conversion
== 'a' || dp
->conversion
== 'A')
4291 *p
++ = dp
->conversion
- 'A' + 'X';
4294 if ((flags
& FLAG_ALT
) || precision
> 0)
4296 *p
++ = decimal_point_char ();
4297 for (; precision
> 0; precision
--)
4300 *p
++ = dp
->conversion
- 'A' + 'P';
4309 END_LONG_DOUBLE_ROUNDING ();
4312 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4316 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4318 double arg
= a
.arg
[dp
->arg_index
].a
.a_double
;
4322 if (dp
->conversion
>= 'A' && dp
->conversion
<= 'Z')
4324 *p
++ = 'N'; *p
++ = 'A'; *p
++ = 'N';
4328 *p
++ = 'n'; *p
++ = 'a'; *p
++ = 'n';
4335 if (signbit (arg
)) /* arg < 0.0 or negative zero */
4343 else if (flags
& FLAG_SHOWSIGN
)
4345 else if (flags
& FLAG_SPACE
)
4348 if (arg
> 0.0 && arg
+ arg
== arg
)
4350 if (dp
->conversion
>= 'A' && dp
->conversion
<= 'Z')
4352 *p
++ = 'I'; *p
++ = 'N'; *p
++ = 'F';
4356 *p
++ = 'i'; *p
++ = 'n'; *p
++ = 'f';
4361 # if NEED_PRINTF_DOUBLE
4364 if (dp
->conversion
== 'f' || dp
->conversion
== 'F')
4370 scale10_round_decimal_double (arg
, precision
);
4373 ndigits
= strlen (digits
);
4375 if (ndigits
> precision
)
4379 *p
++ = digits
[ndigits
];
4381 while (ndigits
> precision
);
4384 /* Here ndigits <= precision. */
4385 if ((flags
& FLAG_ALT
) || precision
> 0)
4387 *p
++ = decimal_point_char ();
4388 for (; precision
> ndigits
; precision
--)
4393 *p
++ = digits
[ndigits
];
4399 else if (dp
->conversion
== 'e' || dp
->conversion
== 'E')
4407 if ((flags
& FLAG_ALT
) || precision
> 0)
4409 *p
++ = decimal_point_char ();
4410 for (; precision
> 0; precision
--)
4421 exponent
= floorlog10 (arg
);
4426 scale10_round_decimal_double (arg
,
4427 (int)precision
- exponent
);
4430 ndigits
= strlen (digits
);
4432 if (ndigits
== precision
+ 1)
4434 if (ndigits
< precision
4435 || ndigits
> precision
+ 2)
4436 /* The exponent was not guessed
4437 precisely enough. */
4440 /* None of two values of exponent is
4441 the right one. Prevent an endless
4445 if (ndigits
== precision
)
4451 /* Here ndigits = precision+1. */
4452 if (is_borderline (digits
, precision
))
4454 /* Maybe the exponent guess was too high
4455 and a smaller exponent can be reached
4456 by turning a 10...0 into 9...9x. */
4458 scale10_round_decimal_double (arg
,
4459 (int)precision
- exponent
+ 1);
4460 if (digits2
== NULL
)
4465 if (strlen (digits2
) == precision
+ 1)
4474 /* Here ndigits = precision+1. */
4476 *p
++ = digits
[--ndigits
];
4477 if ((flags
& FLAG_ALT
) || precision
> 0)
4479 *p
++ = decimal_point_char ();
4483 *p
++ = digits
[ndigits
];
4490 *p
++ = dp
->conversion
; /* 'e' or 'E' */
4491 # if WIDE_CHAR_VERSION
4493 static const wchar_t decimal_format
[] =
4494 /* Produce the same number of exponent digits
4495 as the native printf implementation. */
4496 # if defined _WIN32 && ! defined __CYGWIN__
4497 { '%', '+', '.', '3', 'd', '\0' };
4499 { '%', '+', '.', '2', 'd', '\0' };
4501 SNPRINTF (p
, 6 + 1, decimal_format
, exponent
);
4507 static const char decimal_format
[] =
4508 /* Produce the same number of exponent digits
4509 as the native printf implementation. */
4510 # if defined _WIN32 && ! defined __CYGWIN__
4515 if (sizeof (DCHAR_T
) == 1)
4517 sprintf ((char *) p
, decimal_format
, exponent
);
4525 sprintf (expbuf
, decimal_format
, exponent
);
4526 for (ep
= expbuf
; (*p
= *ep
) != '\0'; ep
++)
4532 else if (dp
->conversion
== 'g' || dp
->conversion
== 'G')
4536 /* precision >= 1. */
4539 /* The exponent is 0, >= -4, < precision.
4540 Use fixed-point notation. */
4542 size_t ndigits
= precision
;
4543 /* Number of trailing zeroes that have to be
4546 (flags
& FLAG_ALT
? 0 : precision
- 1);
4550 if ((flags
& FLAG_ALT
) || ndigits
> nzeroes
)
4552 *p
++ = decimal_point_char ();
4553 while (ndigits
> nzeroes
)
4569 exponent
= floorlog10 (arg
);
4574 scale10_round_decimal_double (arg
,
4575 (int)(precision
- 1) - exponent
);
4578 ndigits
= strlen (digits
);
4580 if (ndigits
== precision
)
4582 if (ndigits
< precision
- 1
4583 || ndigits
> precision
+ 1)
4584 /* The exponent was not guessed
4585 precisely enough. */
4588 /* None of two values of exponent is
4589 the right one. Prevent an endless
4593 if (ndigits
< precision
)
4599 /* Here ndigits = precision. */
4600 if (is_borderline (digits
, precision
- 1))
4602 /* Maybe the exponent guess was too high
4603 and a smaller exponent can be reached
4604 by turning a 10...0 into 9...9x. */
4606 scale10_round_decimal_double (arg
,
4607 (int)(precision
- 1) - exponent
+ 1);
4608 if (digits2
== NULL
)
4613 if (strlen (digits2
) == precision
)
4622 /* Here ndigits = precision. */
4624 /* Determine the number of trailing zeroes
4625 that have to be dropped. */
4627 if ((flags
& FLAG_ALT
) == 0)
4628 while (nzeroes
< ndigits
4629 && digits
[nzeroes
] == '0')
4632 /* The exponent is now determined. */
4634 && exponent
< (long)precision
)
4636 /* Fixed-point notation:
4637 max(exponent,0)+1 digits, then the
4638 decimal point, then the remaining
4639 digits without trailing zeroes. */
4642 size_t ecount
= exponent
+ 1;
4643 /* Note: ecount <= precision = ndigits. */
4644 for (; ecount
> 0; ecount
--)
4645 *p
++ = digits
[--ndigits
];
4646 if ((flags
& FLAG_ALT
) || ndigits
> nzeroes
)
4648 *p
++ = decimal_point_char ();
4649 while (ndigits
> nzeroes
)
4652 *p
++ = digits
[ndigits
];
4658 size_t ecount
= -exponent
- 1;
4660 *p
++ = decimal_point_char ();
4661 for (; ecount
> 0; ecount
--)
4663 while (ndigits
> nzeroes
)
4666 *p
++ = digits
[ndigits
];
4672 /* Exponential notation. */
4673 *p
++ = digits
[--ndigits
];
4674 if ((flags
& FLAG_ALT
) || ndigits
> nzeroes
)
4676 *p
++ = decimal_point_char ();
4677 while (ndigits
> nzeroes
)
4680 *p
++ = digits
[ndigits
];
4683 *p
++ = dp
->conversion
- 'G' + 'E'; /* 'e' or 'E' */
4684 # if WIDE_CHAR_VERSION
4686 static const wchar_t decimal_format
[] =
4687 /* Produce the same number of exponent digits
4688 as the native printf implementation. */
4689 # if defined _WIN32 && ! defined __CYGWIN__
4690 { '%', '+', '.', '3', 'd', '\0' };
4692 { '%', '+', '.', '2', 'd', '\0' };
4694 SNPRINTF (p
, 6 + 1, decimal_format
, exponent
);
4700 static const char decimal_format
[] =
4701 /* Produce the same number of exponent digits
4702 as the native printf implementation. */
4703 # if defined _WIN32 && ! defined __CYGWIN__
4708 if (sizeof (DCHAR_T
) == 1)
4710 sprintf ((char *) p
, decimal_format
, exponent
);
4718 sprintf (expbuf
, decimal_format
, exponent
);
4719 for (ep
= expbuf
; (*p
= *ep
) != '\0'; ep
++)
4732 /* arg is finite. */
4738 if (dp
->conversion
== 'f' || dp
->conversion
== 'F')
4741 if ((flags
& FLAG_ALT
) || precision
> 0)
4743 *p
++ = decimal_point_char ();
4744 for (; precision
> 0; precision
--)
4748 else if (dp
->conversion
== 'e' || dp
->conversion
== 'E')
4751 if ((flags
& FLAG_ALT
) || precision
> 0)
4753 *p
++ = decimal_point_char ();
4754 for (; precision
> 0; precision
--)
4757 *p
++ = dp
->conversion
; /* 'e' or 'E' */
4759 /* Produce the same number of exponent digits as
4760 the native printf implementation. */
4761 # if defined _WIN32 && ! defined __CYGWIN__
4767 else if (dp
->conversion
== 'g' || dp
->conversion
== 'G')
4770 if (flags
& FLAG_ALT
)
4773 (precision
> 0 ? precision
- 1 : 0);
4774 *p
++ = decimal_point_char ();
4775 for (; ndigits
> 0; --ndigits
)
4787 /* The generated string now extends from tmp to p, with the
4788 zero padding insertion point being at pad_ptr. */
4793 size_t pad
= width
- count
;
4794 DCHAR_T
*end
= p
+ pad
;
4796 if (flags
& FLAG_LEFT
)
4798 /* Pad with spaces on the right. */
4799 for (; pad
> 0; pad
--)
4802 else if ((flags
& FLAG_ZERO
) && pad_ptr
!= NULL
)
4804 /* Pad with zeroes. */
4809 for (; pad
> 0; pad
--)
4814 /* Pad with spaces on the left. */
4819 for (; pad
> 0; pad
--)
4828 if (count
>= tmp_length
)
4829 /* tmp_length was incorrectly calculated - fix the
4833 /* Make room for the result. */
4834 if (count
>= allocated
- length
)
4836 size_t n
= xsum (length
, count
);
4838 ENSURE_ALLOCATION (n
);
4841 /* Append the result. */
4842 memcpy (result
+ length
, tmp
, count
* sizeof (DCHAR_T
));
4850 arg_type type
= a
.arg
[dp
->arg_index
].type
;
4851 int flags
= dp
->flags
;
4852 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4855 #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
4858 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4862 #if NEED_PRINTF_UNBOUNDED_PRECISION
4865 # define prec_ourselves 0
4867 #if NEED_PRINTF_FLAG_LEFTADJUST
4868 # define pad_ourselves 1
4869 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4872 # define pad_ourselves 0
4875 unsigned int prefix_count
;
4876 int prefixes
[2] IF_LINT (= { 0 });
4880 TCHAR_T tmpbuf
[700];
4884 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4887 #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
4889 if (dp
->width_start
!= dp
->width_end
)
4891 if (dp
->width_arg_index
!= ARG_NONE
)
4895 if (!(a
.arg
[dp
->width_arg_index
].type
== TYPE_INT
))
4897 arg
= a
.arg
[dp
->width_arg_index
].a
.a_int
;
4901 /* "A negative field width is taken as a '-' flag
4902 followed by a positive field width." */
4909 const FCHAR_T
*digitp
= dp
->width_start
;
4912 width
= xsum (xtimes (width
, 10), *digitp
++ - '0');
4913 while (digitp
!= dp
->width_end
);
4915 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4921 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4924 if (dp
->precision_start
!= dp
->precision_end
)
4926 if (dp
->precision_arg_index
!= ARG_NONE
)
4930 if (!(a
.arg
[dp
->precision_arg_index
].type
== TYPE_INT
))
4932 arg
= a
.arg
[dp
->precision_arg_index
].a
.a_int
;
4933 /* "A negative precision is taken as if the precision
4943 const FCHAR_T
*digitp
= dp
->precision_start
+ 1;
4946 while (digitp
!= dp
->precision_end
)
4947 precision
= xsum (xtimes (precision
, 10), *digitp
++ - '0');
4953 /* Decide whether to handle the precision ourselves. */
4954 #if NEED_PRINTF_UNBOUNDED_PRECISION
4955 switch (dp
->conversion
)
4957 case 'd': case 'i': case 'u':
4959 case 'x': case 'X': case 'p':
4960 prec_ourselves
= has_precision
&& (precision
> 0);
4968 /* Decide whether to perform the padding ourselves. */
4969 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4970 switch (dp
->conversion
)
4972 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4973 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4974 to perform the padding after this conversion. Functions
4975 with unistdio extensions perform the padding based on
4976 character count rather than element count. */
4979 # if NEED_PRINTF_FLAG_ZERO
4980 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4986 pad_ourselves
= prec_ourselves
;
4992 /* Allocate a temporary buffer of sufficient size for calling
4995 MAX_ROOM_NEEDED (&a
, dp
->arg_index
, dp
->conversion
, type
,
4996 flags
, width
, has_precision
, precision
,
4999 if (tmp_length
<= sizeof (tmpbuf
) / sizeof (TCHAR_T
))
5003 size_t tmp_memsize
= xtimes (tmp_length
, sizeof (TCHAR_T
));
5005 if (size_overflow_p (tmp_memsize
))
5006 /* Overflow, would lead to out of memory. */
5008 tmp
= (TCHAR_T
*) malloc (tmp_memsize
);
5010 /* Out of memory. */
5015 /* Construct the format string for calling snprintf or
5019 #if NEED_PRINTF_FLAG_GROUPING
5020 /* The underlying implementation doesn't support the ' flag.
5021 Produce no grouping characters in this case; this is
5022 acceptable because the grouping is locale dependent. */
5024 if (flags
& FLAG_GROUP
)
5027 if (flags
& FLAG_LEFT
)
5029 if (flags
& FLAG_SHOWSIGN
)
5031 if (flags
& FLAG_SPACE
)
5033 if (flags
& FLAG_ALT
)
5035 #if __GLIBC__ >= 2 && !defined __UCLIBC__
5036 if (flags
& FLAG_LOCALIZED
)
5041 if (flags
& FLAG_ZERO
)
5043 if (dp
->width_start
!= dp
->width_end
)
5045 size_t n
= dp
->width_end
- dp
->width_start
;
5046 /* The width specification is known to consist only
5047 of standard ASCII characters. */
5048 if (sizeof (FCHAR_T
) == sizeof (TCHAR_T
))
5050 memcpy (fbp
, dp
->width_start
, n
* sizeof (TCHAR_T
));
5055 const FCHAR_T
*mp
= dp
->width_start
;
5062 if (!prec_ourselves
)
5064 if (dp
->precision_start
!= dp
->precision_end
)
5066 size_t n
= dp
->precision_end
- dp
->precision_start
;
5067 /* The precision specification is known to consist only
5068 of standard ASCII characters. */
5069 if (sizeof (FCHAR_T
) == sizeof (TCHAR_T
))
5071 memcpy (fbp
, dp
->precision_start
, n
* sizeof (TCHAR_T
));
5076 const FCHAR_T
*mp
= dp
->precision_start
;
5086 case TYPE_LONGLONGINT
:
5087 case TYPE_ULONGLONGINT
:
5088 #if defined _WIN32 && ! defined __CYGWIN__
5100 case TYPE_WIDE_CHAR
:
5103 case TYPE_WIDE_STRING
:
5107 case TYPE_LONGDOUBLE
:
5113 #if NEED_PRINTF_DIRECTIVE_F
5114 if (dp
->conversion
== 'F')
5118 *fbp
= dp
->conversion
;
5120 # if ((HAVE_SNPRINTF_RETVAL_C99 && HAVE_SNPRINTF_TRUNCATION_C99) \
5121 || ((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) \
5122 && !defined __UCLIBC__) \
5123 || (defined __APPLE__ && defined __MACH__) \
5124 || defined __ANDROID__ \
5125 || (defined _WIN32 && ! defined __CYGWIN__))
5126 /* On systems where we know that snprintf's return value
5127 conforms to ISO C 99 (HAVE_SNPRINTF_RETVAL_C99) and that
5128 snprintf always produces NUL-terminated strings
5129 (HAVE_SNPRINTF_TRUNCATION_C99), it is possible to avoid
5130 using %n. And it is desirable to do so, because more and
5131 more platforms no longer support %n, for "security reasons".
5132 In particular, the following platforms:
5133 - On glibc2 systems from 2004-10-18 or newer, the use of
5134 %n in format strings in writable memory may crash the
5135 program (if compiled with _FORTIFY_SOURCE=2).
5136 - On Mac OS X 10.13 or newer, the use of %n in format
5137 strings in writable memory by default crashes the
5139 - On Android, starting on 2018-03-07, the use of %n in
5140 format strings produces a fatal error (see
5141 <https://android.googlesource.com/platform/bionic/+/41398d03b7e8e0dfb951660ae713e682e9fc0336>).
5142 On these platforms, HAVE_SNPRINTF_RETVAL_C99 and
5143 HAVE_SNPRINTF_TRUNCATION_C99 are 1. We have listed them
5144 explicitly in the condition above, in case of cross-
5145 compilation (just to be sure). */
5146 /* On native Windows systems (such as mingw), we can avoid using
5148 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
5149 snprintf does not write more than the specified number
5150 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
5151 '4', '5', '6' into buf, not '4', '5', '\0'.)
5152 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
5153 allows us to recognize the case of an insufficient
5154 buffer size: it returns -1 in this case.
5155 On native Windows systems (such as mingw) where the OS is
5156 Windows Vista, the use of %n in format strings by default
5157 crashes the program. See
5158 <https://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
5159 <https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/set-printf-count-output>
5160 So we should avoid %n in this situation. */
5162 # else /* AIX <= 5.1, HP-UX, IRIX, OSF/1, Solaris <= 9, BeOS */
5171 /* Construct the arguments for calling snprintf or sprintf. */
5173 if (!pad_ourselves
&& dp
->width_arg_index
!= ARG_NONE
)
5175 if (!(a
.arg
[dp
->width_arg_index
].type
== TYPE_INT
))
5177 prefixes
[prefix_count
++] = a
.arg
[dp
->width_arg_index
].a
.a_int
;
5179 if (!prec_ourselves
&& dp
->precision_arg_index
!= ARG_NONE
)
5181 if (!(a
.arg
[dp
->precision_arg_index
].type
== TYPE_INT
))
5183 prefixes
[prefix_count
++] = a
.arg
[dp
->precision_arg_index
].a
.a_int
;
5187 /* The SNPRINTF result is appended after result[0..length].
5188 The latter is an array of DCHAR_T; SNPRINTF appends an
5189 array of TCHAR_T to it. This is possible because
5190 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
5191 alignof (TCHAR_T) <= alignof (DCHAR_T). */
5192 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
5193 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
5194 where an snprintf() with maxlen==1 acts like sprintf(). */
5195 ENSURE_ALLOCATION (xsum (length
,
5196 (2 + TCHARS_PER_DCHAR
- 1)
5197 / TCHARS_PER_DCHAR
));
5198 /* Prepare checking whether snprintf returns the count
5200 *(TCHAR_T
*) (result
+ length
) = '\0';
5211 size_t maxlen
= allocated
- length
;
5212 /* SNPRINTF can fail if its second argument is
5214 if (maxlen
> INT_MAX
/ TCHARS_PER_DCHAR
)
5215 maxlen
= INT_MAX
/ TCHARS_PER_DCHAR
;
5216 maxlen
= maxlen
* TCHARS_PER_DCHAR
;
5217 # define SNPRINTF_BUF(arg) \
5218 switch (prefix_count) \
5221 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
5226 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
5228 prefixes[0], arg, &count); \
5231 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
5233 prefixes[0], prefixes[1], arg, \
5240 # define SNPRINTF_BUF(arg) \
5241 switch (prefix_count) \
5244 count = sprintf (tmp, buf, arg); \
5247 count = sprintf (tmp, buf, prefixes[0], arg); \
5250 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
5263 int arg
= a
.arg
[dp
->arg_index
].a
.a_schar
;
5269 unsigned int arg
= a
.arg
[dp
->arg_index
].a
.a_uchar
;
5275 int arg
= a
.arg
[dp
->arg_index
].a
.a_short
;
5281 unsigned int arg
= a
.arg
[dp
->arg_index
].a
.a_ushort
;
5287 int arg
= a
.arg
[dp
->arg_index
].a
.a_int
;
5293 unsigned int arg
= a
.arg
[dp
->arg_index
].a
.a_uint
;
5299 long int arg
= a
.arg
[dp
->arg_index
].a
.a_longint
;
5305 unsigned long int arg
= a
.arg
[dp
->arg_index
].a
.a_ulongint
;
5309 case TYPE_LONGLONGINT
:
5311 long long int arg
= a
.arg
[dp
->arg_index
].a
.a_longlongint
;
5315 case TYPE_ULONGLONGINT
:
5317 unsigned long long int arg
= a
.arg
[dp
->arg_index
].a
.a_ulonglongint
;
5323 double arg
= a
.arg
[dp
->arg_index
].a
.a_double
;
5327 case TYPE_LONGDOUBLE
:
5329 long double arg
= a
.arg
[dp
->arg_index
].a
.a_longdouble
;
5335 int arg
= a
.arg
[dp
->arg_index
].a
.a_char
;
5340 case TYPE_WIDE_CHAR
:
5342 wint_t arg
= a
.arg
[dp
->arg_index
].a
.a_wide_char
;
5349 const char *arg
= a
.arg
[dp
->arg_index
].a
.a_string
;
5354 case TYPE_WIDE_STRING
:
5356 const wchar_t *arg
= a
.arg
[dp
->arg_index
].a
.a_wide_string
;
5363 void *arg
= a
.arg
[dp
->arg_index
].a
.a_pointer
;
5372 /* Portability: Not all implementations of snprintf()
5373 are ISO C 99 compliant. Determine the number of
5374 bytes that snprintf() has produced or would have
5378 /* Verify that snprintf() has NUL-terminated its
5380 if ((unsigned int) count
< maxlen
5381 && ((TCHAR_T
*) (result
+ length
)) [count
] != '\0')
5383 /* Portability hack. */
5384 if (retcount
> count
)
5389 /* snprintf() doesn't understand the '%n'
5393 /* Don't use the '%n' directive; instead, look
5394 at the snprintf() return value. */
5400 /* Look at the snprintf() return value. */
5403 # if !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF
5404 /* HP-UX 10.20 snprintf() is doubly deficient:
5405 It doesn't understand the '%n' directive,
5406 *and* it returns -1 (rather than the length
5407 that would have been required) when the
5408 buffer is too small.
5409 But a failure at this point can also come
5410 from other reasons than a too small buffer,
5411 such as an invalid wide string argument to
5412 the %ls directive, or possibly an invalid
5413 floating-point argument. */
5415 MAX_ROOM_NEEDED (&a
, dp
->arg_index
,
5416 dp
->conversion
, type
, flags
,
5419 precision
, pad_ourselves
);
5421 if (maxlen
< tmp_length
)
5423 /* Make more room. But try to do through
5424 this reallocation only once. */
5425 size_t bigger_need
=
5428 TCHARS_PER_DCHAR
- 1)
5429 / TCHARS_PER_DCHAR
);
5430 /* And always grow proportionally.
5431 (There may be several arguments, each
5432 needing a little more room than the
5434 size_t bigger_need2
=
5435 xsum (xtimes (allocated
, 2), 12);
5436 if (bigger_need
< bigger_need2
)
5437 bigger_need
= bigger_need2
;
5438 ENSURE_ALLOCATION (bigger_need
);
5449 /* Attempt to handle failure. */
5452 /* SNPRINTF or sprintf failed. Save and use the errno
5453 that it has set, if any. */
5454 int saved_errno
= errno
;
5455 if (saved_errno
== 0)
5457 if (dp
->conversion
== 'c' || dp
->conversion
== 's')
5458 saved_errno
= EILSEQ
;
5460 saved_errno
= EINVAL
;
5463 if (!(result
== resultbuf
|| result
== NULL
))
5465 if (buf_malloced
!= NULL
)
5466 free (buf_malloced
);
5469 errno
= saved_errno
;
5474 /* Handle overflow of the allocated buffer.
5475 If such an overflow occurs, a C99 compliant snprintf()
5476 returns a count >= maxlen. However, a non-compliant
5477 snprintf() function returns only count = maxlen - 1. To
5478 cover both cases, test whether count >= maxlen - 1. */
5479 if ((unsigned int) count
+ 1 >= maxlen
)
5481 /* If maxlen already has attained its allowed maximum,
5482 allocating more memory will not increase maxlen.
5483 Instead of looping, bail out. */
5484 if (maxlen
== INT_MAX
/ TCHARS_PER_DCHAR
)
5488 /* Need at least (count + 1) * sizeof (TCHAR_T)
5489 bytes. (The +1 is for the trailing NUL.)
5490 But ask for (count + 2) * sizeof (TCHAR_T)
5491 bytes, so that in the next round, we likely get
5492 maxlen > (unsigned int) count + 1
5493 and so we don't get here again.
5494 And allocate proportionally, to avoid looping
5495 eternally if snprintf() reports a too small
5499 ((unsigned int) count
+ 2
5500 + TCHARS_PER_DCHAR
- 1)
5501 / TCHARS_PER_DCHAR
),
5502 xtimes (allocated
, 2));
5504 ENSURE_ALLOCATION (n
);
5510 #if NEED_PRINTF_UNBOUNDED_PRECISION
5513 /* Handle the precision. */
5516 (TCHAR_T
*) (result
+ length
);
5520 size_t prefix_count
;
5524 /* Put the additional zeroes after the sign. */
5526 && (*prec_ptr
== '-' || *prec_ptr
== '+'
5527 || *prec_ptr
== ' '))
5529 /* Put the additional zeroes after the 0x prefix if
5530 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5532 && prec_ptr
[0] == '0'
5533 && (prec_ptr
[1] == 'x' || prec_ptr
[1] == 'X'))
5536 move
= count
- prefix_count
;
5537 if (precision
> move
)
5539 /* Insert zeroes. */
5540 size_t insert
= precision
- move
;
5546 (count
+ insert
+ TCHARS_PER_DCHAR
- 1)
5547 / TCHARS_PER_DCHAR
);
5548 length
+= (count
+ TCHARS_PER_DCHAR
- 1) / TCHARS_PER_DCHAR
;
5549 ENSURE_ALLOCATION (n
);
5550 length
-= (count
+ TCHARS_PER_DCHAR
- 1) / TCHARS_PER_DCHAR
;
5551 prec_ptr
= (TCHAR_T
*) (result
+ length
);
5554 prec_end
= prec_ptr
+ count
;
5555 prec_ptr
+= prefix_count
;
5557 while (prec_end
> prec_ptr
)
5560 prec_end
[insert
] = prec_end
[0];
5566 while (prec_end
> prec_ptr
);
5574 if (count
>= tmp_length
)
5575 /* tmp_length was incorrectly calculated - fix the
5581 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5582 if (dp
->conversion
== 'c' || dp
->conversion
== 's')
5584 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5586 The result string is not certainly ASCII. */
5587 const TCHAR_T
*tmpsrc
;
5590 /* This code assumes that TCHAR_T is 'char'. */
5591 verify (sizeof (TCHAR_T
) == 1);
5593 tmpsrc
= (TCHAR_T
*) (result
+ length
);
5598 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5599 iconveh_question_mark
,
5605 int saved_errno
= errno
;
5606 if (!(result
== resultbuf
|| result
== NULL
))
5608 if (buf_malloced
!= NULL
)
5609 free (buf_malloced
);
5611 errno
= saved_errno
;
5614 ENSURE_ALLOCATION (xsum (length
, tmpdst_len
));
5615 DCHAR_CPY (result
+ length
, tmpdst
, tmpdst_len
);
5621 /* The result string is ASCII.
5622 Simple 1:1 conversion. */
5624 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5625 no-op conversion, in-place on the array starting
5626 at (result + length). */
5627 if (sizeof (DCHAR_T
) != sizeof (TCHAR_T
))
5630 const TCHAR_T
*tmpsrc
;
5635 if (result
== resultbuf
)
5637 tmpsrc
= (TCHAR_T
*) (result
+ length
);
5638 /* ENSURE_ALLOCATION will not move tmpsrc
5639 (because it's part of resultbuf). */
5640 ENSURE_ALLOCATION (xsum (length
, count
));
5644 /* ENSURE_ALLOCATION will move the array
5645 (because it uses realloc(). */
5646 ENSURE_ALLOCATION (xsum (length
, count
));
5647 tmpsrc
= (TCHAR_T
*) (result
+ length
);
5651 ENSURE_ALLOCATION (xsum (length
, count
));
5653 tmpdst
= result
+ length
;
5654 /* Copy backwards, because of overlapping. */
5657 for (n
= count
; n
> 0; n
--)
5658 *--tmpdst
= *--tmpsrc
;
5663 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5664 /* Make room for the result. */
5665 if (count
> allocated
- length
)
5667 /* Need at least count elements. But allocate
5670 xmax (xsum (length
, count
), xtimes (allocated
, 2));
5672 ENSURE_ALLOCATION (n
);
5676 /* Here count <= allocated - length. */
5678 /* Perform padding. */
5679 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5680 if (pad_ourselves
&& has_width
)
5683 # if ENABLE_UNISTDIO
5684 /* Outside POSIX, it's preferable to compare the width
5685 against the number of _characters_ of the converted
5687 w
= DCHAR_MBSNLEN (result
+ length
, count
);
5689 /* The width is compared against the number of _bytes_
5690 of the converted value, says POSIX. */
5695 size_t pad
= width
- w
;
5697 /* Make room for the result. */
5698 if (xsum (count
, pad
) > allocated
- length
)
5700 /* Need at least count + pad elements. But
5701 allocate proportionally. */
5703 xmax (xsum3 (length
, count
, pad
),
5704 xtimes (allocated
, 2));
5708 ENSURE_ALLOCATION (n
);
5711 ENSURE_ALLOCATION (n
);
5714 /* Here count + pad <= allocated - length. */
5717 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5718 DCHAR_T
* const rp
= result
+ length
;
5720 DCHAR_T
* const rp
= tmp
;
5722 DCHAR_T
*p
= rp
+ count
;
5723 DCHAR_T
*end
= p
+ pad
;
5725 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5726 if (dp
->conversion
== 'c'
5727 || dp
->conversion
== 's')
5728 /* No zero-padding for string directives. */
5733 pad_ptr
= (*rp
== '-' ? rp
+ 1 : rp
);
5734 /* No zero-padding of "inf" and "nan". */
5735 if ((*pad_ptr
>= 'A' && *pad_ptr
<= 'Z')
5736 || (*pad_ptr
>= 'a' && *pad_ptr
<= 'z'))
5739 /* The generated string now extends from rp to p,
5740 with the zero padding insertion point being at
5743 count
= count
+ pad
; /* = end - rp */
5745 if (flags
& FLAG_LEFT
)
5747 /* Pad with spaces on the right. */
5748 for (; pad
> 0; pad
--)
5751 else if ((flags
& FLAG_ZERO
) && pad_ptr
!= NULL
)
5753 /* Pad with zeroes. */
5758 for (; pad
> 0; pad
--)
5763 /* Pad with spaces on the left. */
5768 for (; pad
> 0; pad
--)
5776 /* Here still count <= allocated - length. */
5778 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5779 /* The snprintf() result did fit. */
5781 /* Append the sprintf() result. */
5782 memcpy (result
+ length
, tmp
, count
* sizeof (DCHAR_T
));
5789 #if NEED_PRINTF_DIRECTIVE_F
5790 if (dp
->conversion
== 'F')
5792 /* Convert the %f result to upper case for %F. */
5793 DCHAR_T
*rp
= result
+ length
;
5795 for (rc
= count
; rc
> 0; rc
--, rp
++)
5796 if (*rp
>= 'a' && *rp
<= 'z')
5797 *rp
= *rp
- 'a' + 'A';
5805 #undef pad_ourselves
5806 #undef prec_ourselves
5811 /* Add the final NUL. */
5812 ENSURE_ALLOCATION (xsum (length
, 1));
5813 result
[length
] = '\0';
5815 if (result
!= resultbuf
&& length
+ 1 < allocated
)
5817 /* Shrink the allocated memory if possible. */
5820 memory
= (DCHAR_T
*) realloc (result
, (length
+ 1) * sizeof (DCHAR_T
));
5825 if (buf_malloced
!= NULL
)
5826 free (buf_malloced
);
5829 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5830 says that snprintf() fails with errno = EOVERFLOW in this case, but
5831 that's only because snprintf() returns an 'int'. This function does
5832 not have this limitation. */
5837 if (!(result
== resultbuf
|| result
== NULL
))
5839 if (buf_malloced
!= NULL
)
5840 free (buf_malloced
);
5847 if (!(result
== resultbuf
|| result
== NULL
))
5849 if (buf_malloced
!= NULL
)
5850 free (buf_malloced
);
5858 #undef MAX_ROOM_NEEDED
5859 #undef TCHARS_PER_DCHAR
5867 #undef DCHAR_IS_TCHAR