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 3, 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"
120 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
122 # define EOVERFLOW E2BIG
127 # define local_wcslen wcslen
129 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
130 a dependency towards this library, here is a local substitute.
131 Define this substitute only once, even if this file is included
132 twice in the same compilation unit. */
133 # ifndef local_wcslen_defined
134 # define local_wcslen_defined 1
136 local_wcslen (const wchar_t *s)
140 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
148 /* Default parameters. */
150 # if WIDE_CHAR_VERSION
151 # define VASNPRINTF vasnwprintf
152 # define FCHAR_T wchar_t
153 # define DCHAR_T wchar_t
154 # define TCHAR_T wchar_t
155 # define DCHAR_IS_TCHAR 1
156 # define DIRECTIVE wchar_t_directive
157 # define DIRECTIVES wchar_t_directives
158 # define PRINTF_PARSE wprintf_parse
159 # define DCHAR_CPY wmemcpy
161 # define VASNPRINTF vasnprintf
162 # define FCHAR_T char
163 # define DCHAR_T char
164 # define TCHAR_T char
165 # define DCHAR_IS_TCHAR 1
166 # define DIRECTIVE char_directive
167 # define DIRECTIVES char_directives
168 # define PRINTF_PARSE printf_parse
169 # define DCHAR_CPY memcpy
172 #if WIDE_CHAR_VERSION
173 /* TCHAR_T is wchar_t. */
174 # define USE_SNPRINTF 1
175 # if HAVE_DECL__SNWPRINTF
176 /* On Windows, the function swprintf() has a different signature than
177 on Unix; we use the _snwprintf() function instead. */
178 # define SNPRINTF _snwprintf
181 # define SNPRINTF swprintf
184 /* TCHAR_T is char. */
185 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
186 But don't use it on BeOS, since BeOS snprintf produces no output if the
187 size argument is >= 0x3000000. */
188 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
189 # define USE_SNPRINTF 1
191 # define USE_SNPRINTF 0
193 # if HAVE_DECL__SNPRINTF
195 # define SNPRINTF _snprintf
198 # define SNPRINTF snprintf
199 /* Here we need to call the native snprintf, not rpl_snprintf. */
203 /* Here we need to call the native sprintf, not rpl_sprintf. */
206 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
207 /* Determine the decimal-point character according to the current locale. */
208 # ifndef decimal_point_char_defined
209 # define decimal_point_char_defined 1
211 decimal_point_char ()
214 /* Determine it in a multithread-safe way. We know nl_langinfo is
215 multithread-safe on glibc systems, but is not required to be multithread-
216 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
217 is rarely multithread-safe. */
218 # if HAVE_NL_LANGINFO && __GLIBC__
219 point = nl_langinfo (RADIXCHAR);
222 sprintf (pointbuf, "%#.0f", 1.0);
223 point = &pointbuf[1];
225 point = localeconv () -> decimal_point;
227 /* The decimal point is always a single byte: either '.' or ','. */
228 return (point[0] != '\0' ? point[0] : '.');
233 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
235 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
237 is_infinite_or_zero (double x)
239 return isnand (x) || x + x == x;
244 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
246 /* Equivalent to !isfinite(x), but does not require libm. */
248 is_infinitel (long double x)
250 return isnanl (x) || (x + x == x && x != 0.0L);
255 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
257 /* Converting 'long double' to decimal without rare rounding bugs requires
258 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
259 (and slower) algorithms. */
261 typedef unsigned int mp_limb_t;
262 # define GMP_LIMB_BITS 32
263 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
265 typedef unsigned long long mp_twolimb_t;
266 # define GMP_TWOLIMB_BITS 64
267 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
269 /* Representation of a bignum >= 0. */
273 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
276 /* Compute the product of two bignums >= 0.
277 Return the allocated memory in case of success, NULL in case of memory
278 allocation failure. */
280 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
287 if (src1.nlimbs <= src2.nlimbs)
301 /* Now 0 <= len1 <= len2. */
304 /* src1 or src2 is zero. */
306 dest->limbs = (mp_limb_t *) malloc (1);
310 /* Here 1 <= len1 <= len2. */
316 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
319 for (k = len2; k > 0; )
321 for (i = 0; i < len1; i++)
323 mp_limb_t digit1 = p1[i];
324 mp_twolimb_t carry = 0;
325 for (j = 0; j < len2; j++)
327 mp_limb_t digit2 = p2[j];
328 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
330 dp[i + j] = (mp_limb_t) carry;
331 carry = carry >> GMP_LIMB_BITS;
333 dp[i + len2] = (mp_limb_t) carry;
336 while (dlen > 0 && dp[dlen - 1] == 0)
344 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
345 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
347 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
349 Return the allocated memory in case of success, NULL in case of memory
350 allocation failure. */
352 divide (mpn_t a, mpn_t b, mpn_t *q)
355 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
356 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
357 If m<n, then q:=0 and r:=a.
358 If m>=n=1, perform a single-precision division:
361 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
362 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
363 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
364 Normalise [q[m-1],...,q[0]], yields q.
365 If m>=n>1, perform a multiple-precision division:
366 We have a/b < beta^(m-n+1).
367 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
368 Shift a and b left by s bits, copying them. r:=a.
369 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
370 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
372 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
373 In case of overflow (q* >= beta) set q* := beta-1.
374 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
375 and c3 := b[n-2] * q*.
376 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
377 occurred. Furthermore 0 <= c3 < beta^2.
378 If there was overflow and
379 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
380 the next test can be skipped.}
381 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
382 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
384 Put r := r - b * q* * beta^j. In detail:
385 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
386 hence: u:=0, for i:=0 to n-1 do
388 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
389 u:=u div beta (+ 1, if carry in subtraction)
391 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
393 the carry u does not overflow.}
394 If a negative carry occurs, put q* := q* - 1
395 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
397 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
398 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
400 The room for q[j] can be allocated at the memory location of r[n+j].
401 Finally, round-to-even:
402 Shift r left by 1 bit.
403 If r > b or if r = b and q[0] is odd, q := q+1.
405 const mp_limb_t *a_ptr = a.limbs;
406 size_t a_len = a.nlimbs;
407 const mp_limb_t *b_ptr = b.limbs;
408 size_t b_len = b.nlimbs;
410 mp_limb_t *tmp_roomptr = NULL;
416 /* Allocate room for a_len+2 digits.
417 (Need a_len+1 digits for the real division and 1 more digit for the
418 final rounding of q.) */
419 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
424 while (a_len > 0 && a_ptr[a_len - 1] == 0)
431 /* Division by zero. */
433 if (b_ptr[b_len - 1] == 0)
439 /* Here m = a_len >= 0 and n = b_len > 0. */
443 /* m<n: trivial case. q=0, r := copy of a. */
446 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
447 q_ptr = roomptr + a_len;
452 /* n=1: single precision division.
453 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
457 mp_limb_t den = b_ptr[0];
458 mp_limb_t remainder = 0;
459 const mp_limb_t *sourceptr = a_ptr + a_len;
460 mp_limb_t *destptr = q_ptr + a_len;
462 for (count = a_len; count > 0; count--)
465 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
466 *--destptr = num / den;
467 remainder = num % den;
469 /* Normalise and store r. */
472 r_ptr[0] = remainder;
479 if (q_ptr[q_len - 1] == 0)
485 /* n>1: multiple precision division.
486 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
487 beta^(m-n-1) <= a/b < beta^(m-n+1). */
491 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
519 /* 0 <= s < GMP_LIMB_BITS.
520 Copy b, shifting it left by s bits. */
523 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
524 if (tmp_roomptr == NULL)
530 const mp_limb_t *sourceptr = b_ptr;
531 mp_limb_t *destptr = tmp_roomptr;
532 mp_twolimb_t accu = 0;
534 for (count = b_len; count > 0; count--)
536 accu += (mp_twolimb_t) *sourceptr++ << s;
537 *destptr++ = (mp_limb_t) accu;
538 accu = accu >> GMP_LIMB_BITS;
540 /* accu must be zero, since that was how s was determined. */
546 /* Copy a, shifting it left by s bits, yields r.
548 At the beginning: r = roomptr[0..a_len],
549 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
553 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
558 const mp_limb_t *sourceptr = a_ptr;
559 mp_limb_t *destptr = r_ptr;
560 mp_twolimb_t accu = 0;
562 for (count = a_len; count > 0; count--)
564 accu += (mp_twolimb_t) *sourceptr++ << s;
565 *destptr++ = (mp_limb_t) accu;
566 accu = accu >> GMP_LIMB_BITS;
568 *destptr++ = (mp_limb_t) accu;
570 q_ptr = roomptr + b_len;
571 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
573 size_t j = a_len - b_len; /* m-n */
574 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
575 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
576 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
577 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
578 /* Division loop, traversed m-n+1 times.
579 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
584 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
586 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
588 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
589 | r_ptr[j + b_len - 1];
590 q_star = num / b_msd;
595 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
596 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
597 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
598 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
599 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
601 If yes, jump directly to the subtraction loop.
602 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
603 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
604 if (r_ptr[j + b_len] > b_msd
605 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
606 /* r[j+n] >= b[n-1]+1 or
607 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
612 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
614 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
615 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
616 mp_twolimb_t c3 = /* b[n-2] * q* */
617 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
618 /* While c2 < c3, increase c2 and decrease c3.
619 Consider c3-c2. While it is > 0, decrease it by
620 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
621 this can happen only twice. */
624 q_star = q_star - 1; /* q* := q* - 1 */
625 if (c3 - c2 > b_msdd)
626 q_star = q_star - 1; /* q* := q* - 1 */
632 /* Subtract r := r - b * q* * beta^j. */
635 const mp_limb_t *sourceptr = b_ptr;
636 mp_limb_t *destptr = r_ptr + j;
637 mp_twolimb_t carry = 0;
639 for (count = b_len; count > 0; count--)
641 /* Here 0 <= carry <= q*. */
644 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
645 + (mp_limb_t) ~(*destptr);
646 /* Here 0 <= carry <= beta*q* + beta-1. */
647 *destptr++ = ~(mp_limb_t) carry;
648 carry = carry >> GMP_LIMB_BITS; /* <= q* */
650 cr = (mp_limb_t) carry;
652 /* Subtract cr from r_ptr[j + b_len], then forget about
654 if (cr > r_ptr[j + b_len])
656 /* Subtraction gave a carry. */
657 q_star = q_star - 1; /* q* := q* - 1 */
660 const mp_limb_t *sourceptr = b_ptr;
661 mp_limb_t *destptr = r_ptr + j;
664 for (count = b_len; count > 0; count--)
666 mp_limb_t source1 = *sourceptr++;
667 mp_limb_t source2 = *destptr;
668 *destptr++ = source1 + source2 + carry;
671 ? source1 >= (mp_limb_t) ~source2
672 : source1 > (mp_limb_t) ~source2);
675 /* Forget about the carry and about r[j+n]. */
678 /* q* is determined. Store it as q[j]. */
687 if (q_ptr[q_len - 1] == 0)
689 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
690 b is shifted left by s bits. */
691 /* Shift r right by s bits. */
694 mp_limb_t ptr = r_ptr + r_len;
695 mp_twolimb_t accu = 0;
697 for (count = r_len; count > 0; count--)
699 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
700 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
701 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
706 while (r_len > 0 && r_ptr[r_len - 1] == 0)
709 /* Compare r << 1 with b. */
717 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
718 | (i < r_len ? r_ptr[i] << 1 : 0);
719 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
729 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
734 for (i = 0; i < q_len; i++)
735 if (++(q_ptr[i]) != 0)
740 if (tmp_roomptr != NULL)
747 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
749 Destroys the contents of a.
750 Return the allocated memory - containing the decimal digits in low-to-high
751 order, terminated with a NUL character - in case of success, NULL in case
752 of memory allocation failure. */
754 convert_to_decimal (mpn_t a, size_t extra_zeroes)
756 mp_limb_t *a_ptr = a.limbs;
757 size_t a_len = a.nlimbs;
758 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
759 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
760 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
764 for (; extra_zeroes > 0; extra_zeroes--)
768 /* Divide a by 10^9, in-place. */
769 mp_limb_t remainder = 0;
770 mp_limb_t *ptr = a_ptr + a_len;
772 for (count = a_len; count > 0; count--)
775 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
776 *ptr = num / 1000000000;
777 remainder = num % 1000000000;
779 /* Store the remainder as 9 decimal digits. */
780 for (count = 9; count > 0; count--)
782 *d_ptr++ = '0' + (remainder % 10);
783 remainder = remainder / 10;
786 if (a_ptr[a_len - 1] == 0)
789 /* Remove leading zeroes. */
790 while (d_ptr > c_ptr && d_ptr[-1] == '0')
792 /* But keep at least one zero. */
795 /* Terminate the string. */
801 # if NEED_PRINTF_LONG_DOUBLE
803 /* Assuming x is finite and >= 0:
804 write x as x = 2^e * m, where m is a bignum.
805 Return the allocated memory in case of success, NULL in case of memory
806 allocation failure. */
808 decode_long_double (long double x, int *ep, mpn_t *mp)
815 /* Allocate memory for result. */
816 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
817 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
820 /* Split into exponential part and mantissa. */
821 y = frexpl (x, &exp);
822 if (!(y >= 0.0L && y < 1.0L))
824 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
825 latter is an integer. */
826 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
827 I'm not sure whether it's safe to cast a 'long double' value between
828 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
829 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
831 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
832 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
835 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
838 if (!(y >= 0.0L && y < 1.0L))
840 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
843 if (!(y >= 0.0L && y < 1.0L))
845 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
850 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
853 if (!(y >= 0.0L && y < 1.0L))
855 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
859 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
862 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
865 if (!(y >= 0.0L && y < 1.0L))
867 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
870 if (!(y >= 0.0L && y < 1.0L))
872 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
874 #if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
880 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
883 *ep = exp - LDBL_MANT_BIT;
889 # if NEED_PRINTF_DOUBLE
891 /* Assuming x is finite and >= 0:
892 write x as x = 2^e * m, where m is a bignum.
893 Return the allocated memory in case of success, NULL in case of memory
894 allocation failure. */
896 decode_double (double x, int *ep, mpn_t *mp)
903 /* Allocate memory for result. */
904 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
905 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
908 /* Split into exponential part and mantissa. */
910 if (!(y >= 0.0 && y < 1.0))
912 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
913 latter is an integer. */
914 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
915 I'm not sure whether it's safe to cast a 'double' value between
916 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
917 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
919 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
920 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
923 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
926 if (!(y >= 0.0 && y < 1.0))
928 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
931 if (!(y >= 0.0 && y < 1.0))
933 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
938 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
941 if (!(y >= 0.0 && y < 1.0))
943 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
947 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
950 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
953 if (!(y >= 0.0 && y < 1.0))
955 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
958 if (!(y >= 0.0 && y < 1.0))
960 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
965 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
968 *ep = exp - DBL_MANT_BIT;
974 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
975 Returns the decimal representation of round (x * 10^n).
976 Return the allocated memory - containing the decimal digits in low-to-high
977 order, terminated with a NUL character - in case of success, NULL in case
978 of memory allocation failure. */
980 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
988 unsigned int s_limbs;
997 /* x = 2^e * m, hence
998 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
999 = round (2^s * 5^n * m). */
1002 /* Factor out a common power of 10 if possible. */
1005 extra_zeroes = (s < n ? s : n);
1009 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1010 Before converting to decimal, we need to compute
1011 z = round (2^s * 5^n * m). */
1012 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1013 sign. 2.322 is slightly larger than log(5)/log(2). */
1014 abs_n = (n >= 0 ? n : -n);
1015 abs_s = (s >= 0 ? s : -s);
1016 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1017 + abs_s / GMP_LIMB_BITS + 1)
1018 * sizeof (mp_limb_t));
1019 if (pow5_ptr == NULL)
1024 /* Initialize with 1. */
1027 /* Multiply with 5^|n|. */
1030 static mp_limb_t const small_pow5[13 + 1] =
1032 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1033 48828125, 244140625, 1220703125
1036 for (n13 = 0; n13 <= abs_n; n13 += 13)
1038 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1040 mp_twolimb_t carry = 0;
1041 for (j = 0; j < pow5_len; j++)
1043 mp_limb_t digit2 = pow5_ptr[j];
1044 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1045 pow5_ptr[j] = (mp_limb_t) carry;
1046 carry = carry >> GMP_LIMB_BITS;
1049 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1052 s_limbs = abs_s / GMP_LIMB_BITS;
1053 s_bits = abs_s % GMP_LIMB_BITS;
1054 if (n >= 0 ? s >= 0 : s <= 0)
1056 /* Multiply with 2^|s|. */
1059 mp_limb_t *ptr = pow5_ptr;
1060 mp_twolimb_t accu = 0;
1062 for (count = pow5_len; count > 0; count--)
1064 accu += (mp_twolimb_t) *ptr << s_bits;
1065 *ptr++ = (mp_limb_t) accu;
1066 accu = accu >> GMP_LIMB_BITS;
1070 *ptr = (mp_limb_t) accu;
1077 for (count = pow5_len; count > 0;)
1080 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1082 for (count = s_limbs; count > 0;)
1085 pow5_ptr[count] = 0;
1087 pow5_len += s_limbs;
1089 pow5.limbs = pow5_ptr;
1090 pow5.nlimbs = pow5_len;
1093 /* Multiply m with pow5. No division needed. */
1094 z_memory = multiply (m, pow5, &z);
1098 /* Divide m by pow5 and round. */
1099 z_memory = divide (m, pow5, &z);
1104 pow5.limbs = pow5_ptr;
1105 pow5.nlimbs = pow5_len;
1109 Multiply m with pow5, then divide by 2^|s|. */
1113 tmp_memory = multiply (m, pow5, &numerator);
1114 if (tmp_memory == NULL)
1120 /* Construct 2^|s|. */
1122 mp_limb_t *ptr = pow5_ptr + pow5_len;
1124 for (i = 0; i < s_limbs; i++)
1126 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1127 denominator.limbs = ptr;
1128 denominator.nlimbs = s_limbs + 1;
1130 z_memory = divide (numerator, denominator, &z);
1136 Multiply m with 2^s, then divide by pow5. */
1139 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1140 * sizeof (mp_limb_t));
1141 if (num_ptr == NULL)
1148 mp_limb_t *destptr = num_ptr;
1151 for (i = 0; i < s_limbs; i++)
1156 const mp_limb_t *sourceptr = m.limbs;
1157 mp_twolimb_t accu = 0;
1159 for (count = m.nlimbs; count > 0; count--)
1161 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1162 *destptr++ = (mp_limb_t) accu;
1163 accu = accu >> GMP_LIMB_BITS;
1166 *destptr++ = (mp_limb_t) accu;
1170 const mp_limb_t *sourceptr = m.limbs;
1172 for (count = m.nlimbs; count > 0; count--)
1173 *destptr++ = *sourceptr++;
1175 numerator.limbs = num_ptr;
1176 numerator.nlimbs = destptr - num_ptr;
1178 z_memory = divide (numerator, pow5, &z);
1185 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1187 if (z_memory == NULL)
1189 digits = convert_to_decimal (z, extra_zeroes);
1194 # if NEED_PRINTF_LONG_DOUBLE
1196 /* Assuming x is finite and >= 0, and n is an integer:
1197 Returns the decimal representation of round (x * 10^n).
1198 Return the allocated memory - containing the decimal digits in low-to-high
1199 order, terminated with a NUL character - in case of success, NULL in case
1200 of memory allocation failure. */
1202 scale10_round_decimal_long_double (long double x, int n)
1206 void *memory = decode_long_double (x, &e, &m);
1207 return scale10_round_decimal_decoded (e, m, memory, n);
1212 # if NEED_PRINTF_DOUBLE
1214 /* Assuming x is finite and >= 0, and n is an integer:
1215 Returns the decimal representation of round (x * 10^n).
1216 Return the allocated memory - containing the decimal digits in low-to-high
1217 order, terminated with a NUL character - in case of success, NULL in case
1218 of memory allocation failure. */
1220 scale10_round_decimal_double (double x, int n)
1224 void *memory = decode_double (x, &e, &m);
1225 return scale10_round_decimal_decoded (e, m, memory, n);
1230 # if NEED_PRINTF_LONG_DOUBLE
1232 /* Assuming x is finite and > 0:
1233 Return an approximation for n with 10^n <= x < 10^(n+1).
1234 The approximation is usually the right n, but may be off by 1 sometimes. */
1236 floorlog10l (long double x)
1243 /* Split into exponential part and mantissa. */
1244 y = frexpl (x, &exp);
1245 if (!(y >= 0.0L && y < 1.0L))
1251 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1253 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1254 exp -= GMP_LIMB_BITS;
1256 if (y < (1.0L / (1 << 16)))
1258 y *= 1.0L * (1 << 16);
1261 if (y < (1.0L / (1 << 8)))
1263 y *= 1.0L * (1 << 8);
1266 if (y < (1.0L / (1 << 4)))
1268 y *= 1.0L * (1 << 4);
1271 if (y < (1.0L / (1 << 2)))
1273 y *= 1.0L * (1 << 2);
1276 if (y < (1.0L / (1 << 1)))
1278 y *= 1.0L * (1 << 1);
1282 if (!(y >= 0.5L && y < 1.0L))
1284 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1287 if (z < 0.70710678118654752444)
1289 z *= 1.4142135623730950488;
1292 if (z < 0.8408964152537145431)
1294 z *= 1.1892071150027210667;
1297 if (z < 0.91700404320467123175)
1299 z *= 1.0905077326652576592;
1302 if (z < 0.9576032806985736469)
1304 z *= 1.0442737824274138403;
1307 /* Now 0.95 <= z <= 1.01. */
1309 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1310 Four terms are enough to get an approximation with error < 10^-7. */
1311 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1312 /* Finally multiply with log(2)/log(10), yields an approximation for
1314 l *= 0.30102999566398119523;
1315 /* Round down to the next integer. */
1316 return (int) l + (l < 0 ? -1 : 0);
1321 # if NEED_PRINTF_DOUBLE
1323 /* Assuming x is finite and > 0:
1324 Return an approximation for n with 10^n <= x < 10^(n+1).
1325 The approximation is usually the right n, but may be off by 1 sometimes. */
1327 floorlog10 (double x)
1334 /* Split into exponential part and mantissa. */
1335 y = frexp (x, &exp);
1336 if (!(y >= 0.0 && y < 1.0))
1342 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1344 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1345 exp -= GMP_LIMB_BITS;
1347 if (y < (1.0 / (1 << 16)))
1349 y *= 1.0 * (1 << 16);
1352 if (y < (1.0 / (1 << 8)))
1354 y *= 1.0 * (1 << 8);
1357 if (y < (1.0 / (1 << 4)))
1359 y *= 1.0 * (1 << 4);
1362 if (y < (1.0 / (1 << 2)))
1364 y *= 1.0 * (1 << 2);
1367 if (y < (1.0 / (1 << 1)))
1369 y *= 1.0 * (1 << 1);
1373 if (!(y >= 0.5 && y < 1.0))
1375 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1378 if (z < 0.70710678118654752444)
1380 z *= 1.4142135623730950488;
1383 if (z < 0.8408964152537145431)
1385 z *= 1.1892071150027210667;
1388 if (z < 0.91700404320467123175)
1390 z *= 1.0905077326652576592;
1393 if (z < 0.9576032806985736469)
1395 z *= 1.0442737824274138403;
1398 /* Now 0.95 <= z <= 1.01. */
1400 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1401 Four terms are enough to get an approximation with error < 10^-7. */
1402 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1403 /* Finally multiply with log(2)/log(10), yields an approximation for
1405 l *= 0.30102999566398119523;
1406 /* Round down to the next integer. */
1407 return (int) l + (l < 0 ? -1 : 0);
1415 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1416 const FCHAR_T *format, va_list args)
1421 if (PRINTF_PARSE (format, &d, &a) < 0)
1422 /* errno is already set. */
1430 if (PRINTF_FETCHARGS (args, &a) < 0)
1438 size_t buf_neededlength;
1440 TCHAR_T *buf_malloced;
1444 /* Output string accumulator. */
1449 /* Allocate a small buffer that will hold a directive passed to
1450 sprintf or snprintf. */
1452 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1454 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1456 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1457 buf_malloced = NULL;
1462 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1463 if (size_overflow_p (buf_memsize))
1464 goto out_of_memory_1;
1465 buf = (TCHAR_T *) malloc (buf_memsize);
1467 goto out_of_memory_1;
1471 if (resultbuf != NULL)
1474 allocated = *lengthp;
1483 result is either == resultbuf or == NULL or malloc-allocated.
1484 If length > 0, then result != NULL. */
1486 /* Ensures that allocated >= needed. Aborts through a jump to
1487 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1488 #define ENSURE_ALLOCATION(needed) \
1489 if ((needed) > allocated) \
1491 size_t memory_size; \
1494 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1495 if ((needed) > allocated) \
1496 allocated = (needed); \
1497 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1498 if (size_overflow_p (memory_size)) \
1499 goto out_of_memory; \
1500 if (result == resultbuf || result == NULL) \
1501 memory = (DCHAR_T *) malloc (memory_size); \
1503 memory = (DCHAR_T *) realloc (result, memory_size); \
1504 if (memory == NULL) \
1505 goto out_of_memory; \
1506 if (result == resultbuf && length > 0) \
1507 DCHAR_CPY (memory, result, length); \
1511 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1513 if (cp != dp->dir_start)
1515 size_t n = dp->dir_start - cp;
1516 size_t augmented_length = xsum (length, n);
1518 ENSURE_ALLOCATION (augmented_length);
1519 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1520 need that the format string contains only ASCII characters
1521 if FCHAR_T and DCHAR_T are not the same type. */
1522 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1524 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1525 length = augmented_length;
1530 result[length++] = (unsigned char) *cp++;
1537 /* Execute a single directive. */
1538 if (dp->conversion == '%')
1540 size_t augmented_length;
1542 if (!(dp->arg_index == ARG_NONE))
1544 augmented_length = xsum (length, 1);
1545 ENSURE_ALLOCATION (augmented_length);
1546 result[length] = '%';
1547 length = augmented_length;
1551 if (!(dp->arg_index != ARG_NONE))
1554 if (dp->conversion == 'n')
1556 switch (a.arg[dp->arg_index].type)
1558 case TYPE_COUNT_SCHAR_POINTER:
1559 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1561 case TYPE_COUNT_SHORT_POINTER:
1562 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1564 case TYPE_COUNT_INT_POINTER:
1565 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1567 case TYPE_COUNT_LONGINT_POINTER:
1568 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1570 #if HAVE_LONG_LONG_INT
1571 case TYPE_COUNT_LONGLONGINT_POINTER:
1572 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1580 /* The unistdio extensions. */
1581 else if (dp->conversion == 'U')
1583 arg_type type = a.arg[dp->arg_index].type;
1584 int flags = dp->flags;
1592 if (dp->width_start != dp->width_end)
1594 if (dp->width_arg_index != ARG_NONE)
1598 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1600 arg = a.arg[dp->width_arg_index].a.a_int;
1603 /* "A negative field width is taken as a '-' flag
1604 followed by a positive field width." */
1606 width = (unsigned int) (-arg);
1613 const FCHAR_T *digitp = dp->width_start;
1616 width = xsum (xtimes (width, 10), *digitp++ - '0');
1617 while (digitp != dp->width_end);
1624 if (dp->precision_start != dp->precision_end)
1626 if (dp->precision_arg_index != ARG_NONE)
1630 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1632 arg = a.arg[dp->precision_arg_index].a.a_int;
1633 /* "A negative precision is taken as if the precision
1643 const FCHAR_T *digitp = dp->precision_start + 1;
1646 while (digitp != dp->precision_end)
1647 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1654 case TYPE_U8_STRING:
1656 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1657 const uint8_t *arg_end;
1662 /* Use only PRECISION characters, from the left. */
1665 for (; precision > 0; precision--)
1667 int count = u8_strmblen (arg_end);
1672 if (!(result == resultbuf || result == NULL))
1674 if (buf_malloced != NULL)
1675 free (buf_malloced);
1686 /* Use the entire string, and count the number of
1692 int count = u8_strmblen (arg_end);
1697 if (!(result == resultbuf || result == NULL))
1699 if (buf_malloced != NULL)
1700 free (buf_malloced);
1711 /* Use the entire string. */
1712 arg_end = arg + u8_strlen (arg);
1713 /* The number of characters doesn't matter. */
1717 if (has_width && width > characters
1718 && !(dp->flags & FLAG_LEFT))
1720 size_t n = width - characters;
1721 ENSURE_ALLOCATION (xsum (length, n));
1722 DCHAR_SET (result + length, ' ', n);
1726 # if DCHAR_IS_UINT8_T
1728 size_t n = arg_end - arg;
1729 ENSURE_ALLOCATION (xsum (length, n));
1730 DCHAR_CPY (result + length, arg, n);
1735 DCHAR_T *converted = result + length;
1736 size_t converted_len = allocated - length;
1738 /* Convert from UTF-8 to locale encoding. */
1739 if (u8_conv_to_encoding (locale_charset (),
1740 iconveh_question_mark,
1741 arg, arg_end - arg, NULL,
1742 &converted, &converted_len)
1745 /* Convert from UTF-8 to UTF-16/UTF-32. */
1747 U8_TO_DCHAR (arg, arg_end - arg,
1748 converted, &converted_len);
1749 if (converted == NULL)
1752 int saved_errno = errno;
1753 if (!(result == resultbuf || result == NULL))
1755 if (buf_malloced != NULL)
1756 free (buf_malloced);
1758 errno = saved_errno;
1761 if (converted != result + length)
1763 ENSURE_ALLOCATION (xsum (length, converted_len));
1764 DCHAR_CPY (result + length, converted, converted_len);
1767 length += converted_len;
1771 if (has_width && width > characters
1772 && (dp->flags & FLAG_LEFT))
1774 size_t n = width - characters;
1775 ENSURE_ALLOCATION (xsum (length, n));
1776 DCHAR_SET (result + length, ' ', n);
1782 case TYPE_U16_STRING:
1784 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1785 const uint16_t *arg_end;
1790 /* Use only PRECISION characters, from the left. */
1793 for (; precision > 0; precision--)
1795 int count = u16_strmblen (arg_end);
1800 if (!(result == resultbuf || result == NULL))
1802 if (buf_malloced != NULL)
1803 free (buf_malloced);
1814 /* Use the entire string, and count the number of
1820 int count = u16_strmblen (arg_end);
1825 if (!(result == resultbuf || result == NULL))
1827 if (buf_malloced != NULL)
1828 free (buf_malloced);
1839 /* Use the entire string. */
1840 arg_end = arg + u16_strlen (arg);
1841 /* The number of characters doesn't matter. */
1845 if (has_width && width > characters
1846 && !(dp->flags & FLAG_LEFT))
1848 size_t n = width - characters;
1849 ENSURE_ALLOCATION (xsum (length, n));
1850 DCHAR_SET (result + length, ' ', n);
1854 # if DCHAR_IS_UINT16_T
1856 size_t n = arg_end - arg;
1857 ENSURE_ALLOCATION (xsum (length, n));
1858 DCHAR_CPY (result + length, arg, n);
1863 DCHAR_T *converted = result + length;
1864 size_t converted_len = allocated - length;
1866 /* Convert from UTF-16 to locale encoding. */
1867 if (u16_conv_to_encoding (locale_charset (),
1868 iconveh_question_mark,
1869 arg, arg_end - arg, NULL,
1870 &converted, &converted_len)
1873 /* Convert from UTF-16 to UTF-8/UTF-32. */
1875 U16_TO_DCHAR (arg, arg_end - arg,
1876 converted, &converted_len);
1877 if (converted == NULL)
1880 int saved_errno = errno;
1881 if (!(result == resultbuf || result == NULL))
1883 if (buf_malloced != NULL)
1884 free (buf_malloced);
1886 errno = saved_errno;
1889 if (converted != result + length)
1891 ENSURE_ALLOCATION (xsum (length, converted_len));
1892 DCHAR_CPY (result + length, converted, converted_len);
1895 length += converted_len;
1899 if (has_width && width > characters
1900 && (dp->flags & FLAG_LEFT))
1902 size_t n = width - characters;
1903 ENSURE_ALLOCATION (xsum (length, n));
1904 DCHAR_SET (result + length, ' ', n);
1910 case TYPE_U32_STRING:
1912 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1913 const uint32_t *arg_end;
1918 /* Use only PRECISION characters, from the left. */
1921 for (; precision > 0; precision--)
1923 int count = u32_strmblen (arg_end);
1928 if (!(result == resultbuf || result == NULL))
1930 if (buf_malloced != NULL)
1931 free (buf_malloced);
1942 /* Use the entire string, and count the number of
1948 int count = u32_strmblen (arg_end);
1953 if (!(result == resultbuf || result == NULL))
1955 if (buf_malloced != NULL)
1956 free (buf_malloced);
1967 /* Use the entire string. */
1968 arg_end = arg + u32_strlen (arg);
1969 /* The number of characters doesn't matter. */
1973 if (has_width && width > characters
1974 && !(dp->flags & FLAG_LEFT))
1976 size_t n = width - characters;
1977 ENSURE_ALLOCATION (xsum (length, n));
1978 DCHAR_SET (result + length, ' ', n);
1982 # if DCHAR_IS_UINT32_T
1984 size_t n = arg_end - arg;
1985 ENSURE_ALLOCATION (xsum (length, n));
1986 DCHAR_CPY (result + length, arg, n);
1991 DCHAR_T *converted = result + length;
1992 size_t converted_len = allocated - length;
1994 /* Convert from UTF-32 to locale encoding. */
1995 if (u32_conv_to_encoding (locale_charset (),
1996 iconveh_question_mark,
1997 arg, arg_end - arg, NULL,
1998 &converted, &converted_len)
2001 /* Convert from UTF-32 to UTF-8/UTF-16. */
2003 U32_TO_DCHAR (arg, arg_end - arg,
2004 converted, &converted_len);
2005 if (converted == NULL)
2008 int saved_errno = errno;
2009 if (!(result == resultbuf || result == NULL))
2011 if (buf_malloced != NULL)
2012 free (buf_malloced);
2014 errno = saved_errno;
2017 if (converted != result + length)
2019 ENSURE_ALLOCATION (xsum (length, converted_len));
2020 DCHAR_CPY (result + length, converted, converted_len);
2023 length += converted_len;
2027 if (has_width && width > characters
2028 && (dp->flags & FLAG_LEFT))
2030 size_t n = width - characters;
2031 ENSURE_ALLOCATION (xsum (length, n));
2032 DCHAR_SET (result + length, ' ', n);
2043 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2044 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2045 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2047 # if NEED_PRINTF_DOUBLE
2048 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2050 # if NEED_PRINTF_LONG_DOUBLE
2051 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2057 arg_type type = a.arg[dp->arg_index].type;
2058 int flags = dp->flags;
2064 DCHAR_T tmpbuf[700];
2071 if (dp->width_start != dp->width_end)
2073 if (dp->width_arg_index != ARG_NONE)
2077 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2079 arg = a.arg[dp->width_arg_index].a.a_int;
2082 /* "A negative field width is taken as a '-' flag
2083 followed by a positive field width." */
2085 width = (unsigned int) (-arg);
2092 const FCHAR_T *digitp = dp->width_start;
2095 width = xsum (xtimes (width, 10), *digitp++ - '0');
2096 while (digitp != dp->width_end);
2103 if (dp->precision_start != dp->precision_end)
2105 if (dp->precision_arg_index != ARG_NONE)
2109 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2111 arg = a.arg[dp->precision_arg_index].a.a_int;
2112 /* "A negative precision is taken as if the precision
2122 const FCHAR_T *digitp = dp->precision_start + 1;
2125 while (digitp != dp->precision_end)
2126 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2131 /* Allocate a temporary buffer of sufficient size. */
2132 if (type == TYPE_LONGDOUBLE)
2134 (unsigned int) ((LDBL_DIG + 1)
2135 * 0.831 /* decimal -> hexadecimal */
2137 + 1; /* turn floor into ceil */
2140 (unsigned int) ((DBL_DIG + 1)
2141 * 0.831 /* decimal -> hexadecimal */
2143 + 1; /* turn floor into ceil */
2144 if (tmp_length < precision)
2145 tmp_length = precision;
2146 /* Account for sign, decimal point etc. */
2147 tmp_length = xsum (tmp_length, 12);
2149 if (tmp_length < width)
2152 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2154 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2158 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2160 if (size_overflow_p (tmp_memsize))
2161 /* Overflow, would lead to out of memory. */
2163 tmp = (DCHAR_T *) malloc (tmp_memsize);
2165 /* Out of memory. */
2171 if (type == TYPE_LONGDOUBLE)
2173 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2174 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2178 if (dp->conversion == 'A')
2180 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2184 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2190 DECL_LONG_DOUBLE_ROUNDING
2192 BEGIN_LONG_DOUBLE_ROUNDING ();
2194 if (signbit (arg)) /* arg < 0.0L or negative zero */
2202 else if (flags & FLAG_SHOWSIGN)
2204 else if (flags & FLAG_SPACE)
2207 if (arg > 0.0L && arg + arg == arg)
2209 if (dp->conversion == 'A')
2211 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2215 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2221 long double mantissa;
2224 mantissa = printf_frexpl (arg, &exponent);
2232 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2234 /* Round the mantissa. */
2235 long double tail = mantissa;
2238 for (q = precision; ; q--)
2240 int digit = (int) tail;
2244 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2253 for (q = precision; q > 0; q--)
2259 *p++ = dp->conversion - 'A' + 'X';
2264 digit = (int) mantissa;
2267 if ((flags & FLAG_ALT)
2268 || mantissa > 0.0L || precision > 0)
2270 *p++ = decimal_point_char ();
2271 /* This loop terminates because we assume
2272 that FLT_RADIX is a power of 2. */
2273 while (mantissa > 0.0L)
2276 digit = (int) mantissa;
2281 : dp->conversion - 10);
2285 while (precision > 0)
2292 *p++ = dp->conversion - 'A' + 'P';
2293 # if WIDE_CHAR_VERSION
2295 static const wchar_t decimal_format[] =
2296 { '%', '+', 'd', '\0' };
2297 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2302 if (sizeof (DCHAR_T) == 1)
2304 sprintf ((char *) p, "%+d", exponent);
2312 sprintf (expbuf, "%+d", exponent);
2313 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2319 END_LONG_DOUBLE_ROUNDING ();
2327 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2328 double arg = a.arg[dp->arg_index].a.a_double;
2332 if (dp->conversion == 'A')
2334 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2338 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2345 if (signbit (arg)) /* arg < 0.0 or negative zero */
2353 else if (flags & FLAG_SHOWSIGN)
2355 else if (flags & FLAG_SPACE)
2358 if (arg > 0.0 && arg + arg == arg)
2360 if (dp->conversion == 'A')
2362 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2366 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2375 mantissa = printf_frexp (arg, &exponent);
2383 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2385 /* Round the mantissa. */
2386 double tail = mantissa;
2389 for (q = precision; ; q--)
2391 int digit = (int) tail;
2395 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2404 for (q = precision; q > 0; q--)
2410 *p++ = dp->conversion - 'A' + 'X';
2415 digit = (int) mantissa;
2418 if ((flags & FLAG_ALT)
2419 || mantissa > 0.0 || precision > 0)
2421 *p++ = decimal_point_char ();
2422 /* This loop terminates because we assume
2423 that FLT_RADIX is a power of 2. */
2424 while (mantissa > 0.0)
2427 digit = (int) mantissa;
2432 : dp->conversion - 10);
2436 while (precision > 0)
2443 *p++ = dp->conversion - 'A' + 'P';
2444 # if WIDE_CHAR_VERSION
2446 static const wchar_t decimal_format[] =
2447 { '%', '+', 'd', '\0' };
2448 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2453 if (sizeof (DCHAR_T) == 1)
2455 sprintf ((char *) p, "%+d", exponent);
2463 sprintf (expbuf, "%+d", exponent);
2464 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2474 /* The generated string now extends from tmp to p, with the
2475 zero padding insertion point being at pad_ptr. */
2476 if (has_width && p - tmp < width)
2478 size_t pad = width - (p - tmp);
2479 DCHAR_T *end = p + pad;
2481 if (flags & FLAG_LEFT)
2483 /* Pad with spaces on the right. */
2484 for (; pad > 0; pad--)
2487 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2489 /* Pad with zeroes. */
2494 for (; pad > 0; pad--)
2499 /* Pad with spaces on the left. */
2504 for (; pad > 0; pad--)
2512 size_t count = p - tmp;
2514 if (count >= tmp_length)
2515 /* tmp_length was incorrectly calculated - fix the
2519 /* Make room for the result. */
2520 if (count >= allocated - length)
2522 size_t n = xsum (length, count);
2524 ENSURE_ALLOCATION (n);
2527 /* Append the result. */
2528 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2535 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2536 else if ((dp->conversion == 'f' || dp->conversion == 'F'
2537 || dp->conversion == 'e' || dp->conversion == 'E'
2538 || dp->conversion == 'g' || dp->conversion == 'G'
2539 || dp->conversion == 'a' || dp->conversion == 'A')
2541 # if NEED_PRINTF_DOUBLE
2542 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2543 # elif NEED_PRINTF_INFINITE_DOUBLE
2544 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2545 /* The systems (mingw) which produce wrong output
2546 for Inf, -Inf, and NaN also do so for -0.0.
2547 Therefore we treat this case here as well. */
2548 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2550 # if NEED_PRINTF_LONG_DOUBLE
2551 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2552 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2553 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2554 /* Some systems produce wrong output for Inf,
2556 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
2560 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2561 arg_type type = a.arg[dp->arg_index].type;
2563 int flags = dp->flags;
2569 DCHAR_T tmpbuf[700];
2576 if (dp->width_start != dp->width_end)
2578 if (dp->width_arg_index != ARG_NONE)
2582 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2584 arg = a.arg[dp->width_arg_index].a.a_int;
2587 /* "A negative field width is taken as a '-' flag
2588 followed by a positive field width." */
2590 width = (unsigned int) (-arg);
2597 const FCHAR_T *digitp = dp->width_start;
2600 width = xsum (xtimes (width, 10), *digitp++ - '0');
2601 while (digitp != dp->width_end);
2608 if (dp->precision_start != dp->precision_end)
2610 if (dp->precision_arg_index != ARG_NONE)
2614 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2616 arg = a.arg[dp->precision_arg_index].a.a_int;
2617 /* "A negative precision is taken as if the precision
2627 const FCHAR_T *digitp = dp->precision_start + 1;
2630 while (digitp != dp->precision_end)
2631 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2636 /* POSIX specifies the default precision to be 6 for %f, %F,
2637 %e, %E, but not for %g, %G. Implementations appear to use
2638 the same default precision also for %g, %G. */
2642 /* Allocate a temporary buffer of sufficient size. */
2643 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2644 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
2645 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2646 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2647 # elif NEED_PRINTF_LONG_DOUBLE
2648 tmp_length = LDBL_DIG + 1;
2649 # elif NEED_PRINTF_DOUBLE
2650 tmp_length = DBL_DIG + 1;
2654 if (tmp_length < precision)
2655 tmp_length = precision;
2656 # if NEED_PRINTF_LONG_DOUBLE
2657 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2658 if (type == TYPE_LONGDOUBLE)
2660 if (dp->conversion == 'f' || dp->conversion == 'F')
2662 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2663 if (!(isnanl (arg) || arg + arg == arg))
2665 /* arg is finite and nonzero. */
2666 int exponent = floorlog10l (arg < 0 ? -arg : arg);
2667 if (exponent >= 0 && tmp_length < exponent + precision)
2668 tmp_length = exponent + precision;
2672 # if NEED_PRINTF_DOUBLE
2673 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2674 if (type == TYPE_DOUBLE)
2676 if (dp->conversion == 'f' || dp->conversion == 'F')
2678 double arg = a.arg[dp->arg_index].a.a_double;
2679 if (!(isnand (arg) || arg + arg == arg))
2681 /* arg is finite and nonzero. */
2682 int exponent = floorlog10 (arg < 0 ? -arg : arg);
2683 if (exponent >= 0 && tmp_length < exponent + precision)
2684 tmp_length = exponent + precision;
2688 /* Account for sign, decimal point etc. */
2689 tmp_length = xsum (tmp_length, 12);
2691 if (tmp_length < width)
2694 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2696 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2700 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2702 if (size_overflow_p (tmp_memsize))
2703 /* Overflow, would lead to out of memory. */
2705 tmp = (DCHAR_T *) malloc (tmp_memsize);
2707 /* Out of memory. */
2714 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2715 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2716 if (type == TYPE_LONGDOUBLE)
2719 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2723 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2725 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2729 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2735 DECL_LONG_DOUBLE_ROUNDING
2737 BEGIN_LONG_DOUBLE_ROUNDING ();
2739 if (signbit (arg)) /* arg < 0.0L or negative zero */
2747 else if (flags & FLAG_SHOWSIGN)
2749 else if (flags & FLAG_SPACE)
2752 if (arg > 0.0L && arg + arg == arg)
2754 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2756 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2760 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2765 # if NEED_PRINTF_LONG_DOUBLE
2768 if (dp->conversion == 'f' || dp->conversion == 'F')
2774 scale10_round_decimal_long_double (arg, precision);
2777 END_LONG_DOUBLE_ROUNDING ();
2780 ndigits = strlen (digits);
2782 if (ndigits > precision)
2786 *p++ = digits[ndigits];
2788 while (ndigits > precision);
2791 /* Here ndigits <= precision. */
2792 if ((flags & FLAG_ALT) || precision > 0)
2794 *p++ = decimal_point_char ();
2795 for (; precision > ndigits; precision--)
2800 *p++ = digits[ndigits];
2806 else if (dp->conversion == 'e' || dp->conversion == 'E')
2814 if ((flags & FLAG_ALT) || precision > 0)
2816 *p++ = decimal_point_char ();
2817 for (; precision > 0; precision--)
2828 exponent = floorlog10l (arg);
2833 scale10_round_decimal_long_double (arg,
2834 (int)precision - exponent);
2837 END_LONG_DOUBLE_ROUNDING ();
2840 ndigits = strlen (digits);
2842 if (ndigits == precision + 1)
2844 if (ndigits < precision
2845 || ndigits > precision + 2)
2846 /* The exponent was not guessed
2847 precisely enough. */
2850 /* None of two values of exponent is
2851 the right one. Prevent an endless
2855 if (ndigits == precision)
2862 /* Here ndigits = precision+1. */
2863 *p++ = digits[--ndigits];
2864 if ((flags & FLAG_ALT) || precision > 0)
2866 *p++ = decimal_point_char ();
2870 *p++ = digits[ndigits];
2877 *p++ = dp->conversion; /* 'e' or 'E' */
2878 # if WIDE_CHAR_VERSION
2880 static const wchar_t decimal_format[] =
2881 { '%', '+', '.', '2', 'd', '\0' };
2882 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2887 if (sizeof (DCHAR_T) == 1)
2889 sprintf ((char *) p, "%+.2d", exponent);
2897 sprintf (expbuf, "%+.2d", exponent);
2898 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2903 else if (dp->conversion == 'g' || dp->conversion == 'G')
2907 /* precision >= 1. */
2910 /* The exponent is 0, >= -4, < precision.
2911 Use fixed-point notation. */
2913 size_t ndigits = precision;
2914 /* Number of trailing zeroes that have to be
2917 (flags & FLAG_ALT ? 0 : precision - 1);
2921 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2923 *p++ = decimal_point_char ();
2924 while (ndigits > nzeroes)
2940 exponent = floorlog10l (arg);
2945 scale10_round_decimal_long_double (arg,
2946 (int)(precision - 1) - exponent);
2949 END_LONG_DOUBLE_ROUNDING ();
2952 ndigits = strlen (digits);
2954 if (ndigits == precision)
2956 if (ndigits < precision - 1
2957 || ndigits > precision + 1)
2958 /* The exponent was not guessed
2959 precisely enough. */
2962 /* None of two values of exponent is
2963 the right one. Prevent an endless
2967 if (ndigits < precision)
2973 /* Here ndigits = precision. */
2975 /* Determine the number of trailing zeroes
2976 that have to be dropped. */
2978 if ((flags & FLAG_ALT) == 0)
2979 while (nzeroes < ndigits
2980 && digits[nzeroes] == '0')
2983 /* The exponent is now determined. */
2985 && exponent < (long)precision)
2987 /* Fixed-point notation:
2988 max(exponent,0)+1 digits, then the
2989 decimal point, then the remaining
2990 digits without trailing zeroes. */
2993 size_t count = exponent + 1;
2994 /* Note: count <= precision = ndigits. */
2995 for (; count > 0; count--)
2996 *p++ = digits[--ndigits];
2997 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2999 *p++ = decimal_point_char ();
3000 while (ndigits > nzeroes)
3003 *p++ = digits[ndigits];
3009 size_t count = -exponent - 1;
3011 *p++ = decimal_point_char ();
3012 for (; count > 0; count--)
3014 while (ndigits > nzeroes)
3017 *p++ = digits[ndigits];
3023 /* Exponential notation. */
3024 *p++ = digits[--ndigits];
3025 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3027 *p++ = decimal_point_char ();
3028 while (ndigits > nzeroes)
3031 *p++ = digits[ndigits];
3034 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3035 # if WIDE_CHAR_VERSION
3037 static const wchar_t decimal_format[] =
3038 { '%', '+', '.', '2', 'd', '\0' };
3039 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3044 if (sizeof (DCHAR_T) == 1)
3046 sprintf ((char *) p, "%+.2d", exponent);
3054 sprintf (expbuf, "%+.2d", exponent);
3055 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3067 /* arg is finite. */
3072 END_LONG_DOUBLE_ROUNDING ();
3075 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3079 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3081 double arg = a.arg[dp->arg_index].a.a_double;
3085 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3087 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3091 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3098 if (signbit (arg)) /* arg < 0.0 or negative zero */
3106 else if (flags & FLAG_SHOWSIGN)
3108 else if (flags & FLAG_SPACE)
3111 if (arg > 0.0 && arg + arg == arg)
3113 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3115 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3119 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3124 # if NEED_PRINTF_DOUBLE
3127 if (dp->conversion == 'f' || dp->conversion == 'F')
3133 scale10_round_decimal_double (arg, precision);
3136 ndigits = strlen (digits);
3138 if (ndigits > precision)
3142 *p++ = digits[ndigits];
3144 while (ndigits > precision);
3147 /* Here ndigits <= precision. */
3148 if ((flags & FLAG_ALT) || precision > 0)
3150 *p++ = decimal_point_char ();
3151 for (; precision > ndigits; precision--)
3156 *p++ = digits[ndigits];
3162 else if (dp->conversion == 'e' || dp->conversion == 'E')
3170 if ((flags & FLAG_ALT) || precision > 0)
3172 *p++ = decimal_point_char ();
3173 for (; precision > 0; precision--)
3184 exponent = floorlog10 (arg);
3189 scale10_round_decimal_double (arg,
3190 (int)precision - exponent);
3193 ndigits = strlen (digits);
3195 if (ndigits == precision + 1)
3197 if (ndigits < precision
3198 || ndigits > precision + 2)
3199 /* The exponent was not guessed
3200 precisely enough. */
3203 /* None of two values of exponent is
3204 the right one. Prevent an endless
3208 if (ndigits == precision)
3215 /* Here ndigits = precision+1. */
3216 *p++ = digits[--ndigits];
3217 if ((flags & FLAG_ALT) || precision > 0)
3219 *p++ = decimal_point_char ();
3223 *p++ = digits[ndigits];
3230 *p++ = dp->conversion; /* 'e' or 'E' */
3231 # if WIDE_CHAR_VERSION
3233 static const wchar_t decimal_format[] =
3234 /* Produce the same number of exponent digits
3235 as the native printf implementation. */
3236 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3237 { '%', '+', '.', '3', 'd', '\0' };
3239 { '%', '+', '.', '2', 'd', '\0' };
3241 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3247 static const char decimal_format[] =
3248 /* Produce the same number of exponent digits
3249 as the native printf implementation. */
3250 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3255 if (sizeof (DCHAR_T) == 1)
3257 sprintf ((char *) p, decimal_format, exponent);
3265 sprintf (expbuf, decimal_format, exponent);
3266 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3272 else if (dp->conversion == 'g' || dp->conversion == 'G')
3276 /* precision >= 1. */
3279 /* The exponent is 0, >= -4, < precision.
3280 Use fixed-point notation. */
3282 size_t ndigits = precision;
3283 /* Number of trailing zeroes that have to be
3286 (flags & FLAG_ALT ? 0 : precision - 1);
3290 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3292 *p++ = decimal_point_char ();
3293 while (ndigits > nzeroes)
3309 exponent = floorlog10 (arg);
3314 scale10_round_decimal_double (arg,
3315 (int)(precision - 1) - exponent);
3318 ndigits = strlen (digits);
3320 if (ndigits == precision)
3322 if (ndigits < precision - 1
3323 || ndigits > precision + 1)
3324 /* The exponent was not guessed
3325 precisely enough. */
3328 /* None of two values of exponent is
3329 the right one. Prevent an endless
3333 if (ndigits < precision)
3339 /* Here ndigits = precision. */
3341 /* Determine the number of trailing zeroes
3342 that have to be dropped. */
3344 if ((flags & FLAG_ALT) == 0)
3345 while (nzeroes < ndigits
3346 && digits[nzeroes] == '0')
3349 /* The exponent is now determined. */
3351 && exponent < (long)precision)
3353 /* Fixed-point notation:
3354 max(exponent,0)+1 digits, then the
3355 decimal point, then the remaining
3356 digits without trailing zeroes. */
3359 size_t count = exponent + 1;
3360 /* Note: count <= precision = ndigits. */
3361 for (; count > 0; count--)
3362 *p++ = digits[--ndigits];
3363 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3365 *p++ = decimal_point_char ();
3366 while (ndigits > nzeroes)
3369 *p++ = digits[ndigits];
3375 size_t count = -exponent - 1;
3377 *p++ = decimal_point_char ();
3378 for (; count > 0; count--)
3380 while (ndigits > nzeroes)
3383 *p++ = digits[ndigits];
3389 /* Exponential notation. */
3390 *p++ = digits[--ndigits];
3391 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3393 *p++ = decimal_point_char ();
3394 while (ndigits > nzeroes)
3397 *p++ = digits[ndigits];
3400 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3401 # if WIDE_CHAR_VERSION
3403 static const wchar_t decimal_format[] =
3404 /* Produce the same number of exponent digits
3405 as the native printf implementation. */
3406 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3407 { '%', '+', '.', '3', 'd', '\0' };
3409 { '%', '+', '.', '2', 'd', '\0' };
3411 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3417 static const char decimal_format[] =
3418 /* Produce the same number of exponent digits
3419 as the native printf implementation. */
3420 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3425 if (sizeof (DCHAR_T) == 1)
3427 sprintf ((char *) p, decimal_format, exponent);
3435 sprintf (expbuf, decimal_format, exponent);
3436 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3449 /* arg is finite. */
3455 if (dp->conversion == 'f' || dp->conversion == 'F')
3458 if ((flags & FLAG_ALT) || precision > 0)
3460 *p++ = decimal_point_char ();
3461 for (; precision > 0; precision--)
3465 else if (dp->conversion == 'e' || dp->conversion == 'E')
3468 if ((flags & FLAG_ALT) || precision > 0)
3470 *p++ = decimal_point_char ();
3471 for (; precision > 0; precision--)
3474 *p++ = dp->conversion; /* 'e' or 'E' */
3476 /* Produce the same number of exponent digits as
3477 the native printf implementation. */
3478 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3484 else if (dp->conversion == 'g' || dp->conversion == 'G')
3487 if (flags & FLAG_ALT)
3490 (precision > 0 ? precision - 1 : 0);
3491 *p++ = decimal_point_char ();
3492 for (; ndigits > 0; --ndigits)
3504 /* The generated string now extends from tmp to p, with the
3505 zero padding insertion point being at pad_ptr. */
3506 if (has_width && p - tmp < width)
3508 size_t pad = width - (p - tmp);
3509 DCHAR_T *end = p + pad;
3511 if (flags & FLAG_LEFT)
3513 /* Pad with spaces on the right. */
3514 for (; pad > 0; pad--)
3517 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3519 /* Pad with zeroes. */
3524 for (; pad > 0; pad--)
3529 /* Pad with spaces on the left. */
3534 for (; pad > 0; pad--)
3542 size_t count = p - tmp;
3544 if (count >= tmp_length)
3545 /* tmp_length was incorrectly calculated - fix the
3549 /* Make room for the result. */
3550 if (count >= allocated - length)
3552 size_t n = xsum (length, count);
3554 ENSURE_ALLOCATION (n);
3557 /* Append the result. */
3558 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3567 arg_type type = a.arg[dp->arg_index].type;
3568 int flags = dp->flags;
3569 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3573 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3577 #if NEED_PRINTF_UNBOUNDED_PRECISION
3580 # define prec_ourselves 0
3582 #if NEED_PRINTF_FLAG_LEFTADJUST
3583 # define pad_ourselves 1
3584 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3587 # define pad_ourselves 0
3590 unsigned int prefix_count;
3594 TCHAR_T tmpbuf[700];
3598 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3601 if (dp->width_start != dp->width_end)
3603 if (dp->width_arg_index != ARG_NONE)
3607 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3609 arg = a.arg[dp->width_arg_index].a.a_int;
3612 /* "A negative field width is taken as a '-' flag
3613 followed by a positive field width." */
3615 width = (unsigned int) (-arg);
3622 const FCHAR_T *digitp = dp->width_start;
3625 width = xsum (xtimes (width, 10), *digitp++ - '0');
3626 while (digitp != dp->width_end);
3632 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3635 if (dp->precision_start != dp->precision_end)
3637 if (dp->precision_arg_index != ARG_NONE)
3641 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3643 arg = a.arg[dp->precision_arg_index].a.a_int;
3644 /* "A negative precision is taken as if the precision
3654 const FCHAR_T *digitp = dp->precision_start + 1;
3657 while (digitp != dp->precision_end)
3658 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3665 /* Allocate a temporary buffer of sufficient size for calling
3668 switch (dp->conversion)
3671 case 'd': case 'i': case 'u':
3672 # if HAVE_LONG_LONG_INT
3673 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3675 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3676 * 0.30103 /* binary -> decimal */
3678 + 1; /* turn floor into ceil */
3681 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3683 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3684 * 0.30103 /* binary -> decimal */
3686 + 1; /* turn floor into ceil */
3689 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3690 * 0.30103 /* binary -> decimal */
3692 + 1; /* turn floor into ceil */
3693 if (tmp_length < precision)
3694 tmp_length = precision;
3695 /* Multiply by 2, as an estimate for FLAG_GROUP. */
3696 tmp_length = xsum (tmp_length, tmp_length);
3697 /* Add 1, to account for a leading sign. */
3698 tmp_length = xsum (tmp_length, 1);
3702 # if HAVE_LONG_LONG_INT
3703 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3705 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3706 * 0.333334 /* binary -> octal */
3708 + 1; /* turn floor into ceil */
3711 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3713 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3714 * 0.333334 /* binary -> octal */
3716 + 1; /* turn floor into ceil */
3719 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3720 * 0.333334 /* binary -> octal */
3722 + 1; /* turn floor into ceil */
3723 if (tmp_length < precision)
3724 tmp_length = precision;
3725 /* Add 1, to account for a leading sign. */
3726 tmp_length = xsum (tmp_length, 1);
3730 # if HAVE_LONG_LONG_INT
3731 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3733 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3734 * 0.25 /* binary -> hexadecimal */
3736 + 1; /* turn floor into ceil */
3739 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3741 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3742 * 0.25 /* binary -> hexadecimal */
3744 + 1; /* turn floor into ceil */
3747 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3748 * 0.25 /* binary -> hexadecimal */
3750 + 1; /* turn floor into ceil */
3751 if (tmp_length < precision)
3752 tmp_length = precision;
3753 /* Add 2, to account for a leading sign or alternate form. */
3754 tmp_length = xsum (tmp_length, 2);
3758 if (type == TYPE_LONGDOUBLE)
3760 (unsigned int) (LDBL_MAX_EXP
3761 * 0.30103 /* binary -> decimal */
3762 * 2 /* estimate for FLAG_GROUP */
3764 + 1 /* turn floor into ceil */
3765 + 10; /* sign, decimal point etc. */
3768 (unsigned int) (DBL_MAX_EXP
3769 * 0.30103 /* binary -> decimal */
3770 * 2 /* estimate for FLAG_GROUP */
3772 + 1 /* turn floor into ceil */
3773 + 10; /* sign, decimal point etc. */
3774 tmp_length = xsum (tmp_length, precision);
3777 case 'e': case 'E': case 'g': case 'G':
3779 12; /* sign, decimal point, exponent etc. */
3780 tmp_length = xsum (tmp_length, precision);
3784 if (type == TYPE_LONGDOUBLE)
3786 (unsigned int) (LDBL_DIG
3787 * 0.831 /* decimal -> hexadecimal */
3789 + 1; /* turn floor into ceil */
3792 (unsigned int) (DBL_DIG
3793 * 0.831 /* decimal -> hexadecimal */
3795 + 1; /* turn floor into ceil */
3796 if (tmp_length < precision)
3797 tmp_length = precision;
3798 /* Account for sign, decimal point etc. */
3799 tmp_length = xsum (tmp_length, 12);
3803 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
3804 if (type == TYPE_WIDE_CHAR)
3805 tmp_length = MB_CUR_MAX;
3813 if (type == TYPE_WIDE_STRING)
3816 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
3818 # if !WIDE_CHAR_VERSION
3819 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
3824 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
3829 (unsigned int) (sizeof (void *) * CHAR_BIT
3830 * 0.25 /* binary -> hexadecimal */
3832 + 1 /* turn floor into ceil */
3833 + 2; /* account for leading 0x */
3840 # if ENABLE_UNISTDIO
3841 /* Padding considers the number of characters, therefore the
3842 number of elements after padding may be
3843 > max (tmp_length, width)
3845 <= tmp_length + width. */
3846 tmp_length = xsum (tmp_length, width);
3848 /* Padding considers the number of elements, says POSIX. */
3849 if (tmp_length < width)
3853 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3856 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
3860 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
3862 if (size_overflow_p (tmp_memsize))
3863 /* Overflow, would lead to out of memory. */
3865 tmp = (TCHAR_T *) malloc (tmp_memsize);
3867 /* Out of memory. */
3872 /* Decide whether to handle the precision ourselves. */
3873 #if NEED_PRINTF_UNBOUNDED_PRECISION
3874 switch (dp->conversion)
3876 case 'd': case 'i': case 'u':
3878 case 'x': case 'X': case 'p':
3879 prec_ourselves = has_precision && (precision > 0);
3887 /* Decide whether to perform the padding ourselves. */
3888 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
3889 switch (dp->conversion)
3891 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
3892 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
3893 to perform the padding after this conversion. Functions
3894 with unistdio extensions perform the padding based on
3895 character count rather than element count. */
3898 # if NEED_PRINTF_FLAG_ZERO
3899 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
3905 pad_ourselves = prec_ourselves;
3910 /* Construct the format string for calling snprintf or
3914 #if NEED_PRINTF_FLAG_GROUPING
3915 /* The underlying implementation doesn't support the ' flag.
3916 Produce no grouping characters in this case; this is
3917 acceptable because the grouping is locale dependent. */
3919 if (flags & FLAG_GROUP)
3922 if (flags & FLAG_LEFT)
3924 if (flags & FLAG_SHOWSIGN)
3926 if (flags & FLAG_SPACE)
3928 if (flags & FLAG_ALT)
3932 if (flags & FLAG_ZERO)
3934 if (dp->width_start != dp->width_end)
3936 size_t n = dp->width_end - dp->width_start;
3937 /* The width specification is known to consist only
3938 of standard ASCII characters. */
3939 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
3941 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
3946 const FCHAR_T *mp = dp->width_start;
3948 *fbp++ = (unsigned char) *mp++;
3953 if (!prec_ourselves)
3955 if (dp->precision_start != dp->precision_end)
3957 size_t n = dp->precision_end - dp->precision_start;
3958 /* The precision specification is known to consist only
3959 of standard ASCII characters. */
3960 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
3962 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
3967 const FCHAR_T *mp = dp->precision_start;
3969 *fbp++ = (unsigned char) *mp++;
3977 #if HAVE_LONG_LONG_INT
3978 case TYPE_LONGLONGINT:
3979 case TYPE_ULONGLONGINT:
3980 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3993 case TYPE_WIDE_CHAR:
3996 case TYPE_WIDE_STRING:
4000 case TYPE_LONGDOUBLE:
4006 #if NEED_PRINTF_DIRECTIVE_F
4007 if (dp->conversion == 'F')
4011 *fbp = dp->conversion;
4013 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4018 /* On glibc2 systems from glibc >= 2.3 - probably also older
4019 ones - we know that snprintf's returns value conforms to
4020 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4021 Therefore we can avoid using %n in this situation.
4022 On glibc2 systems from 2004-10-18 or newer, the use of %n
4023 in format strings in writable memory may crash the program
4024 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4025 in this situation. */
4026 /* On native Win32 systems (such as mingw), we can avoid using
4028 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4029 snprintf does not write more than the specified number
4030 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4031 '4', '5', '6' into buf, not '4', '5', '\0'.)
4032 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4033 allows us to recognize the case of an insufficient
4034 buffer size: it returns -1 in this case.
4035 On native Win32 systems (such as mingw) where the OS is
4036 Windows Vista, the use of %n in format strings by default
4037 crashes the program. See
4038 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4039 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4040 So we should avoid %n in this situation. */
4047 /* Construct the arguments for calling snprintf or sprintf. */
4049 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4051 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4053 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4055 if (dp->precision_arg_index != ARG_NONE)
4057 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4059 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4063 /* The SNPRINTF result is appended after result[0..length].
4064 The latter is an array of DCHAR_T; SNPRINTF appends an
4065 array of TCHAR_T to it. This is possible because
4066 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4067 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4068 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4069 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4070 where an snprintf() with maxlen==1 acts like sprintf(). */
4071 ENSURE_ALLOCATION (xsum (length,
4072 (2 + TCHARS_PER_DCHAR - 1)
4073 / TCHARS_PER_DCHAR));
4074 /* Prepare checking whether snprintf returns the count
4076 *(TCHAR_T *) (result + length) = '\0';
4085 size_t maxlen = allocated - length;
4086 /* SNPRINTF can fail if its second argument is
4088 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4089 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4090 maxlen = maxlen * TCHARS_PER_DCHAR;
4091 # define SNPRINTF_BUF(arg) \
4092 switch (prefix_count) \
4095 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4100 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4102 prefixes[0], arg, &count); \
4105 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4107 prefixes[0], prefixes[1], arg, \
4114 # define SNPRINTF_BUF(arg) \
4115 switch (prefix_count) \
4118 count = sprintf (tmp, buf, arg); \
4121 count = sprintf (tmp, buf, prefixes[0], arg); \
4124 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4136 int arg = a.arg[dp->arg_index].a.a_schar;
4142 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4148 int arg = a.arg[dp->arg_index].a.a_short;
4154 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4160 int arg = a.arg[dp->arg_index].a.a_int;
4166 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4172 long int arg = a.arg[dp->arg_index].a.a_longint;
4178 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4182 #if HAVE_LONG_LONG_INT
4183 case TYPE_LONGLONGINT:
4185 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4189 case TYPE_ULONGLONGINT:
4191 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4198 double arg = a.arg[dp->arg_index].a.a_double;
4202 case TYPE_LONGDOUBLE:
4204 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4210 int arg = a.arg[dp->arg_index].a.a_char;
4215 case TYPE_WIDE_CHAR:
4217 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
4224 const char *arg = a.arg[dp->arg_index].a.a_string;
4229 case TYPE_WIDE_STRING:
4231 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
4238 void *arg = a.arg[dp->arg_index].a.a_pointer;
4247 /* Portability: Not all implementations of snprintf()
4248 are ISO C 99 compliant. Determine the number of
4249 bytes that snprintf() has produced or would have
4253 /* Verify that snprintf() has NUL-terminated its
4256 && ((TCHAR_T *) (result + length)) [count] != '\0')
4258 /* Portability hack. */
4259 if (retcount > count)
4264 /* snprintf() doesn't understand the '%n'
4268 /* Don't use the '%n' directive; instead, look
4269 at the snprintf() return value. */
4275 /* Look at the snprintf() return value. */
4278 /* HP-UX 10.20 snprintf() is doubly deficient:
4279 It doesn't understand the '%n' directive,
4280 *and* it returns -1 (rather than the length
4281 that would have been required) when the
4282 buffer is too small. */
4283 size_t bigger_need =
4284 xsum (xtimes (allocated, 2), 12);
4285 ENSURE_ALLOCATION (bigger_need);
4294 /* Attempt to handle failure. */
4297 if (!(result == resultbuf || result == NULL))
4299 if (buf_malloced != NULL)
4300 free (buf_malloced);
4307 /* Handle overflow of the allocated buffer.
4308 If such an overflow occurs, a C99 compliant snprintf()
4309 returns a count >= maxlen. However, a non-compliant
4310 snprintf() function returns only count = maxlen - 1. To
4311 cover both cases, test whether count >= maxlen - 1. */
4312 if ((unsigned int) count + 1 >= maxlen)
4314 /* If maxlen already has attained its allowed maximum,
4315 allocating more memory will not increase maxlen.
4316 Instead of looping, bail out. */
4317 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
4321 /* Need at least (count + 1) * sizeof (TCHAR_T)
4322 bytes. (The +1 is for the trailing NUL.)
4323 But ask for (count + 2) * sizeof (TCHAR_T)
4324 bytes, so that in the next round, we likely get
4325 maxlen > (unsigned int) count + 1
4326 and so we don't get here again.
4327 And allocate proportionally, to avoid looping
4328 eternally if snprintf() reports a too small
4332 ((unsigned int) count + 2
4333 + TCHARS_PER_DCHAR - 1)
4334 / TCHARS_PER_DCHAR),
4335 xtimes (allocated, 2));
4337 ENSURE_ALLOCATION (n);
4343 #if NEED_PRINTF_UNBOUNDED_PRECISION
4346 /* Handle the precision. */
4349 (TCHAR_T *) (result + length);
4353 size_t prefix_count;
4357 /* Put the additional zeroes after the sign. */
4359 && (*prec_ptr == '-' || *prec_ptr == '+'
4360 || *prec_ptr == ' '))
4362 /* Put the additional zeroes after the 0x prefix if
4363 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
4365 && prec_ptr[0] == '0'
4366 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
4369 move = count - prefix_count;
4370 if (precision > move)
4372 /* Insert zeroes. */
4373 size_t insert = precision - move;
4379 (count + insert + TCHARS_PER_DCHAR - 1)
4380 / TCHARS_PER_DCHAR);
4381 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4382 ENSURE_ALLOCATION (n);
4383 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4384 prec_ptr = (TCHAR_T *) (result + length);
4387 prec_end = prec_ptr + count;
4388 prec_ptr += prefix_count;
4390 while (prec_end > prec_ptr)
4393 prec_end[insert] = prec_end[0];
4399 while (prec_end > prec_ptr);
4408 if (count >= tmp_length)
4409 /* tmp_length was incorrectly calculated - fix the
4414 /* Convert from TCHAR_T[] to DCHAR_T[]. */
4415 if (dp->conversion == 'c' || dp->conversion == 's')
4417 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
4419 The result string is not certainly ASCII. */
4420 const TCHAR_T *tmpsrc;
4423 /* This code assumes that TCHAR_T is 'char'. */
4424 typedef int TCHAR_T_verify
4425 [2 * (sizeof (TCHAR_T) == 1) - 1];
4427 tmpsrc = (TCHAR_T *) (result + length);
4433 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
4434 iconveh_question_mark,
4437 &tmpdst, &tmpdst_len)
4440 int saved_errno = errno;
4441 if (!(result == resultbuf || result == NULL))
4443 if (buf_malloced != NULL)
4444 free (buf_malloced);
4446 errno = saved_errno;
4449 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
4450 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
4456 /* The result string is ASCII.
4457 Simple 1:1 conversion. */
4459 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
4460 no-op conversion, in-place on the array starting
4461 at (result + length). */
4462 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
4465 const TCHAR_T *tmpsrc;
4470 if (result == resultbuf)
4472 tmpsrc = (TCHAR_T *) (result + length);
4473 /* ENSURE_ALLOCATION will not move tmpsrc
4474 (because it's part of resultbuf). */
4475 ENSURE_ALLOCATION (xsum (length, count));
4479 /* ENSURE_ALLOCATION will move the array
4480 (because it uses realloc(). */
4481 ENSURE_ALLOCATION (xsum (length, count));
4482 tmpsrc = (TCHAR_T *) (result + length);
4486 ENSURE_ALLOCATION (xsum (length, count));
4488 tmpdst = result + length;
4489 /* Copy backwards, because of overlapping. */
4492 for (n = count; n > 0; n--)
4493 *--tmpdst = (unsigned char) *--tmpsrc;
4498 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4499 /* Make room for the result. */
4500 if (count > allocated - length)
4502 /* Need at least count elements. But allocate
4505 xmax (xsum (length, count), xtimes (allocated, 2));
4507 ENSURE_ALLOCATION (n);
4511 /* Here count <= allocated - length. */
4513 /* Perform padding. */
4514 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4515 if (pad_ourselves && has_width)
4518 # if ENABLE_UNISTDIO
4519 /* Outside POSIX, it's preferrable to compare the width
4520 against the number of _characters_ of the converted
4522 w = DCHAR_MBSNLEN (result + length, count);
4524 /* The width is compared against the number of _bytes_
4525 of the converted value, says POSIX. */
4530 size_t pad = width - w;
4532 /* Make room for the result. */
4533 if (xsum (count, pad) > allocated - length)
4535 /* Need at least count + pad elements. But
4536 allocate proportionally. */
4538 xmax (xsum3 (length, count, pad),
4539 xtimes (allocated, 2));
4542 ENSURE_ALLOCATION (n);
4545 /* Here count + pad <= allocated - length. */
4548 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
4549 DCHAR_T * const rp = result + length;
4551 DCHAR_T * const rp = tmp;
4553 DCHAR_T *p = rp + count;
4554 DCHAR_T *end = p + pad;
4556 # if !DCHAR_IS_TCHAR
4557 if (dp->conversion == 'c'
4558 || dp->conversion == 's')
4559 /* No zero-padding for string directives. */
4564 pad_ptr = (*rp == '-' ? rp + 1 : rp);
4565 /* No zero-padding of "inf" and "nan". */
4566 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
4567 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
4570 /* The generated string now extends from rp to p,
4571 with the zero padding insertion point being at
4574 count = count + pad; /* = end - rp */
4576 if (flags & FLAG_LEFT)
4578 /* Pad with spaces on the right. */
4579 for (; pad > 0; pad--)
4582 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4584 /* Pad with zeroes. */
4589 for (; pad > 0; pad--)
4594 /* Pad with spaces on the left. */
4599 for (; pad > 0; pad--)
4607 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4608 if (count >= tmp_length)
4609 /* tmp_length was incorrectly calculated - fix the
4614 /* Here still count <= allocated - length. */
4616 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
4617 /* The snprintf() result did fit. */
4619 /* Append the sprintf() result. */
4620 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4627 #if NEED_PRINTF_DIRECTIVE_F
4628 if (dp->conversion == 'F')
4630 /* Convert the %f result to upper case for %F. */
4631 DCHAR_T *rp = result + length;
4633 for (rc = count; rc > 0; rc--, rp++)
4634 if (*rp >= 'a' && *rp <= 'z')
4635 *rp = *rp - 'a' + 'A';
4646 /* Add the final NUL. */
4647 ENSURE_ALLOCATION (xsum (length, 1));
4648 result[length] = '\0';
4650 if (result != resultbuf && length + 1 < allocated)
4652 /* Shrink the allocated memory if possible. */
4655 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
4660 if (buf_malloced != NULL)
4661 free (buf_malloced);
4664 /* Note that we can produce a big string of a length > INT_MAX. POSIX
4665 says that snprintf() fails with errno = EOVERFLOW in this case, but
4666 that's only because snprintf() returns an 'int'. This function does
4667 not have this limitation. */
4672 if (!(result == resultbuf || result == NULL))
4674 if (buf_malloced != NULL)
4675 free (buf_malloced);
4682 if (!(result == resultbuf || result == NULL))
4684 if (buf_malloced != NULL)
4685 free (buf_malloced);
4693 #undef TCHARS_PER_DCHAR
4700 #undef DCHAR_IS_TCHAR