1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2008 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* This file can be parametrized with the following macros:
19 VASNPRINTF The name of the function being defined.
20 FCHAR_T The element type of the format string.
21 DCHAR_T The element type of the destination (result) string.
22 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
23 in the format string are ASCII. MUST be set if
24 FCHAR_T and DCHAR_T are not the same type.
25 DIRECTIVE Structure denoting a format directive.
27 DIRECTIVES Structure denoting the set of format directives of a
28 format string. Depends on FCHAR_T.
29 PRINTF_PARSE Function that parses a format string.
31 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
32 DCHAR_SET memset like function for DCHAR_T[] arrays.
33 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
34 SNPRINTF The system's snprintf (or similar) function.
35 This may be either snprintf or swprintf.
36 TCHAR_T The element type of the argument and result string
37 of the said SNPRINTF function. This may be either
38 char or wchar_t. The code exploits that
39 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
40 alignof (TCHAR_T) <= alignof (DCHAR_T).
41 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
42 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
43 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
44 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
45 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
47 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
48 This must come before <config.h> because <config.h> may include
49 <features.h>, and once <features.h> has been included, it's too late. */
51 # define _GNU_SOURCE 1
63 # if WIDE_CHAR_VERSION
64 # include "vasnwprintf.h"
66 # include "vasnprintf.h"
70 #include <locale.h> /* localeconv() */
71 #include <stdio.h> /* snprintf(), sprintf() */
72 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
73 #include <string.h> /* memcpy(), strlen() */
74 #include <errno.h> /* errno */
75 #include <limits.h> /* CHAR_BIT */
76 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
78 # include <langinfo.h>
81 # if WIDE_CHAR_VERSION
82 # include "wprintf-parse.h"
84 # include "printf-parse.h"
88 /* Checked size_t computations. */
91 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
96 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
101 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
103 # include "isnanl-nolibm.h"
107 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
110 # include "printf-frexp.h"
113 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
115 # include "isnanl-nolibm.h"
116 # include "printf-frexpl.h"
122 # define local_wcslen wcslen
124 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
125 a dependency towards this library, here is a local substitute.
126 Define this substitute only once, even if this file is included
127 twice in the same compilation unit. */
128 # ifndef local_wcslen_defined
129 # define local_wcslen_defined 1
131 local_wcslen (const wchar_t *s)
135 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
143 /* Default parameters. */
145 # if WIDE_CHAR_VERSION
146 # define VASNPRINTF vasnwprintf
147 # define FCHAR_T wchar_t
148 # define DCHAR_T wchar_t
149 # define TCHAR_T wchar_t
150 # define DCHAR_IS_TCHAR 1
151 # define DIRECTIVE wchar_t_directive
152 # define DIRECTIVES wchar_t_directives
153 # define PRINTF_PARSE wprintf_parse
154 # define DCHAR_CPY wmemcpy
156 # define VASNPRINTF vasnprintf
157 # define FCHAR_T char
158 # define DCHAR_T char
159 # define TCHAR_T char
160 # define DCHAR_IS_TCHAR 1
161 # define DIRECTIVE char_directive
162 # define DIRECTIVES char_directives
163 # define PRINTF_PARSE printf_parse
164 # define DCHAR_CPY memcpy
167 #if WIDE_CHAR_VERSION
168 /* TCHAR_T is wchar_t. */
169 # define USE_SNPRINTF 1
170 # if HAVE_DECL__SNWPRINTF
171 /* On Windows, the function swprintf() has a different signature than
172 on Unix; we use the _snwprintf() function instead. */
173 # define SNPRINTF _snwprintf
176 # define SNPRINTF swprintf
179 /* TCHAR_T is char. */
180 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
181 But don't use it on BeOS, since BeOS snprintf produces no output if the
182 size argument is >= 0x3000000.
183 Also don't use it on Linux libc5, since there snprintf with size = 1
184 writes any output without bounds, like sprintf. */
185 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
186 # define USE_SNPRINTF 1
188 # define USE_SNPRINTF 0
190 # if HAVE_DECL__SNPRINTF
192 # define SNPRINTF _snprintf
195 # define SNPRINTF snprintf
196 /* Here we need to call the native snprintf, not rpl_snprintf. */
200 /* Here we need to call the native sprintf, not rpl_sprintf. */
203 /* Avoid some warnings from "gcc -Wshadow".
204 This file doesn't use the exp() and remainder() functions. */
208 #define remainder rem
210 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
211 /* Determine the decimal-point character according to the current locale. */
212 # ifndef decimal_point_char_defined
213 # define decimal_point_char_defined 1
215 decimal_point_char ()
218 /* Determine it in a multithread-safe way. We know nl_langinfo is
219 multithread-safe on glibc systems, but is not required to be multithread-
220 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
221 is rarely multithread-safe. */
222 # if HAVE_NL_LANGINFO && __GLIBC__
223 point = nl_langinfo (RADIXCHAR);
226 sprintf (pointbuf, "%#.0f", 1.0);
227 point = &pointbuf[1];
229 point = localeconv () -> decimal_point;
231 /* The decimal point is always a single byte: either '.' or ','. */
232 return (point[0] != '\0' ? point[0] : '.');
237 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
239 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
241 is_infinite_or_zero (double x)
243 return isnand (x) || x + x == x;
248 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
250 /* Equivalent to !isfinite(x), but does not require libm. */
252 is_infinitel (long double x)
254 return isnanl (x) || (x + x == x && x != 0.0L);
259 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
261 /* Converting 'long double' to decimal without rare rounding bugs requires
262 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
263 (and slower) algorithms. */
265 typedef unsigned int mp_limb_t;
266 # define GMP_LIMB_BITS 32
267 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
269 typedef unsigned long long mp_twolimb_t;
270 # define GMP_TWOLIMB_BITS 64
271 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
273 /* Representation of a bignum >= 0. */
277 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
280 /* Compute the product of two bignums >= 0.
281 Return the allocated memory in case of success, NULL in case of memory
282 allocation failure. */
284 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
291 if (src1.nlimbs <= src2.nlimbs)
305 /* Now 0 <= len1 <= len2. */
308 /* src1 or src2 is zero. */
310 dest->limbs = (mp_limb_t *) malloc (1);
314 /* Here 1 <= len1 <= len2. */
320 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
323 for (k = len2; k > 0; )
325 for (i = 0; i < len1; i++)
327 mp_limb_t digit1 = p1[i];
328 mp_twolimb_t carry = 0;
329 for (j = 0; j < len2; j++)
331 mp_limb_t digit2 = p2[j];
332 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
334 dp[i + j] = (mp_limb_t) carry;
335 carry = carry >> GMP_LIMB_BITS;
337 dp[i + len2] = (mp_limb_t) carry;
340 while (dlen > 0 && dp[dlen - 1] == 0)
348 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
349 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
351 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
353 Return the allocated memory in case of success, NULL in case of memory
354 allocation failure. */
356 divide (mpn_t a, mpn_t b, mpn_t *q)
359 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
360 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
361 If m<n, then q:=0 and r:=a.
362 If m>=n=1, perform a single-precision division:
365 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
366 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
367 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
368 Normalise [q[m-1],...,q[0]], yields q.
369 If m>=n>1, perform a multiple-precision division:
370 We have a/b < beta^(m-n+1).
371 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
372 Shift a and b left by s bits, copying them. r:=a.
373 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
374 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
376 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
377 In case of overflow (q* >= beta) set q* := beta-1.
378 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
379 and c3 := b[n-2] * q*.
380 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
381 occurred. Furthermore 0 <= c3 < beta^2.
382 If there was overflow and
383 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
384 the next test can be skipped.}
385 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
386 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
388 Put r := r - b * q* * beta^j. In detail:
389 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
390 hence: u:=0, for i:=0 to n-1 do
392 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
393 u:=u div beta (+ 1, if carry in subtraction)
395 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
397 the carry u does not overflow.}
398 If a negative carry occurs, put q* := q* - 1
399 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
401 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
402 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
404 The room for q[j] can be allocated at the memory location of r[n+j].
405 Finally, round-to-even:
406 Shift r left by 1 bit.
407 If r > b or if r = b and q[0] is odd, q := q+1.
409 const mp_limb_t *a_ptr = a.limbs;
410 size_t a_len = a.nlimbs;
411 const mp_limb_t *b_ptr = b.limbs;
412 size_t b_len = b.nlimbs;
414 mp_limb_t *tmp_roomptr = NULL;
420 /* Allocate room for a_len+2 digits.
421 (Need a_len+1 digits for the real division and 1 more digit for the
422 final rounding of q.) */
423 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
428 while (a_len > 0 && a_ptr[a_len - 1] == 0)
435 /* Division by zero. */
437 if (b_ptr[b_len - 1] == 0)
443 /* Here m = a_len >= 0 and n = b_len > 0. */
447 /* m<n: trivial case. q=0, r := copy of a. */
450 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
451 q_ptr = roomptr + a_len;
456 /* n=1: single precision division.
457 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
461 mp_limb_t den = b_ptr[0];
462 mp_limb_t remainder = 0;
463 const mp_limb_t *sourceptr = a_ptr + a_len;
464 mp_limb_t *destptr = q_ptr + a_len;
466 for (count = a_len; count > 0; count--)
469 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
470 *--destptr = num / den;
471 remainder = num % den;
473 /* Normalise and store r. */
476 r_ptr[0] = remainder;
483 if (q_ptr[q_len - 1] == 0)
489 /* n>1: multiple precision division.
490 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
491 beta^(m-n-1) <= a/b < beta^(m-n+1). */
495 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
523 /* 0 <= s < GMP_LIMB_BITS.
524 Copy b, shifting it left by s bits. */
527 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
528 if (tmp_roomptr == NULL)
534 const mp_limb_t *sourceptr = b_ptr;
535 mp_limb_t *destptr = tmp_roomptr;
536 mp_twolimb_t accu = 0;
538 for (count = b_len; count > 0; count--)
540 accu += (mp_twolimb_t) *sourceptr++ << s;
541 *destptr++ = (mp_limb_t) accu;
542 accu = accu >> GMP_LIMB_BITS;
544 /* accu must be zero, since that was how s was determined. */
550 /* Copy a, shifting it left by s bits, yields r.
552 At the beginning: r = roomptr[0..a_len],
553 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
557 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
562 const mp_limb_t *sourceptr = a_ptr;
563 mp_limb_t *destptr = r_ptr;
564 mp_twolimb_t accu = 0;
566 for (count = a_len; count > 0; count--)
568 accu += (mp_twolimb_t) *sourceptr++ << s;
569 *destptr++ = (mp_limb_t) accu;
570 accu = accu >> GMP_LIMB_BITS;
572 *destptr++ = (mp_limb_t) accu;
574 q_ptr = roomptr + b_len;
575 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
577 size_t j = a_len - b_len; /* m-n */
578 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
579 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
580 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
581 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
582 /* Division loop, traversed m-n+1 times.
583 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
588 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
590 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
592 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
593 | r_ptr[j + b_len - 1];
594 q_star = num / b_msd;
599 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
600 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
601 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
602 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
603 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
605 If yes, jump directly to the subtraction loop.
606 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
607 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
608 if (r_ptr[j + b_len] > b_msd
609 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
610 /* r[j+n] >= b[n-1]+1 or
611 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
616 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
618 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
619 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
620 mp_twolimb_t c3 = /* b[n-2] * q* */
621 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
622 /* While c2 < c3, increase c2 and decrease c3.
623 Consider c3-c2. While it is > 0, decrease it by
624 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
625 this can happen only twice. */
628 q_star = q_star - 1; /* q* := q* - 1 */
629 if (c3 - c2 > b_msdd)
630 q_star = q_star - 1; /* q* := q* - 1 */
636 /* Subtract r := r - b * q* * beta^j. */
639 const mp_limb_t *sourceptr = b_ptr;
640 mp_limb_t *destptr = r_ptr + j;
641 mp_twolimb_t carry = 0;
643 for (count = b_len; count > 0; count--)
645 /* Here 0 <= carry <= q*. */
648 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
649 + (mp_limb_t) ~(*destptr);
650 /* Here 0 <= carry <= beta*q* + beta-1. */
651 *destptr++ = ~(mp_limb_t) carry;
652 carry = carry >> GMP_LIMB_BITS; /* <= q* */
654 cr = (mp_limb_t) carry;
656 /* Subtract cr from r_ptr[j + b_len], then forget about
658 if (cr > r_ptr[j + b_len])
660 /* Subtraction gave a carry. */
661 q_star = q_star - 1; /* q* := q* - 1 */
664 const mp_limb_t *sourceptr = b_ptr;
665 mp_limb_t *destptr = r_ptr + j;
668 for (count = b_len; count > 0; count--)
670 mp_limb_t source1 = *sourceptr++;
671 mp_limb_t source2 = *destptr;
672 *destptr++ = source1 + source2 + carry;
675 ? source1 >= (mp_limb_t) ~source2
676 : source1 > (mp_limb_t) ~source2);
679 /* Forget about the carry and about r[j+n]. */
682 /* q* is determined. Store it as q[j]. */
691 if (q_ptr[q_len - 1] == 0)
693 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
694 b is shifted left by s bits. */
695 /* Shift r right by s bits. */
698 mp_limb_t ptr = r_ptr + r_len;
699 mp_twolimb_t accu = 0;
701 for (count = r_len; count > 0; count--)
703 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
704 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
705 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
710 while (r_len > 0 && r_ptr[r_len - 1] == 0)
713 /* Compare r << 1 with b. */
721 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
722 | (i < r_len ? r_ptr[i] << 1 : 0);
723 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
733 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
738 for (i = 0; i < q_len; i++)
739 if (++(q_ptr[i]) != 0)
744 if (tmp_roomptr != NULL)
751 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
753 Destroys the contents of a.
754 Return the allocated memory - containing the decimal digits in low-to-high
755 order, terminated with a NUL character - in case of success, NULL in case
756 of memory allocation failure. */
758 convert_to_decimal (mpn_t a, size_t extra_zeroes)
760 mp_limb_t *a_ptr = a.limbs;
761 size_t a_len = a.nlimbs;
762 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
763 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
764 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
768 for (; extra_zeroes > 0; extra_zeroes--)
772 /* Divide a by 10^9, in-place. */
773 mp_limb_t remainder = 0;
774 mp_limb_t *ptr = a_ptr + a_len;
776 for (count = a_len; count > 0; count--)
779 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
780 *ptr = num / 1000000000;
781 remainder = num % 1000000000;
783 /* Store the remainder as 9 decimal digits. */
784 for (count = 9; count > 0; count--)
786 *d_ptr++ = '0' + (remainder % 10);
787 remainder = remainder / 10;
790 if (a_ptr[a_len - 1] == 0)
793 /* Remove leading zeroes. */
794 while (d_ptr > c_ptr && d_ptr[-1] == '0')
796 /* But keep at least one zero. */
799 /* Terminate the string. */
805 # if NEED_PRINTF_LONG_DOUBLE
807 /* Assuming x is finite and >= 0:
808 write x as x = 2^e * m, where m is a bignum.
809 Return the allocated memory in case of success, NULL in case of memory
810 allocation failure. */
812 decode_long_double (long double x, int *ep, mpn_t *mp)
819 /* Allocate memory for result. */
820 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
821 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
824 /* Split into exponential part and mantissa. */
825 y = frexpl (x, &exp);
826 if (!(y >= 0.0L && y < 1.0L))
828 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
829 latter is an integer. */
830 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
831 I'm not sure whether it's safe to cast a 'long double' value between
832 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
833 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
835 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
836 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
839 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
842 if (!(y >= 0.0L && y < 1.0L))
844 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
847 if (!(y >= 0.0L && y < 1.0L))
849 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
854 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
857 if (!(y >= 0.0L && y < 1.0L))
859 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
863 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
866 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
869 if (!(y >= 0.0L && y < 1.0L))
871 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
874 if (!(y >= 0.0L && y < 1.0L))
876 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
878 #if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
884 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
887 *ep = exp - LDBL_MANT_BIT;
893 # if NEED_PRINTF_DOUBLE
895 /* Assuming x is finite and >= 0:
896 write x as x = 2^e * m, where m is a bignum.
897 Return the allocated memory in case of success, NULL in case of memory
898 allocation failure. */
900 decode_double (double x, int *ep, mpn_t *mp)
907 /* Allocate memory for result. */
908 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
909 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
912 /* Split into exponential part and mantissa. */
914 if (!(y >= 0.0 && y < 1.0))
916 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
917 latter is an integer. */
918 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
919 I'm not sure whether it's safe to cast a 'double' value between
920 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
921 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
923 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
924 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
927 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
930 if (!(y >= 0.0 && y < 1.0))
932 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
935 if (!(y >= 0.0 && y < 1.0))
937 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
942 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
945 if (!(y >= 0.0 && y < 1.0))
947 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
951 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
954 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
957 if (!(y >= 0.0 && y < 1.0))
959 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
962 if (!(y >= 0.0 && y < 1.0))
964 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
969 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
972 *ep = exp - DBL_MANT_BIT;
978 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
979 Returns the decimal representation of round (x * 10^n).
980 Return the allocated memory - containing the decimal digits in low-to-high
981 order, terminated with a NUL character - in case of success, NULL in case
982 of memory allocation failure. */
984 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
992 unsigned int s_limbs;
1001 /* x = 2^e * m, hence
1002 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1003 = round (2^s * 5^n * m). */
1006 /* Factor out a common power of 10 if possible. */
1009 extra_zeroes = (s < n ? s : n);
1013 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1014 Before converting to decimal, we need to compute
1015 z = round (2^s * 5^n * m). */
1016 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1017 sign. 2.322 is slightly larger than log(5)/log(2). */
1018 abs_n = (n >= 0 ? n : -n);
1019 abs_s = (s >= 0 ? s : -s);
1020 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1021 + abs_s / GMP_LIMB_BITS + 1)
1022 * sizeof (mp_limb_t));
1023 if (pow5_ptr == NULL)
1028 /* Initialize with 1. */
1031 /* Multiply with 5^|n|. */
1034 static mp_limb_t const small_pow5[13 + 1] =
1036 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1037 48828125, 244140625, 1220703125
1040 for (n13 = 0; n13 <= abs_n; n13 += 13)
1042 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1044 mp_twolimb_t carry = 0;
1045 for (j = 0; j < pow5_len; j++)
1047 mp_limb_t digit2 = pow5_ptr[j];
1048 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1049 pow5_ptr[j] = (mp_limb_t) carry;
1050 carry = carry >> GMP_LIMB_BITS;
1053 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1056 s_limbs = abs_s / GMP_LIMB_BITS;
1057 s_bits = abs_s % GMP_LIMB_BITS;
1058 if (n >= 0 ? s >= 0 : s <= 0)
1060 /* Multiply with 2^|s|. */
1063 mp_limb_t *ptr = pow5_ptr;
1064 mp_twolimb_t accu = 0;
1066 for (count = pow5_len; count > 0; count--)
1068 accu += (mp_twolimb_t) *ptr << s_bits;
1069 *ptr++ = (mp_limb_t) accu;
1070 accu = accu >> GMP_LIMB_BITS;
1074 *ptr = (mp_limb_t) accu;
1081 for (count = pow5_len; count > 0;)
1084 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1086 for (count = s_limbs; count > 0;)
1089 pow5_ptr[count] = 0;
1091 pow5_len += s_limbs;
1093 pow5.limbs = pow5_ptr;
1094 pow5.nlimbs = pow5_len;
1097 /* Multiply m with pow5. No division needed. */
1098 z_memory = multiply (m, pow5, &z);
1102 /* Divide m by pow5 and round. */
1103 z_memory = divide (m, pow5, &z);
1108 pow5.limbs = pow5_ptr;
1109 pow5.nlimbs = pow5_len;
1113 Multiply m with pow5, then divide by 2^|s|. */
1117 tmp_memory = multiply (m, pow5, &numerator);
1118 if (tmp_memory == NULL)
1124 /* Construct 2^|s|. */
1126 mp_limb_t *ptr = pow5_ptr + pow5_len;
1128 for (i = 0; i < s_limbs; i++)
1130 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1131 denominator.limbs = ptr;
1132 denominator.nlimbs = s_limbs + 1;
1134 z_memory = divide (numerator, denominator, &z);
1140 Multiply m with 2^s, then divide by pow5. */
1143 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1144 * sizeof (mp_limb_t));
1145 if (num_ptr == NULL)
1152 mp_limb_t *destptr = num_ptr;
1155 for (i = 0; i < s_limbs; i++)
1160 const mp_limb_t *sourceptr = m.limbs;
1161 mp_twolimb_t accu = 0;
1163 for (count = m.nlimbs; count > 0; count--)
1165 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1166 *destptr++ = (mp_limb_t) accu;
1167 accu = accu >> GMP_LIMB_BITS;
1170 *destptr++ = (mp_limb_t) accu;
1174 const mp_limb_t *sourceptr = m.limbs;
1176 for (count = m.nlimbs; count > 0; count--)
1177 *destptr++ = *sourceptr++;
1179 numerator.limbs = num_ptr;
1180 numerator.nlimbs = destptr - num_ptr;
1182 z_memory = divide (numerator, pow5, &z);
1189 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1191 if (z_memory == NULL)
1193 digits = convert_to_decimal (z, extra_zeroes);
1198 # if NEED_PRINTF_LONG_DOUBLE
1200 /* Assuming x is finite and >= 0, and n is an integer:
1201 Returns the decimal representation of round (x * 10^n).
1202 Return the allocated memory - containing the decimal digits in low-to-high
1203 order, terminated with a NUL character - in case of success, NULL in case
1204 of memory allocation failure. */
1206 scale10_round_decimal_long_double (long double x, int n)
1210 void *memory = decode_long_double (x, &e, &m);
1211 return scale10_round_decimal_decoded (e, m, memory, n);
1216 # if NEED_PRINTF_DOUBLE
1218 /* Assuming x is finite and >= 0, and n is an integer:
1219 Returns the decimal representation of round (x * 10^n).
1220 Return the allocated memory - containing the decimal digits in low-to-high
1221 order, terminated with a NUL character - in case of success, NULL in case
1222 of memory allocation failure. */
1224 scale10_round_decimal_double (double x, int n)
1228 void *memory = decode_double (x, &e, &m);
1229 return scale10_round_decimal_decoded (e, m, memory, n);
1234 # if NEED_PRINTF_LONG_DOUBLE
1236 /* Assuming x is finite and > 0:
1237 Return an approximation for n with 10^n <= x < 10^(n+1).
1238 The approximation is usually the right n, but may be off by 1 sometimes. */
1240 floorlog10l (long double x)
1247 /* Split into exponential part and mantissa. */
1248 y = frexpl (x, &exp);
1249 if (!(y >= 0.0L && y < 1.0L))
1255 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1257 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1258 exp -= GMP_LIMB_BITS;
1260 if (y < (1.0L / (1 << 16)))
1262 y *= 1.0L * (1 << 16);
1265 if (y < (1.0L / (1 << 8)))
1267 y *= 1.0L * (1 << 8);
1270 if (y < (1.0L / (1 << 4)))
1272 y *= 1.0L * (1 << 4);
1275 if (y < (1.0L / (1 << 2)))
1277 y *= 1.0L * (1 << 2);
1280 if (y < (1.0L / (1 << 1)))
1282 y *= 1.0L * (1 << 1);
1286 if (!(y >= 0.5L && y < 1.0L))
1288 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1291 if (z < 0.70710678118654752444)
1293 z *= 1.4142135623730950488;
1296 if (z < 0.8408964152537145431)
1298 z *= 1.1892071150027210667;
1301 if (z < 0.91700404320467123175)
1303 z *= 1.0905077326652576592;
1306 if (z < 0.9576032806985736469)
1308 z *= 1.0442737824274138403;
1311 /* Now 0.95 <= z <= 1.01. */
1313 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1314 Four terms are enough to get an approximation with error < 10^-7. */
1315 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1316 /* Finally multiply with log(2)/log(10), yields an approximation for
1318 l *= 0.30102999566398119523;
1319 /* Round down to the next integer. */
1320 return (int) l + (l < 0 ? -1 : 0);
1325 # if NEED_PRINTF_DOUBLE
1327 /* Assuming x is finite and > 0:
1328 Return an approximation for n with 10^n <= x < 10^(n+1).
1329 The approximation is usually the right n, but may be off by 1 sometimes. */
1331 floorlog10 (double x)
1338 /* Split into exponential part and mantissa. */
1339 y = frexp (x, &exp);
1340 if (!(y >= 0.0 && y < 1.0))
1346 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1348 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1349 exp -= GMP_LIMB_BITS;
1351 if (y < (1.0 / (1 << 16)))
1353 y *= 1.0 * (1 << 16);
1356 if (y < (1.0 / (1 << 8)))
1358 y *= 1.0 * (1 << 8);
1361 if (y < (1.0 / (1 << 4)))
1363 y *= 1.0 * (1 << 4);
1366 if (y < (1.0 / (1 << 2)))
1368 y *= 1.0 * (1 << 2);
1371 if (y < (1.0 / (1 << 1)))
1373 y *= 1.0 * (1 << 1);
1377 if (!(y >= 0.5 && y < 1.0))
1379 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1382 if (z < 0.70710678118654752444)
1384 z *= 1.4142135623730950488;
1387 if (z < 0.8408964152537145431)
1389 z *= 1.1892071150027210667;
1392 if (z < 0.91700404320467123175)
1394 z *= 1.0905077326652576592;
1397 if (z < 0.9576032806985736469)
1399 z *= 1.0442737824274138403;
1402 /* Now 0.95 <= z <= 1.01. */
1404 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1405 Four terms are enough to get an approximation with error < 10^-7. */
1406 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1407 /* Finally multiply with log(2)/log(10), yields an approximation for
1409 l *= 0.30102999566398119523;
1410 /* Round down to the next integer. */
1411 return (int) l + (l < 0 ? -1 : 0);
1416 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1417 a single '1' digit. */
1419 is_borderline (const char *digits, size_t precision)
1421 for (; precision > 0; precision--, digits++)
1427 return *digits == '\0';
1433 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1434 const FCHAR_T *format, va_list args)
1439 if (PRINTF_PARSE (format, &d, &a) < 0)
1440 /* errno is already set. */
1448 if (PRINTF_FETCHARGS (args, &a) < 0)
1456 size_t buf_neededlength;
1458 TCHAR_T *buf_malloced;
1462 /* Output string accumulator. */
1467 /* Allocate a small buffer that will hold a directive passed to
1468 sprintf or snprintf. */
1470 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1472 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1474 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1475 buf_malloced = NULL;
1480 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1481 if (size_overflow_p (buf_memsize))
1482 goto out_of_memory_1;
1483 buf = (TCHAR_T *) malloc (buf_memsize);
1485 goto out_of_memory_1;
1489 if (resultbuf != NULL)
1492 allocated = *lengthp;
1501 result is either == resultbuf or == NULL or malloc-allocated.
1502 If length > 0, then result != NULL. */
1504 /* Ensures that allocated >= needed. Aborts through a jump to
1505 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1506 #define ENSURE_ALLOCATION(needed) \
1507 if ((needed) > allocated) \
1509 size_t memory_size; \
1512 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1513 if ((needed) > allocated) \
1514 allocated = (needed); \
1515 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1516 if (size_overflow_p (memory_size)) \
1517 goto out_of_memory; \
1518 if (result == resultbuf || result == NULL) \
1519 memory = (DCHAR_T *) malloc (memory_size); \
1521 memory = (DCHAR_T *) realloc (result, memory_size); \
1522 if (memory == NULL) \
1523 goto out_of_memory; \
1524 if (result == resultbuf && length > 0) \
1525 DCHAR_CPY (memory, result, length); \
1529 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1531 if (cp != dp->dir_start)
1533 size_t n = dp->dir_start - cp;
1534 size_t augmented_length = xsum (length, n);
1536 ENSURE_ALLOCATION (augmented_length);
1537 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1538 need that the format string contains only ASCII characters
1539 if FCHAR_T and DCHAR_T are not the same type. */
1540 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1542 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1543 length = augmented_length;
1548 result[length++] = (unsigned char) *cp++;
1555 /* Execute a single directive. */
1556 if (dp->conversion == '%')
1558 size_t augmented_length;
1560 if (!(dp->arg_index == ARG_NONE))
1562 augmented_length = xsum (length, 1);
1563 ENSURE_ALLOCATION (augmented_length);
1564 result[length] = '%';
1565 length = augmented_length;
1569 if (!(dp->arg_index != ARG_NONE))
1572 if (dp->conversion == 'n')
1574 switch (a.arg[dp->arg_index].type)
1576 case TYPE_COUNT_SCHAR_POINTER:
1577 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1579 case TYPE_COUNT_SHORT_POINTER:
1580 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1582 case TYPE_COUNT_INT_POINTER:
1583 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1585 case TYPE_COUNT_LONGINT_POINTER:
1586 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1588 #if HAVE_LONG_LONG_INT
1589 case TYPE_COUNT_LONGLONGINT_POINTER:
1590 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1598 /* The unistdio extensions. */
1599 else if (dp->conversion == 'U')
1601 arg_type type = a.arg[dp->arg_index].type;
1602 int flags = dp->flags;
1610 if (dp->width_start != dp->width_end)
1612 if (dp->width_arg_index != ARG_NONE)
1616 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1618 arg = a.arg[dp->width_arg_index].a.a_int;
1621 /* "A negative field width is taken as a '-' flag
1622 followed by a positive field width." */
1624 width = (unsigned int) (-arg);
1631 const FCHAR_T *digitp = dp->width_start;
1634 width = xsum (xtimes (width, 10), *digitp++ - '0');
1635 while (digitp != dp->width_end);
1642 if (dp->precision_start != dp->precision_end)
1644 if (dp->precision_arg_index != ARG_NONE)
1648 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1650 arg = a.arg[dp->precision_arg_index].a.a_int;
1651 /* "A negative precision is taken as if the precision
1661 const FCHAR_T *digitp = dp->precision_start + 1;
1664 while (digitp != dp->precision_end)
1665 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1672 case TYPE_U8_STRING:
1674 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1675 const uint8_t *arg_end;
1680 /* Use only PRECISION characters, from the left. */
1683 for (; precision > 0; precision--)
1685 int count = u8_strmblen (arg_end);
1690 if (!(result == resultbuf || result == NULL))
1692 if (buf_malloced != NULL)
1693 free (buf_malloced);
1704 /* Use the entire string, and count the number of
1710 int count = u8_strmblen (arg_end);
1715 if (!(result == resultbuf || result == NULL))
1717 if (buf_malloced != NULL)
1718 free (buf_malloced);
1729 /* Use the entire string. */
1730 arg_end = arg + u8_strlen (arg);
1731 /* The number of characters doesn't matter. */
1735 if (has_width && width > characters
1736 && !(dp->flags & FLAG_LEFT))
1738 size_t n = width - characters;
1739 ENSURE_ALLOCATION (xsum (length, n));
1740 DCHAR_SET (result + length, ' ', n);
1744 # if DCHAR_IS_UINT8_T
1746 size_t n = arg_end - arg;
1747 ENSURE_ALLOCATION (xsum (length, n));
1748 DCHAR_CPY (result + length, arg, n);
1753 DCHAR_T *converted = result + length;
1754 size_t converted_len = allocated - length;
1756 /* Convert from UTF-8 to locale encoding. */
1757 if (u8_conv_to_encoding (locale_charset (),
1758 iconveh_question_mark,
1759 arg, arg_end - arg, NULL,
1760 &converted, &converted_len)
1763 /* Convert from UTF-8 to UTF-16/UTF-32. */
1765 U8_TO_DCHAR (arg, arg_end - arg,
1766 converted, &converted_len);
1767 if (converted == NULL)
1770 int saved_errno = errno;
1771 if (!(result == resultbuf || result == NULL))
1773 if (buf_malloced != NULL)
1774 free (buf_malloced);
1776 errno = saved_errno;
1779 if (converted != result + length)
1781 ENSURE_ALLOCATION (xsum (length, converted_len));
1782 DCHAR_CPY (result + length, converted, converted_len);
1785 length += converted_len;
1789 if (has_width && width > characters
1790 && (dp->flags & FLAG_LEFT))
1792 size_t n = width - characters;
1793 ENSURE_ALLOCATION (xsum (length, n));
1794 DCHAR_SET (result + length, ' ', n);
1800 case TYPE_U16_STRING:
1802 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1803 const uint16_t *arg_end;
1808 /* Use only PRECISION characters, from the left. */
1811 for (; precision > 0; precision--)
1813 int count = u16_strmblen (arg_end);
1818 if (!(result == resultbuf || result == NULL))
1820 if (buf_malloced != NULL)
1821 free (buf_malloced);
1832 /* Use the entire string, and count the number of
1838 int count = u16_strmblen (arg_end);
1843 if (!(result == resultbuf || result == NULL))
1845 if (buf_malloced != NULL)
1846 free (buf_malloced);
1857 /* Use the entire string. */
1858 arg_end = arg + u16_strlen (arg);
1859 /* The number of characters doesn't matter. */
1863 if (has_width && width > characters
1864 && !(dp->flags & FLAG_LEFT))
1866 size_t n = width - characters;
1867 ENSURE_ALLOCATION (xsum (length, n));
1868 DCHAR_SET (result + length, ' ', n);
1872 # if DCHAR_IS_UINT16_T
1874 size_t n = arg_end - arg;
1875 ENSURE_ALLOCATION (xsum (length, n));
1876 DCHAR_CPY (result + length, arg, n);
1881 DCHAR_T *converted = result + length;
1882 size_t converted_len = allocated - length;
1884 /* Convert from UTF-16 to locale encoding. */
1885 if (u16_conv_to_encoding (locale_charset (),
1886 iconveh_question_mark,
1887 arg, arg_end - arg, NULL,
1888 &converted, &converted_len)
1891 /* Convert from UTF-16 to UTF-8/UTF-32. */
1893 U16_TO_DCHAR (arg, arg_end - arg,
1894 converted, &converted_len);
1895 if (converted == NULL)
1898 int saved_errno = errno;
1899 if (!(result == resultbuf || result == NULL))
1901 if (buf_malloced != NULL)
1902 free (buf_malloced);
1904 errno = saved_errno;
1907 if (converted != result + length)
1909 ENSURE_ALLOCATION (xsum (length, converted_len));
1910 DCHAR_CPY (result + length, converted, converted_len);
1913 length += converted_len;
1917 if (has_width && width > characters
1918 && (dp->flags & FLAG_LEFT))
1920 size_t n = width - characters;
1921 ENSURE_ALLOCATION (xsum (length, n));
1922 DCHAR_SET (result + length, ' ', n);
1928 case TYPE_U32_STRING:
1930 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1931 const uint32_t *arg_end;
1936 /* Use only PRECISION characters, from the left. */
1939 for (; precision > 0; precision--)
1941 int count = u32_strmblen (arg_end);
1946 if (!(result == resultbuf || result == NULL))
1948 if (buf_malloced != NULL)
1949 free (buf_malloced);
1960 /* Use the entire string, and count the number of
1966 int count = u32_strmblen (arg_end);
1971 if (!(result == resultbuf || result == NULL))
1973 if (buf_malloced != NULL)
1974 free (buf_malloced);
1985 /* Use the entire string. */
1986 arg_end = arg + u32_strlen (arg);
1987 /* The number of characters doesn't matter. */
1991 if (has_width && width > characters
1992 && !(dp->flags & FLAG_LEFT))
1994 size_t n = width - characters;
1995 ENSURE_ALLOCATION (xsum (length, n));
1996 DCHAR_SET (result + length, ' ', n);
2000 # if DCHAR_IS_UINT32_T
2002 size_t n = arg_end - arg;
2003 ENSURE_ALLOCATION (xsum (length, n));
2004 DCHAR_CPY (result + length, arg, n);
2009 DCHAR_T *converted = result + length;
2010 size_t converted_len = allocated - length;
2012 /* Convert from UTF-32 to locale encoding. */
2013 if (u32_conv_to_encoding (locale_charset (),
2014 iconveh_question_mark,
2015 arg, arg_end - arg, NULL,
2016 &converted, &converted_len)
2019 /* Convert from UTF-32 to UTF-8/UTF-16. */
2021 U32_TO_DCHAR (arg, arg_end - arg,
2022 converted, &converted_len);
2023 if (converted == NULL)
2026 int saved_errno = errno;
2027 if (!(result == resultbuf || result == NULL))
2029 if (buf_malloced != NULL)
2030 free (buf_malloced);
2032 errno = saved_errno;
2035 if (converted != result + length)
2037 ENSURE_ALLOCATION (xsum (length, converted_len));
2038 DCHAR_CPY (result + length, converted, converted_len);
2041 length += converted_len;
2045 if (has_width && width > characters
2046 && (dp->flags & FLAG_LEFT))
2048 size_t n = width - characters;
2049 ENSURE_ALLOCATION (xsum (length, n));
2050 DCHAR_SET (result + length, ' ', n);
2061 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2062 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2063 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2065 # if NEED_PRINTF_DOUBLE
2066 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2068 # if NEED_PRINTF_LONG_DOUBLE
2069 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2075 arg_type type = a.arg[dp->arg_index].type;
2076 int flags = dp->flags;
2082 DCHAR_T tmpbuf[700];
2089 if (dp->width_start != dp->width_end)
2091 if (dp->width_arg_index != ARG_NONE)
2095 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2097 arg = a.arg[dp->width_arg_index].a.a_int;
2100 /* "A negative field width is taken as a '-' flag
2101 followed by a positive field width." */
2103 width = (unsigned int) (-arg);
2110 const FCHAR_T *digitp = dp->width_start;
2113 width = xsum (xtimes (width, 10), *digitp++ - '0');
2114 while (digitp != dp->width_end);
2121 if (dp->precision_start != dp->precision_end)
2123 if (dp->precision_arg_index != ARG_NONE)
2127 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2129 arg = a.arg[dp->precision_arg_index].a.a_int;
2130 /* "A negative precision is taken as if the precision
2140 const FCHAR_T *digitp = dp->precision_start + 1;
2143 while (digitp != dp->precision_end)
2144 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2149 /* Allocate a temporary buffer of sufficient size. */
2150 if (type == TYPE_LONGDOUBLE)
2152 (unsigned int) ((LDBL_DIG + 1)
2153 * 0.831 /* decimal -> hexadecimal */
2155 + 1; /* turn floor into ceil */
2158 (unsigned int) ((DBL_DIG + 1)
2159 * 0.831 /* decimal -> hexadecimal */
2161 + 1; /* turn floor into ceil */
2162 if (tmp_length < precision)
2163 tmp_length = precision;
2164 /* Account for sign, decimal point etc. */
2165 tmp_length = xsum (tmp_length, 12);
2167 if (tmp_length < width)
2170 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2172 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2176 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2178 if (size_overflow_p (tmp_memsize))
2179 /* Overflow, would lead to out of memory. */
2181 tmp = (DCHAR_T *) malloc (tmp_memsize);
2183 /* Out of memory. */
2189 if (type == TYPE_LONGDOUBLE)
2191 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2192 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2196 if (dp->conversion == 'A')
2198 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2202 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2208 DECL_LONG_DOUBLE_ROUNDING
2210 BEGIN_LONG_DOUBLE_ROUNDING ();
2212 if (signbit (arg)) /* arg < 0.0L or negative zero */
2220 else if (flags & FLAG_SHOWSIGN)
2222 else if (flags & FLAG_SPACE)
2225 if (arg > 0.0L && arg + arg == arg)
2227 if (dp->conversion == 'A')
2229 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2233 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2239 long double mantissa;
2242 mantissa = printf_frexpl (arg, &exponent);
2250 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2252 /* Round the mantissa. */
2253 long double tail = mantissa;
2256 for (q = precision; ; q--)
2258 int digit = (int) tail;
2262 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2271 for (q = precision; q > 0; q--)
2277 *p++ = dp->conversion - 'A' + 'X';
2282 digit = (int) mantissa;
2285 if ((flags & FLAG_ALT)
2286 || mantissa > 0.0L || precision > 0)
2288 *p++ = decimal_point_char ();
2289 /* This loop terminates because we assume
2290 that FLT_RADIX is a power of 2. */
2291 while (mantissa > 0.0L)
2294 digit = (int) mantissa;
2299 : dp->conversion - 10);
2303 while (precision > 0)
2310 *p++ = dp->conversion - 'A' + 'P';
2311 # if WIDE_CHAR_VERSION
2313 static const wchar_t decimal_format[] =
2314 { '%', '+', 'd', '\0' };
2315 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2320 if (sizeof (DCHAR_T) == 1)
2322 sprintf ((char *) p, "%+d", exponent);
2330 sprintf (expbuf, "%+d", exponent);
2331 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2337 END_LONG_DOUBLE_ROUNDING ();
2345 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2346 double arg = a.arg[dp->arg_index].a.a_double;
2350 if (dp->conversion == 'A')
2352 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2356 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2363 if (signbit (arg)) /* arg < 0.0 or negative zero */
2371 else if (flags & FLAG_SHOWSIGN)
2373 else if (flags & FLAG_SPACE)
2376 if (arg > 0.0 && arg + arg == arg)
2378 if (dp->conversion == 'A')
2380 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2384 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2393 mantissa = printf_frexp (arg, &exponent);
2401 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2403 /* Round the mantissa. */
2404 double tail = mantissa;
2407 for (q = precision; ; q--)
2409 int digit = (int) tail;
2413 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2422 for (q = precision; q > 0; q--)
2428 *p++ = dp->conversion - 'A' + 'X';
2433 digit = (int) mantissa;
2436 if ((flags & FLAG_ALT)
2437 || mantissa > 0.0 || precision > 0)
2439 *p++ = decimal_point_char ();
2440 /* This loop terminates because we assume
2441 that FLT_RADIX is a power of 2. */
2442 while (mantissa > 0.0)
2445 digit = (int) mantissa;
2450 : dp->conversion - 10);
2454 while (precision > 0)
2461 *p++ = dp->conversion - 'A' + 'P';
2462 # if WIDE_CHAR_VERSION
2464 static const wchar_t decimal_format[] =
2465 { '%', '+', 'd', '\0' };
2466 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2471 if (sizeof (DCHAR_T) == 1)
2473 sprintf ((char *) p, "%+d", exponent);
2481 sprintf (expbuf, "%+d", exponent);
2482 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2492 /* The generated string now extends from tmp to p, with the
2493 zero padding insertion point being at pad_ptr. */
2494 if (has_width && p - tmp < width)
2496 size_t pad = width - (p - tmp);
2497 DCHAR_T *end = p + pad;
2499 if (flags & FLAG_LEFT)
2501 /* Pad with spaces on the right. */
2502 for (; pad > 0; pad--)
2505 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2507 /* Pad with zeroes. */
2512 for (; pad > 0; pad--)
2517 /* Pad with spaces on the left. */
2522 for (; pad > 0; pad--)
2530 size_t count = p - tmp;
2532 if (count >= tmp_length)
2533 /* tmp_length was incorrectly calculated - fix the
2537 /* Make room for the result. */
2538 if (count >= allocated - length)
2540 size_t n = xsum (length, count);
2542 ENSURE_ALLOCATION (n);
2545 /* Append the result. */
2546 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2553 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2554 else if ((dp->conversion == 'f' || dp->conversion == 'F'
2555 || dp->conversion == 'e' || dp->conversion == 'E'
2556 || dp->conversion == 'g' || dp->conversion == 'G'
2557 || dp->conversion == 'a' || dp->conversion == 'A')
2559 # if NEED_PRINTF_DOUBLE
2560 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2561 # elif NEED_PRINTF_INFINITE_DOUBLE
2562 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2563 /* The systems (mingw) which produce wrong output
2564 for Inf, -Inf, and NaN also do so for -0.0.
2565 Therefore we treat this case here as well. */
2566 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2568 # if NEED_PRINTF_LONG_DOUBLE
2569 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2570 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2571 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2572 /* Some systems produce wrong output for Inf,
2574 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
2578 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2579 arg_type type = a.arg[dp->arg_index].type;
2581 int flags = dp->flags;
2587 DCHAR_T tmpbuf[700];
2594 if (dp->width_start != dp->width_end)
2596 if (dp->width_arg_index != ARG_NONE)
2600 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2602 arg = a.arg[dp->width_arg_index].a.a_int;
2605 /* "A negative field width is taken as a '-' flag
2606 followed by a positive field width." */
2608 width = (unsigned int) (-arg);
2615 const FCHAR_T *digitp = dp->width_start;
2618 width = xsum (xtimes (width, 10), *digitp++ - '0');
2619 while (digitp != dp->width_end);
2626 if (dp->precision_start != dp->precision_end)
2628 if (dp->precision_arg_index != ARG_NONE)
2632 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2634 arg = a.arg[dp->precision_arg_index].a.a_int;
2635 /* "A negative precision is taken as if the precision
2645 const FCHAR_T *digitp = dp->precision_start + 1;
2648 while (digitp != dp->precision_end)
2649 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2654 /* POSIX specifies the default precision to be 6 for %f, %F,
2655 %e, %E, but not for %g, %G. Implementations appear to use
2656 the same default precision also for %g, %G. */
2660 /* Allocate a temporary buffer of sufficient size. */
2661 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2662 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
2663 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2664 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2665 # elif NEED_PRINTF_LONG_DOUBLE
2666 tmp_length = LDBL_DIG + 1;
2667 # elif NEED_PRINTF_DOUBLE
2668 tmp_length = DBL_DIG + 1;
2672 if (tmp_length < precision)
2673 tmp_length = precision;
2674 # if NEED_PRINTF_LONG_DOUBLE
2675 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2676 if (type == TYPE_LONGDOUBLE)
2678 if (dp->conversion == 'f' || dp->conversion == 'F')
2680 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2681 if (!(isnanl (arg) || arg + arg == arg))
2683 /* arg is finite and nonzero. */
2684 int exponent = floorlog10l (arg < 0 ? -arg : arg);
2685 if (exponent >= 0 && tmp_length < exponent + precision)
2686 tmp_length = exponent + precision;
2690 # if NEED_PRINTF_DOUBLE
2691 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2692 if (type == TYPE_DOUBLE)
2694 if (dp->conversion == 'f' || dp->conversion == 'F')
2696 double arg = a.arg[dp->arg_index].a.a_double;
2697 if (!(isnand (arg) || arg + arg == arg))
2699 /* arg is finite and nonzero. */
2700 int exponent = floorlog10 (arg < 0 ? -arg : arg);
2701 if (exponent >= 0 && tmp_length < exponent + precision)
2702 tmp_length = exponent + precision;
2706 /* Account for sign, decimal point etc. */
2707 tmp_length = xsum (tmp_length, 12);
2709 if (tmp_length < width)
2712 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2714 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2718 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2720 if (size_overflow_p (tmp_memsize))
2721 /* Overflow, would lead to out of memory. */
2723 tmp = (DCHAR_T *) malloc (tmp_memsize);
2725 /* Out of memory. */
2732 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2733 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2734 if (type == TYPE_LONGDOUBLE)
2737 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2741 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2743 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2747 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2753 DECL_LONG_DOUBLE_ROUNDING
2755 BEGIN_LONG_DOUBLE_ROUNDING ();
2757 if (signbit (arg)) /* arg < 0.0L or negative zero */
2765 else if (flags & FLAG_SHOWSIGN)
2767 else if (flags & FLAG_SPACE)
2770 if (arg > 0.0L && arg + arg == arg)
2772 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2774 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2778 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2783 # if NEED_PRINTF_LONG_DOUBLE
2786 if (dp->conversion == 'f' || dp->conversion == 'F')
2792 scale10_round_decimal_long_double (arg, precision);
2795 END_LONG_DOUBLE_ROUNDING ();
2798 ndigits = strlen (digits);
2800 if (ndigits > precision)
2804 *p++ = digits[ndigits];
2806 while (ndigits > precision);
2809 /* Here ndigits <= precision. */
2810 if ((flags & FLAG_ALT) || precision > 0)
2812 *p++ = decimal_point_char ();
2813 for (; precision > ndigits; precision--)
2818 *p++ = digits[ndigits];
2824 else if (dp->conversion == 'e' || dp->conversion == 'E')
2832 if ((flags & FLAG_ALT) || precision > 0)
2834 *p++ = decimal_point_char ();
2835 for (; precision > 0; precision--)
2846 exponent = floorlog10l (arg);
2851 scale10_round_decimal_long_double (arg,
2852 (int)precision - exponent);
2855 END_LONG_DOUBLE_ROUNDING ();
2858 ndigits = strlen (digits);
2860 if (ndigits == precision + 1)
2862 if (ndigits < precision
2863 || ndigits > precision + 2)
2864 /* The exponent was not guessed
2865 precisely enough. */
2868 /* None of two values of exponent is
2869 the right one. Prevent an endless
2873 if (ndigits == precision)
2879 /* Here ndigits = precision+1. */
2880 if (is_borderline (digits, precision))
2882 /* Maybe the exponent guess was too high
2883 and a smaller exponent can be reached
2884 by turning a 10...0 into 9...9x. */
2886 scale10_round_decimal_long_double (arg,
2887 (int)precision - exponent + 1);
2888 if (digits2 == NULL)
2891 END_LONG_DOUBLE_ROUNDING ();
2894 if (strlen (digits2) == precision + 1)
2903 /* Here ndigits = precision+1. */
2905 *p++ = digits[--ndigits];
2906 if ((flags & FLAG_ALT) || precision > 0)
2908 *p++ = decimal_point_char ();
2912 *p++ = digits[ndigits];
2919 *p++ = dp->conversion; /* 'e' or 'E' */
2920 # if WIDE_CHAR_VERSION
2922 static const wchar_t decimal_format[] =
2923 { '%', '+', '.', '2', 'd', '\0' };
2924 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2929 if (sizeof (DCHAR_T) == 1)
2931 sprintf ((char *) p, "%+.2d", exponent);
2939 sprintf (expbuf, "%+.2d", exponent);
2940 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2945 else if (dp->conversion == 'g' || dp->conversion == 'G')
2949 /* precision >= 1. */
2952 /* The exponent is 0, >= -4, < precision.
2953 Use fixed-point notation. */
2955 size_t ndigits = precision;
2956 /* Number of trailing zeroes that have to be
2959 (flags & FLAG_ALT ? 0 : precision - 1);
2963 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2965 *p++ = decimal_point_char ();
2966 while (ndigits > nzeroes)
2982 exponent = floorlog10l (arg);
2987 scale10_round_decimal_long_double (arg,
2988 (int)(precision - 1) - exponent);
2991 END_LONG_DOUBLE_ROUNDING ();
2994 ndigits = strlen (digits);
2996 if (ndigits == precision)
2998 if (ndigits < precision - 1
2999 || ndigits > precision + 1)
3000 /* The exponent was not guessed
3001 precisely enough. */
3004 /* None of two values of exponent is
3005 the right one. Prevent an endless
3009 if (ndigits < precision)
3015 /* Here ndigits = precision. */
3016 if (is_borderline (digits, precision - 1))
3018 /* Maybe the exponent guess was too high
3019 and a smaller exponent can be reached
3020 by turning a 10...0 into 9...9x. */
3022 scale10_round_decimal_long_double (arg,
3023 (int)(precision - 1) - exponent + 1);
3024 if (digits2 == NULL)
3027 END_LONG_DOUBLE_ROUNDING ();
3030 if (strlen (digits2) == precision)
3039 /* Here ndigits = precision. */
3041 /* Determine the number of trailing zeroes
3042 that have to be dropped. */
3044 if ((flags & FLAG_ALT) == 0)
3045 while (nzeroes < ndigits
3046 && digits[nzeroes] == '0')
3049 /* The exponent is now determined. */
3051 && exponent < (long)precision)
3053 /* Fixed-point notation:
3054 max(exponent,0)+1 digits, then the
3055 decimal point, then the remaining
3056 digits without trailing zeroes. */
3059 size_t count = exponent + 1;
3060 /* Note: count <= precision = ndigits. */
3061 for (; count > 0; count--)
3062 *p++ = digits[--ndigits];
3063 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3065 *p++ = decimal_point_char ();
3066 while (ndigits > nzeroes)
3069 *p++ = digits[ndigits];
3075 size_t count = -exponent - 1;
3077 *p++ = decimal_point_char ();
3078 for (; count > 0; count--)
3080 while (ndigits > nzeroes)
3083 *p++ = digits[ndigits];
3089 /* Exponential notation. */
3090 *p++ = digits[--ndigits];
3091 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3093 *p++ = decimal_point_char ();
3094 while (ndigits > nzeroes)
3097 *p++ = digits[ndigits];
3100 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3101 # if WIDE_CHAR_VERSION
3103 static const wchar_t decimal_format[] =
3104 { '%', '+', '.', '2', 'd', '\0' };
3105 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3110 if (sizeof (DCHAR_T) == 1)
3112 sprintf ((char *) p, "%+.2d", exponent);
3120 sprintf (expbuf, "%+.2d", exponent);
3121 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3133 /* arg is finite. */
3138 END_LONG_DOUBLE_ROUNDING ();
3141 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3145 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3147 double arg = a.arg[dp->arg_index].a.a_double;
3151 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3153 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3157 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3164 if (signbit (arg)) /* arg < 0.0 or negative zero */
3172 else if (flags & FLAG_SHOWSIGN)
3174 else if (flags & FLAG_SPACE)
3177 if (arg > 0.0 && arg + arg == arg)
3179 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3181 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3185 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3190 # if NEED_PRINTF_DOUBLE
3193 if (dp->conversion == 'f' || dp->conversion == 'F')
3199 scale10_round_decimal_double (arg, precision);
3202 ndigits = strlen (digits);
3204 if (ndigits > precision)
3208 *p++ = digits[ndigits];
3210 while (ndigits > precision);
3213 /* Here ndigits <= precision. */
3214 if ((flags & FLAG_ALT) || precision > 0)
3216 *p++ = decimal_point_char ();
3217 for (; precision > ndigits; precision--)
3222 *p++ = digits[ndigits];
3228 else if (dp->conversion == 'e' || dp->conversion == 'E')
3236 if ((flags & FLAG_ALT) || precision > 0)
3238 *p++ = decimal_point_char ();
3239 for (; precision > 0; precision--)
3250 exponent = floorlog10 (arg);
3255 scale10_round_decimal_double (arg,
3256 (int)precision - exponent);
3259 ndigits = strlen (digits);
3261 if (ndigits == precision + 1)
3263 if (ndigits < precision
3264 || ndigits > precision + 2)
3265 /* The exponent was not guessed
3266 precisely enough. */
3269 /* None of two values of exponent is
3270 the right one. Prevent an endless
3274 if (ndigits == precision)
3280 /* Here ndigits = precision+1. */
3281 if (is_borderline (digits, precision))
3283 /* Maybe the exponent guess was too high
3284 and a smaller exponent can be reached
3285 by turning a 10...0 into 9...9x. */
3287 scale10_round_decimal_double (arg,
3288 (int)precision - exponent + 1);
3289 if (digits2 == NULL)
3294 if (strlen (digits2) == precision + 1)
3303 /* Here ndigits = precision+1. */
3305 *p++ = digits[--ndigits];
3306 if ((flags & FLAG_ALT) || precision > 0)
3308 *p++ = decimal_point_char ();
3312 *p++ = digits[ndigits];
3319 *p++ = dp->conversion; /* 'e' or 'E' */
3320 # if WIDE_CHAR_VERSION
3322 static const wchar_t decimal_format[] =
3323 /* Produce the same number of exponent digits
3324 as the native printf implementation. */
3325 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3326 { '%', '+', '.', '3', 'd', '\0' };
3328 { '%', '+', '.', '2', 'd', '\0' };
3330 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3336 static const char decimal_format[] =
3337 /* Produce the same number of exponent digits
3338 as the native printf implementation. */
3339 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3344 if (sizeof (DCHAR_T) == 1)
3346 sprintf ((char *) p, decimal_format, exponent);
3354 sprintf (expbuf, decimal_format, exponent);
3355 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3361 else if (dp->conversion == 'g' || dp->conversion == 'G')
3365 /* precision >= 1. */
3368 /* The exponent is 0, >= -4, < precision.
3369 Use fixed-point notation. */
3371 size_t ndigits = precision;
3372 /* Number of trailing zeroes that have to be
3375 (flags & FLAG_ALT ? 0 : precision - 1);
3379 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3381 *p++ = decimal_point_char ();
3382 while (ndigits > nzeroes)
3398 exponent = floorlog10 (arg);
3403 scale10_round_decimal_double (arg,
3404 (int)(precision - 1) - exponent);
3407 ndigits = strlen (digits);
3409 if (ndigits == precision)
3411 if (ndigits < precision - 1
3412 || ndigits > precision + 1)
3413 /* The exponent was not guessed
3414 precisely enough. */
3417 /* None of two values of exponent is
3418 the right one. Prevent an endless
3422 if (ndigits < precision)
3428 /* Here ndigits = precision. */
3429 if (is_borderline (digits, precision - 1))
3431 /* Maybe the exponent guess was too high
3432 and a smaller exponent can be reached
3433 by turning a 10...0 into 9...9x. */
3435 scale10_round_decimal_double (arg,
3436 (int)(precision - 1) - exponent + 1);
3437 if (digits2 == NULL)
3442 if (strlen (digits2) == precision)
3451 /* Here ndigits = precision. */
3453 /* Determine the number of trailing zeroes
3454 that have to be dropped. */
3456 if ((flags & FLAG_ALT) == 0)
3457 while (nzeroes < ndigits
3458 && digits[nzeroes] == '0')
3461 /* The exponent is now determined. */
3463 && exponent < (long)precision)
3465 /* Fixed-point notation:
3466 max(exponent,0)+1 digits, then the
3467 decimal point, then the remaining
3468 digits without trailing zeroes. */
3471 size_t count = exponent + 1;
3472 /* Note: count <= precision = ndigits. */
3473 for (; count > 0; count--)
3474 *p++ = digits[--ndigits];
3475 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3477 *p++ = decimal_point_char ();
3478 while (ndigits > nzeroes)
3481 *p++ = digits[ndigits];
3487 size_t count = -exponent - 1;
3489 *p++ = decimal_point_char ();
3490 for (; count > 0; count--)
3492 while (ndigits > nzeroes)
3495 *p++ = digits[ndigits];
3501 /* Exponential notation. */
3502 *p++ = digits[--ndigits];
3503 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3505 *p++ = decimal_point_char ();
3506 while (ndigits > nzeroes)
3509 *p++ = digits[ndigits];
3512 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3513 # if WIDE_CHAR_VERSION
3515 static const wchar_t decimal_format[] =
3516 /* Produce the same number of exponent digits
3517 as the native printf implementation. */
3518 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3519 { '%', '+', '.', '3', 'd', '\0' };
3521 { '%', '+', '.', '2', 'd', '\0' };
3523 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3529 static const char decimal_format[] =
3530 /* Produce the same number of exponent digits
3531 as the native printf implementation. */
3532 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3537 if (sizeof (DCHAR_T) == 1)
3539 sprintf ((char *) p, decimal_format, exponent);
3547 sprintf (expbuf, decimal_format, exponent);
3548 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3561 /* arg is finite. */
3567 if (dp->conversion == 'f' || dp->conversion == 'F')
3570 if ((flags & FLAG_ALT) || precision > 0)
3572 *p++ = decimal_point_char ();
3573 for (; precision > 0; precision--)
3577 else if (dp->conversion == 'e' || dp->conversion == 'E')
3580 if ((flags & FLAG_ALT) || precision > 0)
3582 *p++ = decimal_point_char ();
3583 for (; precision > 0; precision--)
3586 *p++ = dp->conversion; /* 'e' or 'E' */
3588 /* Produce the same number of exponent digits as
3589 the native printf implementation. */
3590 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3596 else if (dp->conversion == 'g' || dp->conversion == 'G')
3599 if (flags & FLAG_ALT)
3602 (precision > 0 ? precision - 1 : 0);
3603 *p++ = decimal_point_char ();
3604 for (; ndigits > 0; --ndigits)
3616 /* The generated string now extends from tmp to p, with the
3617 zero padding insertion point being at pad_ptr. */
3618 if (has_width && p - tmp < width)
3620 size_t pad = width - (p - tmp);
3621 DCHAR_T *end = p + pad;
3623 if (flags & FLAG_LEFT)
3625 /* Pad with spaces on the right. */
3626 for (; pad > 0; pad--)
3629 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3631 /* Pad with zeroes. */
3636 for (; pad > 0; pad--)
3641 /* Pad with spaces on the left. */
3646 for (; pad > 0; pad--)
3654 size_t count = p - tmp;
3656 if (count >= tmp_length)
3657 /* tmp_length was incorrectly calculated - fix the
3661 /* Make room for the result. */
3662 if (count >= allocated - length)
3664 size_t n = xsum (length, count);
3666 ENSURE_ALLOCATION (n);
3669 /* Append the result. */
3670 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3679 arg_type type = a.arg[dp->arg_index].type;
3680 int flags = dp->flags;
3681 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3685 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3689 #if NEED_PRINTF_UNBOUNDED_PRECISION
3692 # define prec_ourselves 0
3694 #if NEED_PRINTF_FLAG_LEFTADJUST
3695 # define pad_ourselves 1
3696 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3699 # define pad_ourselves 0
3702 unsigned int prefix_count;
3706 TCHAR_T tmpbuf[700];
3710 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3713 if (dp->width_start != dp->width_end)
3715 if (dp->width_arg_index != ARG_NONE)
3719 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3721 arg = a.arg[dp->width_arg_index].a.a_int;
3724 /* "A negative field width is taken as a '-' flag
3725 followed by a positive field width." */
3727 width = (unsigned int) (-arg);
3734 const FCHAR_T *digitp = dp->width_start;
3737 width = xsum (xtimes (width, 10), *digitp++ - '0');
3738 while (digitp != dp->width_end);
3744 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3747 if (dp->precision_start != dp->precision_end)
3749 if (dp->precision_arg_index != ARG_NONE)
3753 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3755 arg = a.arg[dp->precision_arg_index].a.a_int;
3756 /* "A negative precision is taken as if the precision
3766 const FCHAR_T *digitp = dp->precision_start + 1;
3769 while (digitp != dp->precision_end)
3770 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3776 /* Decide whether to handle the precision ourselves. */
3777 #if NEED_PRINTF_UNBOUNDED_PRECISION
3778 switch (dp->conversion)
3780 case 'd': case 'i': case 'u':
3782 case 'x': case 'X': case 'p':
3783 prec_ourselves = has_precision && (precision > 0);
3791 /* Decide whether to perform the padding ourselves. */
3792 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
3793 switch (dp->conversion)
3795 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
3796 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
3797 to perform the padding after this conversion. Functions
3798 with unistdio extensions perform the padding based on
3799 character count rather than element count. */
3802 # if NEED_PRINTF_FLAG_ZERO
3803 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
3809 pad_ourselves = prec_ourselves;
3815 /* Allocate a temporary buffer of sufficient size for calling
3818 switch (dp->conversion)
3821 case 'd': case 'i': case 'u':
3822 # if HAVE_LONG_LONG_INT
3823 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3825 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3826 * 0.30103 /* binary -> decimal */
3828 + 1; /* turn floor into ceil */
3831 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3833 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3834 * 0.30103 /* binary -> decimal */
3836 + 1; /* turn floor into ceil */
3839 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3840 * 0.30103 /* binary -> decimal */
3842 + 1; /* turn floor into ceil */
3843 if (tmp_length < precision)
3844 tmp_length = precision;
3845 /* Multiply by 2, as an estimate for FLAG_GROUP. */
3846 tmp_length = xsum (tmp_length, tmp_length);
3847 /* Add 1, to account for a leading sign. */
3848 tmp_length = xsum (tmp_length, 1);
3852 # if HAVE_LONG_LONG_INT
3853 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3855 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3856 * 0.333334 /* binary -> octal */
3858 + 1; /* turn floor into ceil */
3861 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3863 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3864 * 0.333334 /* binary -> octal */
3866 + 1; /* turn floor into ceil */
3869 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3870 * 0.333334 /* binary -> octal */
3872 + 1; /* turn floor into ceil */
3873 if (tmp_length < precision)
3874 tmp_length = precision;
3875 /* Add 1, to account for a leading sign. */
3876 tmp_length = xsum (tmp_length, 1);
3880 # if HAVE_LONG_LONG_INT
3881 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3883 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3884 * 0.25 /* binary -> hexadecimal */
3886 + 1; /* turn floor into ceil */
3889 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3891 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3892 * 0.25 /* binary -> hexadecimal */
3894 + 1; /* turn floor into ceil */
3897 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3898 * 0.25 /* binary -> hexadecimal */
3900 + 1; /* turn floor into ceil */
3901 if (tmp_length < precision)
3902 tmp_length = precision;
3903 /* Add 2, to account for a leading sign or alternate form. */
3904 tmp_length = xsum (tmp_length, 2);
3908 if (type == TYPE_LONGDOUBLE)
3910 (unsigned int) (LDBL_MAX_EXP
3911 * 0.30103 /* binary -> decimal */
3912 * 2 /* estimate for FLAG_GROUP */
3914 + 1 /* turn floor into ceil */
3915 + 10; /* sign, decimal point etc. */
3918 (unsigned int) (DBL_MAX_EXP
3919 * 0.30103 /* binary -> decimal */
3920 * 2 /* estimate for FLAG_GROUP */
3922 + 1 /* turn floor into ceil */
3923 + 10; /* sign, decimal point etc. */
3924 tmp_length = xsum (tmp_length, precision);
3927 case 'e': case 'E': case 'g': case 'G':
3929 12; /* sign, decimal point, exponent etc. */
3930 tmp_length = xsum (tmp_length, precision);
3934 if (type == TYPE_LONGDOUBLE)
3936 (unsigned int) (LDBL_DIG
3937 * 0.831 /* decimal -> hexadecimal */
3939 + 1; /* turn floor into ceil */
3942 (unsigned int) (DBL_DIG
3943 * 0.831 /* decimal -> hexadecimal */
3945 + 1; /* turn floor into ceil */
3946 if (tmp_length < precision)
3947 tmp_length = precision;
3948 /* Account for sign, decimal point etc. */
3949 tmp_length = xsum (tmp_length, 12);
3953 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
3954 if (type == TYPE_WIDE_CHAR)
3955 tmp_length = MB_CUR_MAX;
3963 if (type == TYPE_WIDE_STRING)
3966 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
3968 # if !WIDE_CHAR_VERSION
3969 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
3974 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
3979 (unsigned int) (sizeof (void *) * CHAR_BIT
3980 * 0.25 /* binary -> hexadecimal */
3982 + 1 /* turn floor into ceil */
3983 + 2; /* account for leading 0x */
3992 # if ENABLE_UNISTDIO
3993 /* Padding considers the number of characters, therefore
3994 the number of elements after padding may be
3995 > max (tmp_length, width)
3997 <= tmp_length + width. */
3998 tmp_length = xsum (tmp_length, width);
4000 /* Padding considers the number of elements,
4002 if (tmp_length < width)
4007 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
4010 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4014 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4016 if (size_overflow_p (tmp_memsize))
4017 /* Overflow, would lead to out of memory. */
4019 tmp = (TCHAR_T *) malloc (tmp_memsize);
4021 /* Out of memory. */
4026 /* Construct the format string for calling snprintf or
4030 #if NEED_PRINTF_FLAG_GROUPING
4031 /* The underlying implementation doesn't support the ' flag.
4032 Produce no grouping characters in this case; this is
4033 acceptable because the grouping is locale dependent. */
4035 if (flags & FLAG_GROUP)
4038 if (flags & FLAG_LEFT)
4040 if (flags & FLAG_SHOWSIGN)
4042 if (flags & FLAG_SPACE)
4044 if (flags & FLAG_ALT)
4048 if (flags & FLAG_ZERO)
4050 if (dp->width_start != dp->width_end)
4052 size_t n = dp->width_end - dp->width_start;
4053 /* The width specification is known to consist only
4054 of standard ASCII characters. */
4055 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4057 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4062 const FCHAR_T *mp = dp->width_start;
4064 *fbp++ = (unsigned char) *mp++;
4069 if (!prec_ourselves)
4071 if (dp->precision_start != dp->precision_end)
4073 size_t n = dp->precision_end - dp->precision_start;
4074 /* The precision specification is known to consist only
4075 of standard ASCII characters. */
4076 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4078 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4083 const FCHAR_T *mp = dp->precision_start;
4085 *fbp++ = (unsigned char) *mp++;
4093 #if HAVE_LONG_LONG_INT
4094 case TYPE_LONGLONGINT:
4095 case TYPE_ULONGLONGINT:
4096 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4109 case TYPE_WIDE_CHAR:
4112 case TYPE_WIDE_STRING:
4116 case TYPE_LONGDOUBLE:
4122 #if NEED_PRINTF_DIRECTIVE_F
4123 if (dp->conversion == 'F')
4127 *fbp = dp->conversion;
4129 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4134 /* On glibc2 systems from glibc >= 2.3 - probably also older
4135 ones - we know that snprintf's returns value conforms to
4136 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4137 Therefore we can avoid using %n in this situation.
4138 On glibc2 systems from 2004-10-18 or newer, the use of %n
4139 in format strings in writable memory may crash the program
4140 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4141 in this situation. */
4142 /* On native Win32 systems (such as mingw), we can avoid using
4144 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4145 snprintf does not write more than the specified number
4146 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4147 '4', '5', '6' into buf, not '4', '5', '\0'.)
4148 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4149 allows us to recognize the case of an insufficient
4150 buffer size: it returns -1 in this case.
4151 On native Win32 systems (such as mingw) where the OS is
4152 Windows Vista, the use of %n in format strings by default
4153 crashes the program. See
4154 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4155 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4156 So we should avoid %n in this situation. */
4163 /* Construct the arguments for calling snprintf or sprintf. */
4165 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4167 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4169 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4171 if (dp->precision_arg_index != ARG_NONE)
4173 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4175 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4179 /* The SNPRINTF result is appended after result[0..length].
4180 The latter is an array of DCHAR_T; SNPRINTF appends an
4181 array of TCHAR_T to it. This is possible because
4182 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4183 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4184 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4185 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4186 where an snprintf() with maxlen==1 acts like sprintf(). */
4187 ENSURE_ALLOCATION (xsum (length,
4188 (2 + TCHARS_PER_DCHAR - 1)
4189 / TCHARS_PER_DCHAR));
4190 /* Prepare checking whether snprintf returns the count
4192 *(TCHAR_T *) (result + length) = '\0';
4201 size_t maxlen = allocated - length;
4202 /* SNPRINTF can fail if its second argument is
4204 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4205 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4206 maxlen = maxlen * TCHARS_PER_DCHAR;
4207 # define SNPRINTF_BUF(arg) \
4208 switch (prefix_count) \
4211 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4216 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4218 prefixes[0], arg, &count); \
4221 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4223 prefixes[0], prefixes[1], arg, \
4230 # define SNPRINTF_BUF(arg) \
4231 switch (prefix_count) \
4234 count = sprintf (tmp, buf, arg); \
4237 count = sprintf (tmp, buf, prefixes[0], arg); \
4240 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4252 int arg = a.arg[dp->arg_index].a.a_schar;
4258 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4264 int arg = a.arg[dp->arg_index].a.a_short;
4270 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4276 int arg = a.arg[dp->arg_index].a.a_int;
4282 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4288 long int arg = a.arg[dp->arg_index].a.a_longint;
4294 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4298 #if HAVE_LONG_LONG_INT
4299 case TYPE_LONGLONGINT:
4301 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4305 case TYPE_ULONGLONGINT:
4307 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4314 double arg = a.arg[dp->arg_index].a.a_double;
4318 case TYPE_LONGDOUBLE:
4320 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4326 int arg = a.arg[dp->arg_index].a.a_char;
4331 case TYPE_WIDE_CHAR:
4333 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
4340 const char *arg = a.arg[dp->arg_index].a.a_string;
4345 case TYPE_WIDE_STRING:
4347 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
4354 void *arg = a.arg[dp->arg_index].a.a_pointer;
4363 /* Portability: Not all implementations of snprintf()
4364 are ISO C 99 compliant. Determine the number of
4365 bytes that snprintf() has produced or would have
4369 /* Verify that snprintf() has NUL-terminated its
4372 && ((TCHAR_T *) (result + length)) [count] != '\0')
4374 /* Portability hack. */
4375 if (retcount > count)
4380 /* snprintf() doesn't understand the '%n'
4384 /* Don't use the '%n' directive; instead, look
4385 at the snprintf() return value. */
4391 /* Look at the snprintf() return value. */
4394 /* HP-UX 10.20 snprintf() is doubly deficient:
4395 It doesn't understand the '%n' directive,
4396 *and* it returns -1 (rather than the length
4397 that would have been required) when the
4398 buffer is too small. */
4399 size_t bigger_need =
4400 xsum (xtimes (allocated, 2), 12);
4401 ENSURE_ALLOCATION (bigger_need);
4410 /* Attempt to handle failure. */
4413 if (!(result == resultbuf || result == NULL))
4415 if (buf_malloced != NULL)
4416 free (buf_malloced);
4423 /* Handle overflow of the allocated buffer.
4424 If such an overflow occurs, a C99 compliant snprintf()
4425 returns a count >= maxlen. However, a non-compliant
4426 snprintf() function returns only count = maxlen - 1. To
4427 cover both cases, test whether count >= maxlen - 1. */
4428 if ((unsigned int) count + 1 >= maxlen)
4430 /* If maxlen already has attained its allowed maximum,
4431 allocating more memory will not increase maxlen.
4432 Instead of looping, bail out. */
4433 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
4437 /* Need at least (count + 1) * sizeof (TCHAR_T)
4438 bytes. (The +1 is for the trailing NUL.)
4439 But ask for (count + 2) * sizeof (TCHAR_T)
4440 bytes, so that in the next round, we likely get
4441 maxlen > (unsigned int) count + 1
4442 and so we don't get here again.
4443 And allocate proportionally, to avoid looping
4444 eternally if snprintf() reports a too small
4448 ((unsigned int) count + 2
4449 + TCHARS_PER_DCHAR - 1)
4450 / TCHARS_PER_DCHAR),
4451 xtimes (allocated, 2));
4453 ENSURE_ALLOCATION (n);
4459 #if NEED_PRINTF_UNBOUNDED_PRECISION
4462 /* Handle the precision. */
4465 (TCHAR_T *) (result + length);
4469 size_t prefix_count;
4473 /* Put the additional zeroes after the sign. */
4475 && (*prec_ptr == '-' || *prec_ptr == '+'
4476 || *prec_ptr == ' '))
4478 /* Put the additional zeroes after the 0x prefix if
4479 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
4481 && prec_ptr[0] == '0'
4482 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
4485 move = count - prefix_count;
4486 if (precision > move)
4488 /* Insert zeroes. */
4489 size_t insert = precision - move;
4495 (count + insert + TCHARS_PER_DCHAR - 1)
4496 / TCHARS_PER_DCHAR);
4497 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4498 ENSURE_ALLOCATION (n);
4499 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4500 prec_ptr = (TCHAR_T *) (result + length);
4503 prec_end = prec_ptr + count;
4504 prec_ptr += prefix_count;
4506 while (prec_end > prec_ptr)
4509 prec_end[insert] = prec_end[0];
4515 while (prec_end > prec_ptr);
4523 if (count >= tmp_length)
4524 /* tmp_length was incorrectly calculated - fix the
4530 /* Convert from TCHAR_T[] to DCHAR_T[]. */
4531 if (dp->conversion == 'c' || dp->conversion == 's')
4533 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
4535 The result string is not certainly ASCII. */
4536 const TCHAR_T *tmpsrc;
4539 /* This code assumes that TCHAR_T is 'char'. */
4540 typedef int TCHAR_T_verify
4541 [2 * (sizeof (TCHAR_T) == 1) - 1];
4543 tmpsrc = (TCHAR_T *) (result + length);
4549 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
4550 iconveh_question_mark,
4553 &tmpdst, &tmpdst_len)
4556 int saved_errno = errno;
4557 if (!(result == resultbuf || result == NULL))
4559 if (buf_malloced != NULL)
4560 free (buf_malloced);
4562 errno = saved_errno;
4565 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
4566 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
4572 /* The result string is ASCII.
4573 Simple 1:1 conversion. */
4575 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
4576 no-op conversion, in-place on the array starting
4577 at (result + length). */
4578 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
4581 const TCHAR_T *tmpsrc;
4586 if (result == resultbuf)
4588 tmpsrc = (TCHAR_T *) (result + length);
4589 /* ENSURE_ALLOCATION will not move tmpsrc
4590 (because it's part of resultbuf). */
4591 ENSURE_ALLOCATION (xsum (length, count));
4595 /* ENSURE_ALLOCATION will move the array
4596 (because it uses realloc(). */
4597 ENSURE_ALLOCATION (xsum (length, count));
4598 tmpsrc = (TCHAR_T *) (result + length);
4602 ENSURE_ALLOCATION (xsum (length, count));
4604 tmpdst = result + length;
4605 /* Copy backwards, because of overlapping. */
4608 for (n = count; n > 0; n--)
4609 *--tmpdst = (unsigned char) *--tmpsrc;
4614 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4615 /* Make room for the result. */
4616 if (count > allocated - length)
4618 /* Need at least count elements. But allocate
4621 xmax (xsum (length, count), xtimes (allocated, 2));
4623 ENSURE_ALLOCATION (n);
4627 /* Here count <= allocated - length. */
4629 /* Perform padding. */
4630 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4631 if (pad_ourselves && has_width)
4634 # if ENABLE_UNISTDIO
4635 /* Outside POSIX, it's preferrable to compare the width
4636 against the number of _characters_ of the converted
4638 w = DCHAR_MBSNLEN (result + length, count);
4640 /* The width is compared against the number of _bytes_
4641 of the converted value, says POSIX. */
4646 size_t pad = width - w;
4648 /* Make room for the result. */
4649 if (xsum (count, pad) > allocated - length)
4651 /* Need at least count + pad elements. But
4652 allocate proportionally. */
4654 xmax (xsum3 (length, count, pad),
4655 xtimes (allocated, 2));
4659 ENSURE_ALLOCATION (n);
4662 ENSURE_ALLOCATION (n);
4665 /* Here count + pad <= allocated - length. */
4668 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
4669 DCHAR_T * const rp = result + length;
4671 DCHAR_T * const rp = tmp;
4673 DCHAR_T *p = rp + count;
4674 DCHAR_T *end = p + pad;
4676 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4677 if (dp->conversion == 'c'
4678 || dp->conversion == 's')
4679 /* No zero-padding for string directives. */
4684 pad_ptr = (*rp == '-' ? rp + 1 : rp);
4685 /* No zero-padding of "inf" and "nan". */
4686 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
4687 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
4690 /* The generated string now extends from rp to p,
4691 with the zero padding insertion point being at
4694 count = count + pad; /* = end - rp */
4696 if (flags & FLAG_LEFT)
4698 /* Pad with spaces on the right. */
4699 for (; pad > 0; pad--)
4702 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4704 /* Pad with zeroes. */
4709 for (; pad > 0; pad--)
4714 /* Pad with spaces on the left. */
4719 for (; pad > 0; pad--)
4727 /* Here still count <= allocated - length. */
4729 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
4730 /* The snprintf() result did fit. */
4732 /* Append the sprintf() result. */
4733 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4740 #if NEED_PRINTF_DIRECTIVE_F
4741 if (dp->conversion == 'F')
4743 /* Convert the %f result to upper case for %F. */
4744 DCHAR_T *rp = result + length;
4746 for (rc = count; rc > 0; rc--, rp++)
4747 if (*rp >= 'a' && *rp <= 'z')
4748 *rp = *rp - 'a' + 'A';
4759 /* Add the final NUL. */
4760 ENSURE_ALLOCATION (xsum (length, 1));
4761 result[length] = '\0';
4763 if (result != resultbuf && length + 1 < allocated)
4765 /* Shrink the allocated memory if possible. */
4768 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
4773 if (buf_malloced != NULL)
4774 free (buf_malloced);
4777 /* Note that we can produce a big string of a length > INT_MAX. POSIX
4778 says that snprintf() fails with errno = EOVERFLOW in this case, but
4779 that's only because snprintf() returns an 'int'. This function does
4780 not have this limitation. */
4785 if (!(result == resultbuf || result == NULL))
4787 if (buf_malloced != NULL)
4788 free (buf_malloced);
4795 if (!(result == resultbuf || result == NULL))
4797 if (buf_malloced != NULL)
4798 free (buf_malloced);
4806 #undef TCHARS_PER_DCHAR
4813 #undef DCHAR_IS_TCHAR