1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2007 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_LONG_DOUBLE && !defined IN_LIBINTL
97 #if NEED_PRINTF_INFINITE_DOUBLE && !defined IN_LIBINTL
102 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !defined IN_LIBINTL
104 # include "isnanl-nolibm.h"
108 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
111 # include "printf-frexp.h"
112 # include "isnanl-nolibm.h"
113 # include "printf-frexpl.h"
117 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
119 # define EOVERFLOW E2BIG
124 # define local_wcslen wcslen
126 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
127 a dependency towards this library, here is a local substitute.
128 Define this substitute only once, even if this file is included
129 twice in the same compilation unit. */
130 # ifndef local_wcslen_defined
131 # define local_wcslen_defined 1
133 local_wcslen (const wchar_t *s)
137 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
145 /* Default parameters. */
147 # if WIDE_CHAR_VERSION
148 # define VASNPRINTF vasnwprintf
149 # define FCHAR_T wchar_t
150 # define DCHAR_T wchar_t
151 # define TCHAR_T wchar_t
152 # define DCHAR_IS_TCHAR 1
153 # define DIRECTIVE wchar_t_directive
154 # define DIRECTIVES wchar_t_directives
155 # define PRINTF_PARSE wprintf_parse
156 # define DCHAR_CPY wmemcpy
158 # define VASNPRINTF vasnprintf
159 # define FCHAR_T char
160 # define DCHAR_T char
161 # define TCHAR_T char
162 # define DCHAR_IS_TCHAR 1
163 # define DIRECTIVE char_directive
164 # define DIRECTIVES char_directives
165 # define PRINTF_PARSE printf_parse
166 # define DCHAR_CPY memcpy
169 #if WIDE_CHAR_VERSION
170 /* TCHAR_T is wchar_t. */
171 # define USE_SNPRINTF 1
172 # if HAVE_DECL__SNWPRINTF
173 /* On Windows, the function swprintf() has a different signature than
174 on Unix; we use the _snwprintf() function instead. */
175 # define SNPRINTF _snwprintf
178 # define SNPRINTF swprintf
181 /* TCHAR_T is char. */
182 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
183 But don't use it on BeOS, since BeOS snprintf produces no output if the
184 size argument is >= 0x3000000. */
185 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
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 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
204 /* Determine the decimal-point character according to the current locale. */
205 # ifndef decimal_point_char_defined
206 # define decimal_point_char_defined 1
208 decimal_point_char ()
211 /* Determine it in a multithread-safe way. We know nl_langinfo is
212 multithread-safe on glibc systems, but is not required to be multithread-
213 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
214 is rarely multithread-safe. */
215 # if HAVE_NL_LANGINFO && __GLIBC__
216 point = nl_langinfo (RADIXCHAR);
219 sprintf (pointbuf, "%#.0f", 1.0);
220 point = &pointbuf[1];
222 point = localeconv () -> decimal_point;
224 /* The decimal point is always a single byte: either '.' or ','. */
225 return (point[0] != '\0' ? point[0] : '.');
230 #if NEED_PRINTF_INFINITE_DOUBLE && !defined IN_LIBINTL
232 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
234 is_infinite_or_zero (double x)
236 return isnan (x) || x + x == x;
241 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !defined IN_LIBINTL
243 /* Equivalent to !isfinite(x), but does not require libm. */
245 is_infinitel (long double x)
247 return isnanl (x) || (x + x == x && x != 0.0L);
252 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
254 /* Converting 'long double' to decimal without rare rounding bugs requires
255 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
256 (and slower) algorithms. */
258 typedef unsigned int mp_limb_t;
259 # define GMP_LIMB_BITS 32
260 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
262 typedef unsigned long long mp_twolimb_t;
263 # define GMP_TWOLIMB_BITS 64
264 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
266 /* Representation of a bignum >= 0. */
270 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
273 /* Compute the product of two bignums >= 0.
274 Return the allocated memory in case of success, NULL in case of memory
275 allocation failure. */
277 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
284 if (src1.nlimbs <= src2.nlimbs)
298 /* Now 0 <= len1 <= len2. */
301 /* src1 or src2 is zero. */
303 dest->limbs = (mp_limb_t *) malloc (1);
307 /* Here 1 <= len1 <= len2. */
313 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
316 for (k = len2; k > 0; )
318 for (i = 0; i < len1; i++)
320 mp_limb_t digit1 = p1[i];
321 mp_twolimb_t carry = 0;
322 for (j = 0; j < len2; j++)
324 mp_limb_t digit2 = p2[j];
325 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
327 dp[i + j] = (mp_limb_t) carry;
328 carry = carry >> GMP_LIMB_BITS;
330 dp[i + len2] = (mp_limb_t) carry;
333 while (dlen > 0 && dp[dlen - 1] == 0)
341 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
342 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
344 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
346 Return the allocated memory in case of success, NULL in case of memory
347 allocation failure. */
349 divide (mpn_t a, mpn_t b, mpn_t *q)
352 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
353 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
354 If m<n, then q:=0 and r:=a.
355 If m>=n=1, perform a single-precision division:
358 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
359 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
360 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
361 Normalise [q[m-1],...,q[0]], yields q.
362 If m>=n>1, perform a multiple-precision division:
363 We have a/b < beta^(m-n+1).
364 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
365 Shift a and b left by s bits, copying them. r:=a.
366 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
367 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
369 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
370 In case of overflow (q* >= beta) set q* := beta-1.
371 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
372 and c3 := b[n-2] * q*.
373 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
374 occurred. Furthermore 0 <= c3 < beta^2.
375 If there was overflow and
376 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
377 the next test can be skipped.}
378 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
379 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
381 Put r := r - b * q* * beta^j. In detail:
382 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
383 hence: u:=0, for i:=0 to n-1 do
385 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
386 u:=u div beta (+ 1, if carry in subtraction)
388 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
390 the carry u does not overflow.}
391 If a negative carry occurs, put q* := q* - 1
392 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
394 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
395 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
397 The room for q[j] can be allocated at the memory location of r[n+j].
398 Finally, round-to-even:
399 Shift r left by 1 bit.
400 If r > b or if r = b and q[0] is odd, q := q+1.
402 const mp_limb_t *a_ptr = a.limbs;
403 size_t a_len = a.nlimbs;
404 const mp_limb_t *b_ptr = b.limbs;
405 size_t b_len = b.nlimbs;
407 mp_limb_t *tmp_roomptr = NULL;
413 /* Allocate room for a_len+2 digits.
414 (Need a_len+1 digits for the real division and 1 more digit for the
415 final rounding of q.) */
416 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
421 while (a_len > 0 && a_ptr[a_len - 1] == 0)
428 /* Division by zero. */
430 if (b_ptr[b_len - 1] == 0)
436 /* Here m = a_len >= 0 and n = b_len > 0. */
440 /* m<n: trivial case. q=0, r := copy of a. */
443 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
444 q_ptr = roomptr + a_len;
449 /* n=1: single precision division.
450 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
454 mp_limb_t den = b_ptr[0];
455 mp_limb_t remainder = 0;
456 const mp_limb_t *sourceptr = a_ptr + a_len;
457 mp_limb_t *destptr = q_ptr + a_len;
459 for (count = a_len; count > 0; count--)
462 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
463 *--destptr = num / den;
464 remainder = num % den;
466 /* Normalise and store r. */
469 r_ptr[0] = remainder;
476 if (q_ptr[q_len - 1] == 0)
482 /* n>1: multiple precision division.
483 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
484 beta^(m-n-1) <= a/b < beta^(m-n+1). */
488 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
516 /* 0 <= s < GMP_LIMB_BITS.
517 Copy b, shifting it left by s bits. */
520 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
521 if (tmp_roomptr == NULL)
527 const mp_limb_t *sourceptr = b_ptr;
528 mp_limb_t *destptr = tmp_roomptr;
529 mp_twolimb_t accu = 0;
531 for (count = b_len; count > 0; count--)
533 accu += (mp_twolimb_t) *sourceptr++ << s;
534 *destptr++ = (mp_limb_t) accu;
535 accu = accu >> GMP_LIMB_BITS;
537 /* accu must be zero, since that was how s was determined. */
543 /* Copy a, shifting it left by s bits, yields r.
545 At the beginning: r = roomptr[0..a_len],
546 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
550 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
555 const mp_limb_t *sourceptr = a_ptr;
556 mp_limb_t *destptr = r_ptr;
557 mp_twolimb_t accu = 0;
559 for (count = a_len; count > 0; count--)
561 accu += (mp_twolimb_t) *sourceptr++ << s;
562 *destptr++ = (mp_limb_t) accu;
563 accu = accu >> GMP_LIMB_BITS;
565 *destptr++ = (mp_limb_t) accu;
567 q_ptr = roomptr + b_len;
568 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
570 size_t j = a_len - b_len; /* m-n */
571 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
572 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
573 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
574 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
575 /* Division loop, traversed m-n+1 times.
576 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
581 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
583 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
585 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
586 | r_ptr[j + b_len - 1];
587 q_star = num / b_msd;
592 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
593 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
594 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
595 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
596 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
598 If yes, jump directly to the subtraction loop.
599 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
600 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
601 if (r_ptr[j + b_len] > b_msd
602 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
603 /* r[j+n] >= b[n-1]+1 or
604 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
609 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
611 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
612 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
613 mp_twolimb_t c3 = /* b[n-2] * q* */
614 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
615 /* While c2 < c3, increase c2 and decrease c3.
616 Consider c3-c2. While it is > 0, decrease it by
617 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
618 this can happen only twice. */
621 q_star = q_star - 1; /* q* := q* - 1 */
622 if (c3 - c2 > b_msdd)
623 q_star = q_star - 1; /* q* := q* - 1 */
629 /* Subtract r := r - b * q* * beta^j. */
632 const mp_limb_t *sourceptr = b_ptr;
633 mp_limb_t *destptr = r_ptr + j;
634 mp_twolimb_t carry = 0;
636 for (count = b_len; count > 0; count--)
638 /* Here 0 <= carry <= q*. */
641 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
642 + (mp_limb_t) ~(*destptr);
643 /* Here 0 <= carry <= beta*q* + beta-1. */
644 *destptr++ = ~(mp_limb_t) carry;
645 carry = carry >> GMP_LIMB_BITS; /* <= q* */
647 cr = (mp_limb_t) carry;
649 /* Subtract cr from r_ptr[j + b_len], then forget about
651 if (cr > r_ptr[j + b_len])
653 /* Subtraction gave a carry. */
654 q_star = q_star - 1; /* q* := q* - 1 */
657 const mp_limb_t *sourceptr = b_ptr;
658 mp_limb_t *destptr = r_ptr + j;
661 for (count = b_len; count > 0; count--)
663 mp_limb_t source1 = *sourceptr++;
664 mp_limb_t source2 = *destptr;
665 *destptr++ = source1 + source2 + carry;
668 ? source1 >= (mp_limb_t) ~source2
669 : source1 > (mp_limb_t) ~source2);
672 /* Forget about the carry and about r[j+n]. */
675 /* q* is determined. Store it as q[j]. */
684 if (q_ptr[q_len - 1] == 0)
686 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
687 b is shifted left by s bits. */
688 /* Shift r right by s bits. */
691 mp_limb_t ptr = r_ptr + r_len;
692 mp_twolimb_t accu = 0;
694 for (count = r_len; count > 0; count--)
696 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
697 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
698 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
703 while (r_len > 0 && r_ptr[r_len - 1] == 0)
706 /* Compare r << 1 with b. */
714 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
715 | (i < r_len ? r_ptr[i] << 1 : 0);
716 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
726 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
731 for (i = 0; i < q_len; i++)
732 if (++(q_ptr[i]) != 0)
737 if (tmp_roomptr != NULL)
744 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
746 Destroys the contents of a.
747 Return the allocated memory - containing the decimal digits in low-to-high
748 order, terminated with a NUL character - in case of success, NULL in case
749 of memory allocation failure. */
751 convert_to_decimal (mpn_t a, size_t extra_zeroes)
753 mp_limb_t *a_ptr = a.limbs;
754 size_t a_len = a.nlimbs;
755 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
756 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
757 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
761 for (; extra_zeroes > 0; extra_zeroes--)
765 /* Divide a by 10^9, in-place. */
766 mp_limb_t remainder = 0;
767 mp_limb_t *ptr = a_ptr + a_len;
769 for (count = a_len; count > 0; count--)
772 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
773 *ptr = num / 1000000000;
774 remainder = num % 1000000000;
776 /* Store the remainder as 9 decimal digits. */
777 for (count = 9; count > 0; count--)
779 *d_ptr++ = '0' + (remainder % 10);
780 remainder = remainder / 10;
783 if (a_ptr[a_len - 1] == 0)
786 /* Remove leading zeroes. */
787 while (d_ptr > c_ptr && d_ptr[-1] == '0')
789 /* But keep at least one zero. */
792 /* Terminate the string. */
798 /* Assuming x is finite and >= 0:
799 write x as x = 2^e * m, where m is a bignum.
800 Return the allocated memory in case of success, NULL in case of memory
801 allocation failure. */
803 decode_long_double (long double x, int *ep, mpn_t *mp)
810 /* Allocate memory for result. */
811 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
812 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
815 /* Split into exponential part and mantissa. */
816 y = frexpl (x, &exp);
817 if (!(y >= 0.0L && y < 1.0L))
819 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
820 latter is an integer. */
821 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
822 I'm not sure whether it's safe to cast a 'long double' value between
823 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
824 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
826 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
827 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
830 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
833 if (!(y >= 0.0L && y < 1.0L))
835 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
838 if (!(y >= 0.0L && y < 1.0L))
840 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
845 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
848 if (!(y >= 0.0L && y < 1.0L))
850 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
854 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
857 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
860 if (!(y >= 0.0L && y < 1.0L))
862 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
865 if (!(y >= 0.0L && y < 1.0L))
867 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
872 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
875 *ep = exp - LDBL_MANT_BIT;
879 /* Assuming x is finite and >= 0, and n is an integer:
880 Returns the decimal representation of round (x * 10^n).
881 Return the allocated memory - containing the decimal digits in low-to-high
882 order, terminated with a NUL character - in case of success, NULL in case
883 of memory allocation failure. */
885 scale10_round_decimal_long_double (long double x, int n)
889 void *memory = decode_long_double (x, &e, &m);
896 unsigned int s_limbs;
905 /* x = 2^e * m, hence
906 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
907 = round (2^s * 5^n * m). */
910 /* Factor out a common power of 10 if possible. */
913 extra_zeroes = (s < n ? s : n);
917 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
918 Before converting to decimal, we need to compute
919 z = round (2^s * 5^n * m). */
920 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
921 sign. 2.322 is slightly larger than log(5)/log(2). */
922 abs_n = (n >= 0 ? n : -n);
923 abs_s = (s >= 0 ? s : -s);
924 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
925 + abs_s / GMP_LIMB_BITS + 1)
926 * sizeof (mp_limb_t));
927 if (pow5_ptr == NULL)
932 /* Initialize with 1. */
935 /* Multiply with 5^|n|. */
938 static mp_limb_t const small_pow5[13 + 1] =
940 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
941 48828125, 244140625, 1220703125
944 for (n13 = 0; n13 <= abs_n; n13 += 13)
946 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
948 mp_twolimb_t carry = 0;
949 for (j = 0; j < pow5_len; j++)
951 mp_limb_t digit2 = pow5_ptr[j];
952 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
953 pow5_ptr[j] = (mp_limb_t) carry;
954 carry = carry >> GMP_LIMB_BITS;
957 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
960 s_limbs = abs_s / GMP_LIMB_BITS;
961 s_bits = abs_s % GMP_LIMB_BITS;
962 if (n >= 0 ? s >= 0 : s <= 0)
964 /* Multiply with 2^|s|. */
967 mp_limb_t *ptr = pow5_ptr;
968 mp_twolimb_t accu = 0;
970 for (count = pow5_len; count > 0; count--)
972 accu += (mp_twolimb_t) *ptr << s_bits;
973 *ptr++ = (mp_limb_t) accu;
974 accu = accu >> GMP_LIMB_BITS;
978 *ptr = (mp_limb_t) accu;
985 for (count = pow5_len; count > 0;)
988 pow5_ptr[s_limbs + count] = pow5_ptr[count];
990 for (count = s_limbs; count > 0;)
997 pow5.limbs = pow5_ptr;
998 pow5.nlimbs = pow5_len;
1001 /* Multiply m with pow5. No division needed. */
1002 z_memory = multiply (m, pow5, &z);
1006 /* Divide m by pow5 and round. */
1007 z_memory = divide (m, pow5, &z);
1012 pow5.limbs = pow5_ptr;
1013 pow5.nlimbs = pow5_len;
1017 Multiply m with pow5, then divide by 2^|s|. */
1021 tmp_memory = multiply (m, pow5, &numerator);
1022 if (tmp_memory == NULL)
1028 /* Construct 2^|s|. */
1030 mp_limb_t *ptr = pow5_ptr + pow5_len;
1032 for (i = 0; i < s_limbs; i++)
1034 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1035 denominator.limbs = ptr;
1036 denominator.nlimbs = s_limbs + 1;
1038 z_memory = divide (numerator, denominator, &z);
1044 Multiply m with 2^s, then divide by pow5. */
1047 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1048 * sizeof (mp_limb_t));
1049 if (num_ptr == NULL)
1056 mp_limb_t *destptr = num_ptr;
1059 for (i = 0; i < s_limbs; i++)
1064 const mp_limb_t *sourceptr = m.limbs;
1065 mp_twolimb_t accu = 0;
1067 for (count = m.nlimbs; count > 0; count--)
1069 accu += (mp_twolimb_t) *sourceptr++ << s;
1070 *destptr++ = (mp_limb_t) accu;
1071 accu = accu >> GMP_LIMB_BITS;
1074 *destptr++ = (mp_limb_t) accu;
1078 const mp_limb_t *sourceptr = m.limbs;
1080 for (count = m.nlimbs; count > 0; count--)
1081 *destptr++ = *sourceptr++;
1083 numerator.limbs = num_ptr;
1084 numerator.nlimbs = destptr - num_ptr;
1086 z_memory = divide (numerator, pow5, &z);
1093 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1095 if (z_memory == NULL)
1097 digits = convert_to_decimal (z, extra_zeroes);
1102 /* Assuming x is finite and > 0:
1103 Return an approximation for n with 10^n <= x < 10^(n+1).
1104 The approximation is usually the right n, but may be off by 1 sometimes. */
1106 floorlog10l (long double x)
1113 /* Split into exponential part and mantissa. */
1114 y = frexpl (x, &exp);
1115 if (!(y >= 0.0L && y < 1.0L))
1121 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1123 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1124 exp -= GMP_LIMB_BITS;
1126 if (y < (1.0L / (1 << 16)))
1128 y *= 1.0L * (1 << 16);
1131 if (y < (1.0L / (1 << 8)))
1133 y *= 1.0L * (1 << 8);
1136 if (y < (1.0L / (1 << 4)))
1138 y *= 1.0L * (1 << 4);
1141 if (y < (1.0L / (1 << 2)))
1143 y *= 1.0L * (1 << 2);
1146 if (y < (1.0L / (1 << 1)))
1148 y *= 1.0L * (1 << 1);
1152 if (!(y >= 0.5L && y < 1.0L))
1154 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1157 if (z < 0.70710678118654752444)
1159 z *= 1.4142135623730950488;
1162 if (z < 0.8408964152537145431)
1164 z *= 1.1892071150027210667;
1167 if (z < 0.91700404320467123175)
1169 z *= 1.0905077326652576592;
1172 if (z < 0.9576032806985736469)
1174 z *= 1.0442737824274138403;
1177 /* Now 0.95 <= z <= 1.01. */
1179 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1180 Four terms are enough to get an approximation with error < 10^-7. */
1181 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1182 /* Finally multiply with log(2)/log(10), yields an approximation for
1184 l *= 0.30102999566398119523;
1185 /* Round down to the next integer. */
1186 return (int) l + (l < 0 ? -1 : 0);
1192 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1193 const FCHAR_T *format, va_list args)
1198 if (PRINTF_PARSE (format, &d, &a) < 0)
1199 /* errno is already set. */
1207 if (PRINTF_FETCHARGS (args, &a) < 0)
1215 size_t buf_neededlength;
1217 TCHAR_T *buf_malloced;
1221 /* Output string accumulator. */
1226 /* Allocate a small buffer that will hold a directive passed to
1227 sprintf or snprintf. */
1229 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1231 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1233 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1234 buf_malloced = NULL;
1239 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1240 if (size_overflow_p (buf_memsize))
1241 goto out_of_memory_1;
1242 buf = (TCHAR_T *) malloc (buf_memsize);
1244 goto out_of_memory_1;
1248 if (resultbuf != NULL)
1251 allocated = *lengthp;
1260 result is either == resultbuf or == NULL or malloc-allocated.
1261 If length > 0, then result != NULL. */
1263 /* Ensures that allocated >= needed. Aborts through a jump to
1264 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1265 #define ENSURE_ALLOCATION(needed) \
1266 if ((needed) > allocated) \
1268 size_t memory_size; \
1271 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1272 if ((needed) > allocated) \
1273 allocated = (needed); \
1274 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1275 if (size_overflow_p (memory_size)) \
1276 goto out_of_memory; \
1277 if (result == resultbuf || result == NULL) \
1278 memory = (DCHAR_T *) malloc (memory_size); \
1280 memory = (DCHAR_T *) realloc (result, memory_size); \
1281 if (memory == NULL) \
1282 goto out_of_memory; \
1283 if (result == resultbuf && length > 0) \
1284 DCHAR_CPY (memory, result, length); \
1288 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1290 if (cp != dp->dir_start)
1292 size_t n = dp->dir_start - cp;
1293 size_t augmented_length = xsum (length, n);
1295 ENSURE_ALLOCATION (augmented_length);
1296 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1297 need that the format string contains only ASCII characters
1298 if FCHAR_T and DCHAR_T are not the same type. */
1299 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1301 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1302 length = augmented_length;
1307 result[length++] = (unsigned char) *cp++;
1314 /* Execute a single directive. */
1315 if (dp->conversion == '%')
1317 size_t augmented_length;
1319 if (!(dp->arg_index == ARG_NONE))
1321 augmented_length = xsum (length, 1);
1322 ENSURE_ALLOCATION (augmented_length);
1323 result[length] = '%';
1324 length = augmented_length;
1328 if (!(dp->arg_index != ARG_NONE))
1331 if (dp->conversion == 'n')
1333 switch (a.arg[dp->arg_index].type)
1335 case TYPE_COUNT_SCHAR_POINTER:
1336 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1338 case TYPE_COUNT_SHORT_POINTER:
1339 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1341 case TYPE_COUNT_INT_POINTER:
1342 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1344 case TYPE_COUNT_LONGINT_POINTER:
1345 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1347 #if HAVE_LONG_LONG_INT
1348 case TYPE_COUNT_LONGLONGINT_POINTER:
1349 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1357 /* The unistdio extensions. */
1358 else if (dp->conversion == 'U')
1360 arg_type type = a.arg[dp->arg_index].type;
1361 int flags = dp->flags;
1369 if (dp->width_start != dp->width_end)
1371 if (dp->width_arg_index != ARG_NONE)
1375 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1377 arg = a.arg[dp->width_arg_index].a.a_int;
1380 /* "A negative field width is taken as a '-' flag
1381 followed by a positive field width." */
1383 width = (unsigned int) (-arg);
1390 const FCHAR_T *digitp = dp->width_start;
1393 width = xsum (xtimes (width, 10), *digitp++ - '0');
1394 while (digitp != dp->width_end);
1401 if (dp->precision_start != dp->precision_end)
1403 if (dp->precision_arg_index != ARG_NONE)
1407 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1409 arg = a.arg[dp->precision_arg_index].a.a_int;
1410 /* "A negative precision is taken as if the precision
1420 const FCHAR_T *digitp = dp->precision_start + 1;
1423 while (digitp != dp->precision_end)
1424 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1431 case TYPE_U8_STRING:
1433 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1434 const uint8_t *arg_end;
1439 /* Use only PRECISION characters, from the left. */
1442 for (; precision > 0; precision--)
1444 int count = u8_strmblen (arg_end);
1449 if (!(result == resultbuf || result == NULL))
1451 if (buf_malloced != NULL)
1452 free (buf_malloced);
1463 /* Use the entire string, and count the number of
1469 int count = u8_strmblen (arg_end);
1474 if (!(result == resultbuf || result == NULL))
1476 if (buf_malloced != NULL)
1477 free (buf_malloced);
1488 /* Use the entire string. */
1489 arg_end = arg + u8_strlen (arg);
1490 /* The number of characters doesn't matter. */
1494 if (has_width && width > characters
1495 && !(dp->flags & FLAG_LEFT))
1497 size_t n = width - characters;
1498 ENSURE_ALLOCATION (xsum (length, n));
1499 DCHAR_SET (result + length, ' ', n);
1503 # if DCHAR_IS_UINT8_T
1505 size_t n = arg_end - arg;
1506 ENSURE_ALLOCATION (xsum (length, n));
1507 DCHAR_CPY (result + length, arg, n);
1512 DCHAR_T *converted = result + length;
1513 size_t converted_len = allocated - length;
1515 /* Convert from UTF-8 to locale encoding. */
1516 if (u8_conv_to_encoding (locale_charset (),
1517 iconveh_question_mark,
1518 arg, arg_end - arg, NULL,
1519 &converted, &converted_len)
1522 /* Convert from UTF-8 to UTF-16/UTF-32. */
1524 U8_TO_DCHAR (arg, arg_end - arg,
1525 converted, &converted_len);
1526 if (converted == NULL)
1529 int saved_errno = errno;
1530 if (!(result == resultbuf || result == NULL))
1532 if (buf_malloced != NULL)
1533 free (buf_malloced);
1535 errno = saved_errno;
1538 if (converted != result + length)
1540 ENSURE_ALLOCATION (xsum (length, converted_len));
1541 DCHAR_CPY (result + length, converted, converted_len);
1544 length += converted_len;
1548 if (has_width && width > characters
1549 && (dp->flags & FLAG_LEFT))
1551 size_t n = width - characters;
1552 ENSURE_ALLOCATION (xsum (length, n));
1553 DCHAR_SET (result + length, ' ', n);
1559 case TYPE_U16_STRING:
1561 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1562 const uint16_t *arg_end;
1567 /* Use only PRECISION characters, from the left. */
1570 for (; precision > 0; precision--)
1572 int count = u16_strmblen (arg_end);
1577 if (!(result == resultbuf || result == NULL))
1579 if (buf_malloced != NULL)
1580 free (buf_malloced);
1591 /* Use the entire string, and count the number of
1597 int count = u16_strmblen (arg_end);
1602 if (!(result == resultbuf || result == NULL))
1604 if (buf_malloced != NULL)
1605 free (buf_malloced);
1616 /* Use the entire string. */
1617 arg_end = arg + u16_strlen (arg);
1618 /* The number of characters doesn't matter. */
1622 if (has_width && width > characters
1623 && !(dp->flags & FLAG_LEFT))
1625 size_t n = width - characters;
1626 ENSURE_ALLOCATION (xsum (length, n));
1627 DCHAR_SET (result + length, ' ', n);
1631 # if DCHAR_IS_UINT16_T
1633 size_t n = arg_end - arg;
1634 ENSURE_ALLOCATION (xsum (length, n));
1635 DCHAR_CPY (result + length, arg, n);
1640 DCHAR_T *converted = result + length;
1641 size_t converted_len = allocated - length;
1643 /* Convert from UTF-16 to locale encoding. */
1644 if (u16_conv_to_encoding (locale_charset (),
1645 iconveh_question_mark,
1646 arg, arg_end - arg, NULL,
1647 &converted, &converted_len)
1650 /* Convert from UTF-16 to UTF-8/UTF-32. */
1652 U16_TO_DCHAR (arg, arg_end - arg,
1653 converted, &converted_len);
1654 if (converted == NULL)
1657 int saved_errno = errno;
1658 if (!(result == resultbuf || result == NULL))
1660 if (buf_malloced != NULL)
1661 free (buf_malloced);
1663 errno = saved_errno;
1666 if (converted != result + length)
1668 ENSURE_ALLOCATION (xsum (length, converted_len));
1669 DCHAR_CPY (result + length, converted, converted_len);
1672 length += converted_len;
1676 if (has_width && width > characters
1677 && (dp->flags & FLAG_LEFT))
1679 size_t n = width - characters;
1680 ENSURE_ALLOCATION (xsum (length, n));
1681 DCHAR_SET (result + length, ' ', n);
1687 case TYPE_U32_STRING:
1689 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1690 const uint32_t *arg_end;
1695 /* Use only PRECISION characters, from the left. */
1698 for (; precision > 0; precision--)
1700 int count = u32_strmblen (arg_end);
1705 if (!(result == resultbuf || result == NULL))
1707 if (buf_malloced != NULL)
1708 free (buf_malloced);
1719 /* Use the entire string, and count the number of
1725 int count = u32_strmblen (arg_end);
1730 if (!(result == resultbuf || result == NULL))
1732 if (buf_malloced != NULL)
1733 free (buf_malloced);
1744 /* Use the entire string. */
1745 arg_end = arg + u32_strlen (arg);
1746 /* The number of characters doesn't matter. */
1750 if (has_width && width > characters
1751 && !(dp->flags & FLAG_LEFT))
1753 size_t n = width - characters;
1754 ENSURE_ALLOCATION (xsum (length, n));
1755 DCHAR_SET (result + length, ' ', n);
1759 # if DCHAR_IS_UINT32_T
1761 size_t n = arg_end - arg;
1762 ENSURE_ALLOCATION (xsum (length, n));
1763 DCHAR_CPY (result + length, arg, n);
1768 DCHAR_T *converted = result + length;
1769 size_t converted_len = allocated - length;
1771 /* Convert from UTF-32 to locale encoding. */
1772 if (u32_conv_to_encoding (locale_charset (),
1773 iconveh_question_mark,
1774 arg, arg_end - arg, NULL,
1775 &converted, &converted_len)
1778 /* Convert from UTF-32 to UTF-8/UTF-16. */
1780 U32_TO_DCHAR (arg, arg_end - arg,
1781 converted, &converted_len);
1782 if (converted == NULL)
1785 int saved_errno = errno;
1786 if (!(result == resultbuf || result == NULL))
1788 if (buf_malloced != NULL)
1789 free (buf_malloced);
1791 errno = saved_errno;
1794 if (converted != result + length)
1796 ENSURE_ALLOCATION (xsum (length, converted_len));
1797 DCHAR_CPY (result + length, converted, converted_len);
1800 length += converted_len;
1804 if (has_width && width > characters
1805 && (dp->flags & FLAG_LEFT))
1807 size_t n = width - characters;
1808 ENSURE_ALLOCATION (xsum (length, n));
1809 DCHAR_SET (result + length, ' ', n);
1820 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
1821 else if (dp->conversion == 'a' || dp->conversion == 'A')
1823 arg_type type = a.arg[dp->arg_index].type;
1824 int flags = dp->flags;
1830 DCHAR_T tmpbuf[700];
1837 if (dp->width_start != dp->width_end)
1839 if (dp->width_arg_index != ARG_NONE)
1843 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1845 arg = a.arg[dp->width_arg_index].a.a_int;
1848 /* "A negative field width is taken as a '-' flag
1849 followed by a positive field width." */
1851 width = (unsigned int) (-arg);
1858 const FCHAR_T *digitp = dp->width_start;
1861 width = xsum (xtimes (width, 10), *digitp++ - '0');
1862 while (digitp != dp->width_end);
1869 if (dp->precision_start != dp->precision_end)
1871 if (dp->precision_arg_index != ARG_NONE)
1875 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1877 arg = a.arg[dp->precision_arg_index].a.a_int;
1878 /* "A negative precision is taken as if the precision
1888 const FCHAR_T *digitp = dp->precision_start + 1;
1891 while (digitp != dp->precision_end)
1892 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1897 /* Allocate a temporary buffer of sufficient size. */
1898 if (type == TYPE_LONGDOUBLE)
1900 (unsigned int) ((LDBL_DIG + 1)
1901 * 0.831 /* decimal -> hexadecimal */
1903 + 1; /* turn floor into ceil */
1906 (unsigned int) ((DBL_DIG + 1)
1907 * 0.831 /* decimal -> hexadecimal */
1909 + 1; /* turn floor into ceil */
1910 if (tmp_length < precision)
1911 tmp_length = precision;
1912 /* Account for sign, decimal point etc. */
1913 tmp_length = xsum (tmp_length, 12);
1915 if (tmp_length < width)
1918 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1920 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
1924 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
1926 if (size_overflow_p (tmp_memsize))
1927 /* Overflow, would lead to out of memory. */
1929 tmp = (DCHAR_T *) malloc (tmp_memsize);
1931 /* Out of memory. */
1937 if (type == TYPE_LONGDOUBLE)
1939 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1943 if (dp->conversion == 'A')
1945 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1949 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1955 DECL_LONG_DOUBLE_ROUNDING
1957 BEGIN_LONG_DOUBLE_ROUNDING ();
1959 if (signbit (arg)) /* arg < 0.0L or negative zero */
1967 else if (flags & FLAG_SHOWSIGN)
1969 else if (flags & FLAG_SPACE)
1972 if (arg > 0.0L && arg + arg == arg)
1974 if (dp->conversion == 'A')
1976 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1980 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1986 long double mantissa;
1989 mantissa = printf_frexpl (arg, &exponent);
1997 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
1999 /* Round the mantissa. */
2000 long double tail = mantissa;
2003 for (q = precision; ; q--)
2005 int digit = (int) tail;
2009 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2018 for (q = precision; q > 0; q--)
2024 *p++ = dp->conversion - 'A' + 'X';
2029 digit = (int) mantissa;
2032 if ((flags & FLAG_ALT)
2033 || mantissa > 0.0L || precision > 0)
2035 *p++ = decimal_point_char ();
2036 /* This loop terminates because we assume
2037 that FLT_RADIX is a power of 2. */
2038 while (mantissa > 0.0L)
2041 digit = (int) mantissa;
2046 : dp->conversion - 10);
2050 while (precision > 0)
2057 *p++ = dp->conversion - 'A' + 'P';
2058 # if WIDE_CHAR_VERSION
2060 static const wchar_t decimal_format[] =
2061 { '%', '+', 'd', '\0' };
2062 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2067 if (sizeof (DCHAR_T) == 1)
2069 sprintf ((char *) p, "%+d", exponent);
2077 sprintf (expbuf, "%+d", exponent);
2078 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2084 END_LONG_DOUBLE_ROUNDING ();
2089 double arg = a.arg[dp->arg_index].a.a_double;
2093 if (dp->conversion == 'A')
2095 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2099 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2106 if (signbit (arg)) /* arg < 0.0 or negative zero */
2114 else if (flags & FLAG_SHOWSIGN)
2116 else if (flags & FLAG_SPACE)
2119 if (arg > 0.0 && arg + arg == arg)
2121 if (dp->conversion == 'A')
2123 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2127 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2136 mantissa = printf_frexp (arg, &exponent);
2144 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2146 /* Round the mantissa. */
2147 double tail = mantissa;
2150 for (q = precision; ; q--)
2152 int digit = (int) tail;
2156 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2165 for (q = precision; q > 0; q--)
2171 *p++ = dp->conversion - 'A' + 'X';
2176 digit = (int) mantissa;
2179 if ((flags & FLAG_ALT)
2180 || mantissa > 0.0 || precision > 0)
2182 *p++ = decimal_point_char ();
2183 /* This loop terminates because we assume
2184 that FLT_RADIX is a power of 2. */
2185 while (mantissa > 0.0)
2188 digit = (int) mantissa;
2193 : dp->conversion - 10);
2197 while (precision > 0)
2204 *p++ = dp->conversion - 'A' + 'P';
2205 # if WIDE_CHAR_VERSION
2207 static const wchar_t decimal_format[] =
2208 { '%', '+', 'd', '\0' };
2209 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2214 if (sizeof (DCHAR_T) == 1)
2216 sprintf ((char *) p, "%+d", exponent);
2224 sprintf (expbuf, "%+d", exponent);
2225 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2232 /* The generated string now extends from tmp to p, with the
2233 zero padding insertion point being at pad_ptr. */
2234 if (has_width && p - tmp < width)
2236 size_t pad = width - (p - tmp);
2237 DCHAR_T *end = p + pad;
2239 if (flags & FLAG_LEFT)
2241 /* Pad with spaces on the right. */
2242 for (; pad > 0; pad--)
2245 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2247 /* Pad with zeroes. */
2252 for (; pad > 0; pad--)
2257 /* Pad with spaces on the left. */
2262 for (; pad > 0; pad--)
2270 size_t count = p - tmp;
2272 if (count >= tmp_length)
2273 /* tmp_length was incorrectly calculated - fix the
2277 /* Make room for the result. */
2278 if (count >= allocated - length)
2280 size_t n = xsum (length, count);
2282 ENSURE_ALLOCATION (n);
2285 /* Append the result. */
2286 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2293 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2294 else if ((dp->conversion == 'f' || dp->conversion == 'F'
2295 || dp->conversion == 'e' || dp->conversion == 'E'
2296 || dp->conversion == 'g' || dp->conversion == 'G'
2297 || dp->conversion == 'a' || dp->conversion == 'A')
2299 # if NEED_PRINTF_INFINITE_DOUBLE
2300 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2301 /* The systems (mingw) which produce wrong output
2302 for Inf, -Inf, and NaN also do so for -0.0.
2303 Therefore we treat this case here as well. */
2304 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2306 # if NEED_PRINTF_LONG_DOUBLE
2307 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2308 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2309 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2310 /* Some systems produce wrong output for Inf,
2312 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
2316 # if NEED_PRINTF_INFINITE_DOUBLE && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2317 arg_type type = a.arg[dp->arg_index].type;
2319 int flags = dp->flags;
2325 DCHAR_T tmpbuf[700];
2332 if (dp->width_start != dp->width_end)
2334 if (dp->width_arg_index != ARG_NONE)
2338 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2340 arg = a.arg[dp->width_arg_index].a.a_int;
2343 /* "A negative field width is taken as a '-' flag
2344 followed by a positive field width." */
2346 width = (unsigned int) (-arg);
2353 const FCHAR_T *digitp = dp->width_start;
2356 width = xsum (xtimes (width, 10), *digitp++ - '0');
2357 while (digitp != dp->width_end);
2364 if (dp->precision_start != dp->precision_end)
2366 if (dp->precision_arg_index != ARG_NONE)
2370 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2372 arg = a.arg[dp->precision_arg_index].a.a_int;
2373 /* "A negative precision is taken as if the precision
2383 const FCHAR_T *digitp = dp->precision_start + 1;
2386 while (digitp != dp->precision_end)
2387 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2392 /* POSIX specifies the default precision to be 6 for %f, %F,
2393 %e, %E, but not for %g, %G. Implementations appear to use
2394 the same default precision also for %g, %G. */
2398 /* Allocate a temporary buffer of sufficient size. */
2399 # if NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2400 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2401 # elif NEED_PRINTF_LONG_DOUBLE
2402 tmp_length = LDBL_DIG + 1;
2406 if (tmp_length < precision)
2407 tmp_length = precision;
2408 # if NEED_PRINTF_LONG_DOUBLE
2409 # if NEED_PRINTF_INFINITE_DOUBLE
2410 if (type == TYPE_LONGDOUBLE)
2412 if (dp->conversion == 'f' || dp->conversion == 'F')
2414 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2415 if (!(isnanl (arg) || arg + arg == arg))
2417 /* arg is finite and nonzero. */
2418 int exponent = floorlog10l (arg < 0 ? -arg : arg);
2419 if (exponent >= 0 && tmp_length < exponent + precision)
2420 tmp_length = exponent + precision;
2424 /* Account for sign, decimal point etc. */
2425 tmp_length = xsum (tmp_length, 12);
2427 if (tmp_length < width)
2430 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2432 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2436 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2438 if (size_overflow_p (tmp_memsize))
2439 /* Overflow, would lead to out of memory. */
2441 tmp = (DCHAR_T *) malloc (tmp_memsize);
2443 /* Out of memory. */
2450 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2451 # if NEED_PRINTF_INFINITE_DOUBLE
2452 if (type == TYPE_LONGDOUBLE)
2455 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2459 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2461 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2465 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2471 DECL_LONG_DOUBLE_ROUNDING
2473 BEGIN_LONG_DOUBLE_ROUNDING ();
2475 if (signbit (arg)) /* arg < 0.0L or negative zero */
2483 else if (flags & FLAG_SHOWSIGN)
2485 else if (flags & FLAG_SPACE)
2488 if (arg > 0.0L && arg + arg == arg)
2490 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2492 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2496 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2501 # if NEED_PRINTF_LONG_DOUBLE
2504 if (dp->conversion == 'f' || dp->conversion == 'F')
2510 scale10_round_decimal_long_double (arg, precision);
2513 END_LONG_DOUBLE_ROUNDING ();
2516 ndigits = strlen (digits);
2518 if (ndigits > precision)
2522 *p++ = digits[ndigits];
2524 while (ndigits > precision);
2527 /* Here ndigits <= precision. */
2528 if ((flags & FLAG_ALT) || precision > 0)
2530 *p++ = decimal_point_char ();
2531 for (; precision > ndigits; precision--)
2536 *p++ = digits[ndigits];
2542 else if (dp->conversion == 'e' || dp->conversion == 'E')
2550 if ((flags & FLAG_ALT) || precision > 0)
2552 *p++ = decimal_point_char ();
2553 for (; precision > 0; precision--)
2564 exponent = floorlog10l (arg);
2569 scale10_round_decimal_long_double (arg,
2570 (int)precision - exponent);
2573 END_LONG_DOUBLE_ROUNDING ();
2576 ndigits = strlen (digits);
2578 if (ndigits == precision + 1)
2580 if (ndigits < precision
2581 || ndigits > precision + 2)
2582 /* The exponent was not guessed
2583 precisely enough. */
2586 /* None of two values of exponent is
2587 the right one. Prevent an endless
2591 if (ndigits == precision)
2598 /* Here ndigits = precision+1. */
2599 *p++ = digits[--ndigits];
2600 if ((flags & FLAG_ALT) || precision > 0)
2602 *p++ = decimal_point_char ();
2606 *p++ = digits[ndigits];
2613 *p++ = dp->conversion; /* 'e' or 'E' */
2614 # if WIDE_CHAR_VERSION
2616 static const wchar_t decimal_format[] =
2617 { '%', '+', '.', '2', 'd', '\0' };
2618 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2623 if (sizeof (DCHAR_T) == 1)
2625 sprintf ((char *) p, "%+.2d", exponent);
2633 sprintf (expbuf, "%+.2d", exponent);
2634 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2639 else if (dp->conversion == 'g' || dp->conversion == 'G')
2643 /* precision >= 1. */
2646 /* The exponent is 0, >= -4, < precision.
2647 Use fixed-point notation. */
2649 size_t ndigits = precision;
2650 /* Number of trailing zeroes that have to be
2653 (flags & FLAG_ALT ? 0 : precision - 1);
2657 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2659 *p++ = decimal_point_char ();
2660 while (ndigits > nzeroes)
2676 exponent = floorlog10l (arg);
2681 scale10_round_decimal_long_double (arg,
2682 (int)(precision - 1) - exponent);
2685 END_LONG_DOUBLE_ROUNDING ();
2688 ndigits = strlen (digits);
2690 if (ndigits == precision)
2692 if (ndigits < precision - 1
2693 || ndigits > precision + 1)
2694 /* The exponent was not guessed
2695 precisely enough. */
2698 /* None of two values of exponent is
2699 the right one. Prevent an endless
2703 if (ndigits < precision)
2709 /* Here ndigits = precision. */
2711 /* Determine the number of trailing zeroes
2712 that have to be dropped. */
2714 if ((flags & FLAG_ALT) == 0)
2715 while (nzeroes < ndigits
2716 && digits[nzeroes] == '0')
2719 /* The exponent is now determined. */
2721 && exponent < (long)precision)
2723 /* Fixed-point notation:
2724 max(exponent,0)+1 digits, then the
2725 decimal point, then the remaining
2726 digits without trailing zeroes. */
2729 size_t count = exponent + 1;
2730 /* Note: count <= precision = ndigits. */
2731 for (; count > 0; count--)
2732 *p++ = digits[--ndigits];
2733 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2735 *p++ = decimal_point_char ();
2736 while (ndigits > nzeroes)
2739 *p++ = digits[ndigits];
2745 size_t count = -exponent - 1;
2747 *p++ = decimal_point_char ();
2748 for (; count > 0; count--)
2750 while (ndigits > nzeroes)
2753 *p++ = digits[ndigits];
2759 /* Exponential notation. */
2760 *p++ = digits[--ndigits];
2761 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2763 *p++ = decimal_point_char ();
2764 while (ndigits > nzeroes)
2767 *p++ = digits[ndigits];
2770 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
2771 # if WIDE_CHAR_VERSION
2773 static const wchar_t decimal_format[] =
2774 { '%', '+', '.', '2', 'd', '\0' };
2775 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2780 if (sizeof (DCHAR_T) == 1)
2782 sprintf ((char *) p, "%+.2d", exponent);
2790 sprintf (expbuf, "%+.2d", exponent);
2791 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2803 /* arg is finite. */
2808 END_LONG_DOUBLE_ROUNDING ();
2811 # if NEED_PRINTF_INFINITE_DOUBLE
2815 # if NEED_PRINTF_INFINITE_DOUBLE
2817 /* Simpler than above: handle only NaN, Infinity, zero. */
2818 double arg = a.arg[dp->arg_index].a.a_double;
2822 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2824 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2828 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2835 if (signbit (arg)) /* arg < 0.0L or negative zero */
2843 else if (flags & FLAG_SHOWSIGN)
2845 else if (flags & FLAG_SPACE)
2848 if (arg > 0.0 && arg + arg == arg)
2850 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2852 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2856 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2866 if (dp->conversion == 'f' || dp->conversion == 'F')
2869 if ((flags & FLAG_ALT) || precision > 0)
2871 *p++ = decimal_point_char ();
2872 for (; precision > 0; precision--)
2876 else if (dp->conversion == 'e' || dp->conversion == 'E')
2879 if ((flags & FLAG_ALT) || precision > 0)
2881 *p++ = decimal_point_char ();
2882 for (; precision > 0; precision--)
2885 *p++ = dp->conversion; /* 'e' or 'E' */
2887 /* Produce the same number of exponent digits as
2888 the native printf implementation. */
2889 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2895 else if (dp->conversion == 'g' || dp->conversion == 'G')
2898 if (flags & FLAG_ALT)
2901 (precision > 0 ? precision - 1 : 0);
2902 *p++ = decimal_point_char ();
2903 for (; ndigits > 0; --ndigits)
2914 /* The generated string now extends from tmp to p, with the
2915 zero padding insertion point being at pad_ptr. */
2916 if (has_width && p - tmp < width)
2918 size_t pad = width - (p - tmp);
2919 DCHAR_T *end = p + pad;
2921 if (flags & FLAG_LEFT)
2923 /* Pad with spaces on the right. */
2924 for (; pad > 0; pad--)
2927 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2929 /* Pad with zeroes. */
2934 for (; pad > 0; pad--)
2939 /* Pad with spaces on the left. */
2944 for (; pad > 0; pad--)
2952 size_t count = p - tmp;
2954 if (count >= tmp_length)
2955 /* tmp_length was incorrectly calculated - fix the
2959 /* Make room for the result. */
2960 if (count >= allocated - length)
2962 size_t n = xsum (length, count);
2964 ENSURE_ALLOCATION (n);
2967 /* Append the result. */
2968 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2977 arg_type type = a.arg[dp->arg_index].type;
2978 int flags = dp->flags;
2979 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO
2983 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO
2986 # define pad_ourselves 0
2989 unsigned int prefix_count;
2993 TCHAR_T tmpbuf[700];
2997 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO
3000 if (dp->width_start != dp->width_end)
3002 if (dp->width_arg_index != ARG_NONE)
3006 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3008 arg = a.arg[dp->width_arg_index].a.a_int;
3011 /* "A negative field width is taken as a '-' flag
3012 followed by a positive field width." */
3014 width = (unsigned int) (-arg);
3021 const FCHAR_T *digitp = dp->width_start;
3024 width = xsum (xtimes (width, 10), *digitp++ - '0');
3025 while (digitp != dp->width_end);
3032 /* Allocate a temporary buffer of sufficient size for calling
3038 if (dp->precision_start != dp->precision_end)
3040 if (dp->precision_arg_index != ARG_NONE)
3044 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3046 arg = a.arg[dp->precision_arg_index].a.a_int;
3047 precision = (arg < 0 ? 0 : arg);
3051 const FCHAR_T *digitp = dp->precision_start + 1;
3054 while (digitp != dp->precision_end)
3055 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3059 switch (dp->conversion)
3062 case 'd': case 'i': case 'u':
3063 # if HAVE_LONG_LONG_INT
3064 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3066 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3067 * 0.30103 /* binary -> decimal */
3069 + 1; /* turn floor into ceil */
3072 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3074 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3075 * 0.30103 /* binary -> decimal */
3077 + 1; /* turn floor into ceil */
3080 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3081 * 0.30103 /* binary -> decimal */
3083 + 1; /* turn floor into ceil */
3084 if (tmp_length < precision)
3085 tmp_length = precision;
3086 /* Multiply by 2, as an estimate for FLAG_GROUP. */
3087 tmp_length = xsum (tmp_length, tmp_length);
3088 /* Add 1, to account for a leading sign. */
3089 tmp_length = xsum (tmp_length, 1);
3093 # if HAVE_LONG_LONG_INT
3094 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3096 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3097 * 0.333334 /* binary -> octal */
3099 + 1; /* turn floor into ceil */
3102 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3104 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3105 * 0.333334 /* binary -> octal */
3107 + 1; /* turn floor into ceil */
3110 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3111 * 0.333334 /* binary -> octal */
3113 + 1; /* turn floor into ceil */
3114 if (tmp_length < precision)
3115 tmp_length = precision;
3116 /* Add 1, to account for a leading sign. */
3117 tmp_length = xsum (tmp_length, 1);
3121 # if HAVE_LONG_LONG_INT
3122 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3124 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3125 * 0.25 /* binary -> hexadecimal */
3127 + 1; /* turn floor into ceil */
3130 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3132 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3133 * 0.25 /* binary -> hexadecimal */
3135 + 1; /* turn floor into ceil */
3138 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3139 * 0.25 /* binary -> hexadecimal */
3141 + 1; /* turn floor into ceil */
3142 if (tmp_length < precision)
3143 tmp_length = precision;
3144 /* Add 2, to account for a leading sign or alternate form. */
3145 tmp_length = xsum (tmp_length, 2);
3149 if (type == TYPE_LONGDOUBLE)
3151 (unsigned int) (LDBL_MAX_EXP
3152 * 0.30103 /* binary -> decimal */
3153 * 2 /* estimate for FLAG_GROUP */
3155 + 1 /* turn floor into ceil */
3156 + 10; /* sign, decimal point etc. */
3159 (unsigned int) (DBL_MAX_EXP
3160 * 0.30103 /* binary -> decimal */
3161 * 2 /* estimate for FLAG_GROUP */
3163 + 1 /* turn floor into ceil */
3164 + 10; /* sign, decimal point etc. */
3165 tmp_length = xsum (tmp_length, precision);
3168 case 'e': case 'E': case 'g': case 'G':
3170 12; /* sign, decimal point, exponent etc. */
3171 tmp_length = xsum (tmp_length, precision);
3175 if (type == TYPE_LONGDOUBLE)
3177 (unsigned int) (LDBL_DIG
3178 * 0.831 /* decimal -> hexadecimal */
3180 + 1; /* turn floor into ceil */
3183 (unsigned int) (DBL_DIG
3184 * 0.831 /* decimal -> hexadecimal */
3186 + 1; /* turn floor into ceil */
3187 if (tmp_length < precision)
3188 tmp_length = precision;
3189 /* Account for sign, decimal point etc. */
3190 tmp_length = xsum (tmp_length, 12);
3194 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
3195 if (type == TYPE_WIDE_CHAR)
3196 tmp_length = MB_CUR_MAX;
3204 if (type == TYPE_WIDE_STRING)
3207 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
3209 # if !WIDE_CHAR_VERSION
3210 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
3215 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
3220 (unsigned int) (sizeof (void *) * CHAR_BIT
3221 * 0.25 /* binary -> hexadecimal */
3223 + 1 /* turn floor into ceil */
3224 + 2; /* account for leading 0x */
3231 # if ENABLE_UNISTDIO
3232 /* Padding considers the number of characters, therefore the
3233 number of elements after padding may be
3234 > max (tmp_length, width)
3236 <= tmp_length + width. */
3237 tmp_length = xsum (tmp_length, width);
3239 /* Padding considers the number of elements, says POSIX. */
3240 if (tmp_length < width)
3244 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3247 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
3251 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
3253 if (size_overflow_p (tmp_memsize))
3254 /* Overflow, would lead to out of memory. */
3256 tmp = (TCHAR_T *) malloc (tmp_memsize);
3258 /* Out of memory. */
3263 /* Decide whether to perform the padding ourselves. */
3264 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO
3265 switch (dp->conversion)
3267 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
3268 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
3269 to perform the padding after this conversion. Functions
3270 with unistdio extensions perform the padding based on
3271 character count rather than element count. */
3274 # if NEED_PRINTF_FLAG_ZERO
3275 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
3286 /* Construct the format string for calling snprintf or
3290 #if NEED_PRINTF_FLAG_GROUPING
3291 /* The underlying implementation doesn't support the ' flag.
3292 Produce no grouping characters in this case; this is
3293 acceptable because the grouping is locale dependent. */
3295 if (flags & FLAG_GROUP)
3298 if (flags & FLAG_LEFT)
3300 if (flags & FLAG_SHOWSIGN)
3302 if (flags & FLAG_SPACE)
3304 if (flags & FLAG_ALT)
3308 if (flags & FLAG_ZERO)
3310 if (dp->width_start != dp->width_end)
3312 size_t n = dp->width_end - dp->width_start;
3313 /* The width specification is known to consist only
3314 of standard ASCII characters. */
3315 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
3317 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
3322 const FCHAR_T *mp = dp->width_start;
3324 *fbp++ = (unsigned char) *mp++;
3329 if (dp->precision_start != dp->precision_end)
3331 size_t n = dp->precision_end - dp->precision_start;
3332 /* The precision specification is known to consist only
3333 of standard ASCII characters. */
3334 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
3336 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
3341 const FCHAR_T *mp = dp->precision_start;
3343 *fbp++ = (unsigned char) *mp++;
3350 #if HAVE_LONG_LONG_INT
3351 case TYPE_LONGLONGINT:
3352 case TYPE_ULONGLONGINT:
3353 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3366 case TYPE_WIDE_CHAR:
3369 case TYPE_WIDE_STRING:
3373 case TYPE_LONGDOUBLE:
3379 #if NEED_PRINTF_DIRECTIVE_F
3380 if (dp->conversion == 'F')
3384 *fbp = dp->conversion;
3386 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3))
3391 /* On glibc2 systems from glibc >= 2.3 - probably also older
3392 ones - we know that snprintf's returns value conforms to
3393 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
3394 Therefore we can avoid using %n in this situation.
3395 On glibc2 systems from 2004-10-18 or newer, the use of %n
3396 in format strings in writable memory may crash the program
3397 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
3398 in this situation. */
3405 /* Construct the arguments for calling snprintf or sprintf. */
3407 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
3409 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3411 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
3413 if (dp->precision_arg_index != ARG_NONE)
3415 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3417 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
3421 /* The SNPRINTF result is appended after result[0..length].
3422 The latter is an array of DCHAR_T; SNPRINTF appends an
3423 array of TCHAR_T to it. This is possible because
3424 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
3425 alignof (TCHAR_T) <= alignof (DCHAR_T). */
3426 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
3427 /* Prepare checking whether snprintf returns the count
3429 ENSURE_ALLOCATION (xsum (length, 1));
3430 *(TCHAR_T *) (result + length) = '\0';
3439 size_t maxlen = allocated - length;
3440 /* SNPRINTF can fail if its second argument is
3442 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
3443 maxlen = INT_MAX / TCHARS_PER_DCHAR;
3444 maxlen = maxlen * TCHARS_PER_DCHAR;
3445 # define SNPRINTF_BUF(arg) \
3446 switch (prefix_count) \
3449 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
3454 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
3456 prefixes[0], arg, &count); \
3459 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
3461 prefixes[0], prefixes[1], arg, \
3468 # define SNPRINTF_BUF(arg) \
3469 switch (prefix_count) \
3472 count = sprintf (tmp, buf, arg); \
3475 count = sprintf (tmp, buf, prefixes[0], arg); \
3478 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
3490 int arg = a.arg[dp->arg_index].a.a_schar;
3496 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
3502 int arg = a.arg[dp->arg_index].a.a_short;
3508 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
3514 int arg = a.arg[dp->arg_index].a.a_int;
3520 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
3526 long int arg = a.arg[dp->arg_index].a.a_longint;
3532 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
3536 #if HAVE_LONG_LONG_INT
3537 case TYPE_LONGLONGINT:
3539 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
3543 case TYPE_ULONGLONGINT:
3545 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
3552 double arg = a.arg[dp->arg_index].a.a_double;
3556 case TYPE_LONGDOUBLE:
3558 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3564 int arg = a.arg[dp->arg_index].a.a_char;
3569 case TYPE_WIDE_CHAR:
3571 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
3578 const char *arg = a.arg[dp->arg_index].a.a_string;
3583 case TYPE_WIDE_STRING:
3585 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
3592 void *arg = a.arg[dp->arg_index].a.a_pointer;
3601 /* Portability: Not all implementations of snprintf()
3602 are ISO C 99 compliant. Determine the number of
3603 bytes that snprintf() has produced or would have
3607 /* Verify that snprintf() has NUL-terminated its
3610 && ((TCHAR_T *) (result + length)) [count] != '\0')
3612 /* Portability hack. */
3613 if (retcount > count)
3618 /* snprintf() doesn't understand the '%n'
3622 /* Don't use the '%n' directive; instead, look
3623 at the snprintf() return value. */
3629 /* Look at the snprintf() return value. */
3632 /* HP-UX 10.20 snprintf() is doubly deficient:
3633 It doesn't understand the '%n' directive,
3634 *and* it returns -1 (rather than the length
3635 that would have been required) when the
3636 buffer is too small. */
3637 size_t bigger_need =
3638 xsum (xtimes (allocated, 2), 12);
3639 ENSURE_ALLOCATION (bigger_need);
3648 /* Attempt to handle failure. */
3651 if (!(result == resultbuf || result == NULL))
3653 if (buf_malloced != NULL)
3654 free (buf_malloced);
3661 /* Handle overflow of the allocated buffer.
3662 If such an overflow occurs, a C99 compliant snprintf()
3663 returns a count >= maxlen. However, a non-compliant
3664 snprintf() function returns only count = maxlen - 1. To
3665 cover both cases, test whether count >= maxlen - 1. */
3666 if ((unsigned int) count + 1 >= maxlen)
3668 /* If maxlen already has attained its allowed maximum,
3669 allocating more memory will not increase maxlen.
3670 Instead of looping, bail out. */
3671 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
3675 /* Need at least count * sizeof (TCHAR_T) bytes.
3676 But allocate proportionally, to avoid looping
3677 eternally if snprintf() reports a too small
3681 (count + TCHARS_PER_DCHAR - 1)
3682 / TCHARS_PER_DCHAR),
3683 xtimes (allocated, 2));
3685 ENSURE_ALLOCATION (n);
3693 if (count >= tmp_length)
3694 /* tmp_length was incorrectly calculated - fix the
3699 /* Convert from TCHAR_T[] to DCHAR_T[]. */
3700 if (dp->conversion == 'c' || dp->conversion == 's')
3702 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
3704 The result string is not certainly ASCII. */
3705 const TCHAR_T *tmpsrc;
3708 /* This code assumes that TCHAR_T is 'char'. */
3709 typedef int TCHAR_T_verify
3710 [2 * (sizeof (TCHAR_T) == 1) - 1];
3712 tmpsrc = (TCHAR_T *) (result + length);
3718 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
3719 iconveh_question_mark,
3722 &tmpdst, &tmpdst_len)
3725 int saved_errno = errno;
3726 if (!(result == resultbuf || result == NULL))
3728 if (buf_malloced != NULL)
3729 free (buf_malloced);
3731 errno = saved_errno;
3734 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
3735 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
3741 /* The result string is ASCII.
3742 Simple 1:1 conversion. */
3744 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
3745 no-op conversion, in-place on the array starting
3746 at (result + length). */
3747 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
3750 const TCHAR_T *tmpsrc;
3755 if (result == resultbuf)
3757 tmpsrc = (TCHAR_T *) (result + length);
3758 /* ENSURE_ALLOCATION will not move tmpsrc
3759 (because it's part of resultbuf). */
3760 ENSURE_ALLOCATION (xsum (length, count));
3764 /* ENSURE_ALLOCATION will move the array
3765 (because it uses realloc(). */
3766 ENSURE_ALLOCATION (xsum (length, count));
3767 tmpsrc = (TCHAR_T *) (result + length);
3771 ENSURE_ALLOCATION (xsum (length, count));
3773 tmpdst = result + length;
3774 /* Copy backwards, because of overlapping. */
3777 for (n = count; n > 0; n--)
3778 *--tmpdst = (unsigned char) *--tmpsrc;
3783 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
3784 /* Make room for the result. */
3785 if (count > allocated - length)
3787 /* Need at least count elements. But allocate
3790 xmax (xsum (length, count), xtimes (allocated, 2));
3792 ENSURE_ALLOCATION (n);
3796 /* Here count <= allocated - length. */
3798 /* Perform padding. */
3799 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO
3800 if (pad_ourselves && has_width)
3803 # if ENABLE_UNISTDIO
3804 /* Outside POSIX, it's preferrable to compare the width
3805 against the number of _characters_ of the converted
3807 w = DCHAR_MBSNLEN (result + length, count);
3809 /* The width is compared against the number of _bytes_
3810 of the converted value, says POSIX. */
3815 size_t pad = width - w;
3817 /* Make room for the result. */
3818 if (xsum (count, pad) > allocated - length)
3820 /* Need at least count + pad elements. But
3821 allocate proportionally. */
3823 xmax (xsum3 (length, count, pad),
3824 xtimes (allocated, 2));
3827 ENSURE_ALLOCATION (n);
3830 /* Here count + pad <= allocated - length. */
3833 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
3834 DCHAR_T * const rp = result + length;
3836 DCHAR_T * const rp = tmp;
3838 DCHAR_T *p = rp + count;
3839 DCHAR_T *end = p + pad;
3840 # if NEED_PRINTF_FLAG_ZERO
3842 # if !DCHAR_IS_TCHAR
3843 if (dp->conversion == 'c'
3844 || dp->conversion == 's')
3845 /* No zero-padding for string directives. */
3850 pad_ptr = (*rp == '-' ? rp + 1 : rp);
3851 /* No zero-padding of "inf" and "nan". */
3852 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
3853 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
3857 /* The generated string now extends from rp to p,
3858 with the zero padding insertion point being at
3861 count = count + pad; /* = end - rp */
3863 if (flags & FLAG_LEFT)
3865 /* Pad with spaces on the right. */
3866 for (; pad > 0; pad--)
3869 # if NEED_PRINTF_FLAG_ZERO
3870 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3872 /* Pad with zeroes. */
3877 for (; pad > 0; pad--)
3883 /* Pad with spaces on the left. */
3888 for (; pad > 0; pad--)
3896 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
3897 if (count >= tmp_length)
3898 /* tmp_length was incorrectly calculated - fix the
3903 /* Here still count <= allocated - length. */
3905 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
3906 /* The snprintf() result did fit. */
3908 /* Append the sprintf() result. */
3909 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3916 #if NEED_PRINTF_DIRECTIVE_F
3917 if (dp->conversion == 'F')
3919 /* Convert the %f result to upper case for %F. */
3920 DCHAR_T *rp = result + length;
3922 for (rc = count; rc > 0; rc--, rp++)
3923 if (*rp >= 'a' && *rp <= 'z')
3924 *rp = *rp - 'a' + 'A';
3935 /* Add the final NUL. */
3936 ENSURE_ALLOCATION (xsum (length, 1));
3937 result[length] = '\0';
3939 if (result != resultbuf && length + 1 < allocated)
3941 /* Shrink the allocated memory if possible. */
3944 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
3949 if (buf_malloced != NULL)
3950 free (buf_malloced);
3953 /* Note that we can produce a big string of a length > INT_MAX. POSIX
3954 says that snprintf() fails with errno = EOVERFLOW in this case, but
3955 that's only because snprintf() returns an 'int'. This function does
3956 not have this limitation. */
3960 if (!(result == resultbuf || result == NULL))
3962 if (buf_malloced != NULL)
3963 free (buf_malloced);
3969 if (!(result == resultbuf || result == NULL))
3971 if (buf_malloced != NULL)
3972 free (buf_malloced);
3980 #undef TCHARS_PER_DCHAR