1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2008 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* This file can be parametrized with the following macros:
19 VASNPRINTF The name of the function being defined.
20 FCHAR_T The element type of the format string.
21 DCHAR_T The element type of the destination (result) string.
22 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
23 in the format string are ASCII. MUST be set if
24 FCHAR_T and DCHAR_T are not the same type.
25 DIRECTIVE Structure denoting a format directive.
27 DIRECTIVES Structure denoting the set of format directives of a
28 format string. Depends on FCHAR_T.
29 PRINTF_PARSE Function that parses a format string.
31 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
32 DCHAR_SET memset like function for DCHAR_T[] arrays.
33 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
34 SNPRINTF The system's snprintf (or similar) function.
35 This may be either snprintf or swprintf.
36 TCHAR_T The element type of the argument and result string
37 of the said SNPRINTF function. This may be either
38 char or wchar_t. The code exploits that
39 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
40 alignof (TCHAR_T) <= alignof (DCHAR_T).
41 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
42 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
43 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
44 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
45 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
47 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
48 This must come before <config.h> because <config.h> may include
49 <features.h>, and once <features.h> has been included, it's too late. */
51 # define _GNU_SOURCE 1
63 # if WIDE_CHAR_VERSION
64 # include "vasnwprintf.h"
66 # include "vasnprintf.h"
70 #include <locale.h> /* localeconv() */
71 #include <stdio.h> /* snprintf(), sprintf() */
72 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
73 #include <string.h> /* memcpy(), strlen() */
74 #include <errno.h> /* errno */
75 #include <limits.h> /* CHAR_BIT */
76 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
78 # include <langinfo.h>
81 # if WIDE_CHAR_VERSION
82 # include "wprintf-parse.h"
84 # include "printf-parse.h"
88 /* Checked size_t computations. */
91 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
96 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
101 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
103 # include "isnanl-nolibm.h"
107 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
110 # include "printf-frexp.h"
113 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
115 # include "isnanl-nolibm.h"
116 # include "printf-frexpl.h"
122 # define local_wcslen wcslen
124 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
125 a dependency towards this library, here is a local substitute.
126 Define this substitute only once, even if this file is included
127 twice in the same compilation unit. */
128 # ifndef local_wcslen_defined
129 # define local_wcslen_defined 1
131 local_wcslen (const wchar_t *s)
135 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
143 /* Default parameters. */
145 # if WIDE_CHAR_VERSION
146 # define VASNPRINTF vasnwprintf
147 # define FCHAR_T wchar_t
148 # define DCHAR_T wchar_t
149 # define TCHAR_T wchar_t
150 # define DCHAR_IS_TCHAR 1
151 # define DIRECTIVE wchar_t_directive
152 # define DIRECTIVES wchar_t_directives
153 # define PRINTF_PARSE wprintf_parse
154 # define DCHAR_CPY wmemcpy
156 # define VASNPRINTF vasnprintf
157 # define FCHAR_T char
158 # define DCHAR_T char
159 # define TCHAR_T char
160 # define DCHAR_IS_TCHAR 1
161 # define DIRECTIVE char_directive
162 # define DIRECTIVES char_directives
163 # define PRINTF_PARSE printf_parse
164 # define DCHAR_CPY memcpy
167 #if WIDE_CHAR_VERSION
168 /* TCHAR_T is wchar_t. */
169 # define USE_SNPRINTF 1
170 # if HAVE_DECL__SNWPRINTF
171 /* On Windows, the function swprintf() has a different signature than
172 on Unix; we use the _snwprintf() function instead. */
173 # define SNPRINTF _snwprintf
176 # define SNPRINTF swprintf
179 /* TCHAR_T is char. */
180 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
181 But don't use it on BeOS, since BeOS snprintf produces no output if the
182 size argument is >= 0x3000000.
183 Also don't use it on Linux libc5, since there snprintf with size = 1
184 writes any output without bounds, like sprintf. */
185 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
186 # define USE_SNPRINTF 1
188 # define USE_SNPRINTF 0
190 # if HAVE_DECL__SNPRINTF
192 # define SNPRINTF _snprintf
195 # define SNPRINTF snprintf
196 /* Here we need to call the native snprintf, not rpl_snprintf. */
200 /* Here we need to call the native sprintf, not rpl_sprintf. */
203 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_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 && !NEED_PRINTF_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 isnand (x) || x + x == x;
241 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_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 || NEED_PRINTF_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 # if NEED_PRINTF_LONG_DOUBLE
800 /* Assuming x is finite and >= 0:
801 write x as x = 2^e * m, where m is a bignum.
802 Return the allocated memory in case of success, NULL in case of memory
803 allocation failure. */
805 decode_long_double (long double x, int *ep, mpn_t *mp)
812 /* Allocate memory for result. */
813 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
814 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
817 /* Split into exponential part and mantissa. */
818 y = frexpl (x, &exp);
819 if (!(y >= 0.0L && y < 1.0L))
821 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
822 latter is an integer. */
823 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
824 I'm not sure whether it's safe to cast a 'long double' value between
825 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
826 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
828 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
829 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
832 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
835 if (!(y >= 0.0L && y < 1.0L))
837 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
840 if (!(y >= 0.0L && y < 1.0L))
842 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
847 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
850 if (!(y >= 0.0L && y < 1.0L))
852 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
856 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
859 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
862 if (!(y >= 0.0L && y < 1.0L))
864 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
867 if (!(y >= 0.0L && y < 1.0L))
869 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
871 #if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
877 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
880 *ep = exp - LDBL_MANT_BIT;
886 # if NEED_PRINTF_DOUBLE
888 /* Assuming x is finite and >= 0:
889 write x as x = 2^e * m, where m is a bignum.
890 Return the allocated memory in case of success, NULL in case of memory
891 allocation failure. */
893 decode_double (double x, int *ep, mpn_t *mp)
900 /* Allocate memory for result. */
901 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
902 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
905 /* Split into exponential part and mantissa. */
907 if (!(y >= 0.0 && y < 1.0))
909 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
910 latter is an integer. */
911 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
912 I'm not sure whether it's safe to cast a 'double' value between
913 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
914 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
916 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
917 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
920 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
923 if (!(y >= 0.0 && y < 1.0))
925 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
928 if (!(y >= 0.0 && y < 1.0))
930 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
935 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
938 if (!(y >= 0.0 && y < 1.0))
940 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
944 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
947 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
950 if (!(y >= 0.0 && y < 1.0))
952 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
955 if (!(y >= 0.0 && y < 1.0))
957 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
962 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
965 *ep = exp - DBL_MANT_BIT;
971 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
972 Returns the decimal representation of round (x * 10^n).
973 Return the allocated memory - containing the decimal digits in low-to-high
974 order, terminated with a NUL character - in case of success, NULL in case
975 of memory allocation failure. */
977 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
985 unsigned int s_limbs;
994 /* x = 2^e * m, hence
995 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
996 = round (2^s * 5^n * m). */
999 /* Factor out a common power of 10 if possible. */
1002 extra_zeroes = (s < n ? s : n);
1006 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1007 Before converting to decimal, we need to compute
1008 z = round (2^s * 5^n * m). */
1009 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1010 sign. 2.322 is slightly larger than log(5)/log(2). */
1011 abs_n = (n >= 0 ? n : -n);
1012 abs_s = (s >= 0 ? s : -s);
1013 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1014 + abs_s / GMP_LIMB_BITS + 1)
1015 * sizeof (mp_limb_t));
1016 if (pow5_ptr == NULL)
1021 /* Initialize with 1. */
1024 /* Multiply with 5^|n|. */
1027 static mp_limb_t const small_pow5[13 + 1] =
1029 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1030 48828125, 244140625, 1220703125
1033 for (n13 = 0; n13 <= abs_n; n13 += 13)
1035 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1037 mp_twolimb_t carry = 0;
1038 for (j = 0; j < pow5_len; j++)
1040 mp_limb_t digit2 = pow5_ptr[j];
1041 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1042 pow5_ptr[j] = (mp_limb_t) carry;
1043 carry = carry >> GMP_LIMB_BITS;
1046 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1049 s_limbs = abs_s / GMP_LIMB_BITS;
1050 s_bits = abs_s % GMP_LIMB_BITS;
1051 if (n >= 0 ? s >= 0 : s <= 0)
1053 /* Multiply with 2^|s|. */
1056 mp_limb_t *ptr = pow5_ptr;
1057 mp_twolimb_t accu = 0;
1059 for (count = pow5_len; count > 0; count--)
1061 accu += (mp_twolimb_t) *ptr << s_bits;
1062 *ptr++ = (mp_limb_t) accu;
1063 accu = accu >> GMP_LIMB_BITS;
1067 *ptr = (mp_limb_t) accu;
1074 for (count = pow5_len; count > 0;)
1077 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1079 for (count = s_limbs; count > 0;)
1082 pow5_ptr[count] = 0;
1084 pow5_len += s_limbs;
1086 pow5.limbs = pow5_ptr;
1087 pow5.nlimbs = pow5_len;
1090 /* Multiply m with pow5. No division needed. */
1091 z_memory = multiply (m, pow5, &z);
1095 /* Divide m by pow5 and round. */
1096 z_memory = divide (m, pow5, &z);
1101 pow5.limbs = pow5_ptr;
1102 pow5.nlimbs = pow5_len;
1106 Multiply m with pow5, then divide by 2^|s|. */
1110 tmp_memory = multiply (m, pow5, &numerator);
1111 if (tmp_memory == NULL)
1117 /* Construct 2^|s|. */
1119 mp_limb_t *ptr = pow5_ptr + pow5_len;
1121 for (i = 0; i < s_limbs; i++)
1123 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1124 denominator.limbs = ptr;
1125 denominator.nlimbs = s_limbs + 1;
1127 z_memory = divide (numerator, denominator, &z);
1133 Multiply m with 2^s, then divide by pow5. */
1136 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1137 * sizeof (mp_limb_t));
1138 if (num_ptr == NULL)
1145 mp_limb_t *destptr = num_ptr;
1148 for (i = 0; i < s_limbs; i++)
1153 const mp_limb_t *sourceptr = m.limbs;
1154 mp_twolimb_t accu = 0;
1156 for (count = m.nlimbs; count > 0; count--)
1158 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1159 *destptr++ = (mp_limb_t) accu;
1160 accu = accu >> GMP_LIMB_BITS;
1163 *destptr++ = (mp_limb_t) accu;
1167 const mp_limb_t *sourceptr = m.limbs;
1169 for (count = m.nlimbs; count > 0; count--)
1170 *destptr++ = *sourceptr++;
1172 numerator.limbs = num_ptr;
1173 numerator.nlimbs = destptr - num_ptr;
1175 z_memory = divide (numerator, pow5, &z);
1182 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1184 if (z_memory == NULL)
1186 digits = convert_to_decimal (z, extra_zeroes);
1191 # if NEED_PRINTF_LONG_DOUBLE
1193 /* Assuming x is finite and >= 0, and n is an integer:
1194 Returns the decimal representation of round (x * 10^n).
1195 Return the allocated memory - containing the decimal digits in low-to-high
1196 order, terminated with a NUL character - in case of success, NULL in case
1197 of memory allocation failure. */
1199 scale10_round_decimal_long_double (long double x, int n)
1203 void *memory = decode_long_double (x, &e, &m);
1204 return scale10_round_decimal_decoded (e, m, memory, n);
1209 # if NEED_PRINTF_DOUBLE
1211 /* Assuming x is finite and >= 0, and n is an integer:
1212 Returns the decimal representation of round (x * 10^n).
1213 Return the allocated memory - containing the decimal digits in low-to-high
1214 order, terminated with a NUL character - in case of success, NULL in case
1215 of memory allocation failure. */
1217 scale10_round_decimal_double (double x, int n)
1221 void *memory = decode_double (x, &e, &m);
1222 return scale10_round_decimal_decoded (e, m, memory, n);
1227 # if NEED_PRINTF_LONG_DOUBLE
1229 /* Assuming x is finite and > 0:
1230 Return an approximation for n with 10^n <= x < 10^(n+1).
1231 The approximation is usually the right n, but may be off by 1 sometimes. */
1233 floorlog10l (long double x)
1240 /* Split into exponential part and mantissa. */
1241 y = frexpl (x, &exp);
1242 if (!(y >= 0.0L && y < 1.0L))
1248 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1250 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1251 exp -= GMP_LIMB_BITS;
1253 if (y < (1.0L / (1 << 16)))
1255 y *= 1.0L * (1 << 16);
1258 if (y < (1.0L / (1 << 8)))
1260 y *= 1.0L * (1 << 8);
1263 if (y < (1.0L / (1 << 4)))
1265 y *= 1.0L * (1 << 4);
1268 if (y < (1.0L / (1 << 2)))
1270 y *= 1.0L * (1 << 2);
1273 if (y < (1.0L / (1 << 1)))
1275 y *= 1.0L * (1 << 1);
1279 if (!(y >= 0.5L && y < 1.0L))
1281 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1284 if (z < 0.70710678118654752444)
1286 z *= 1.4142135623730950488;
1289 if (z < 0.8408964152537145431)
1291 z *= 1.1892071150027210667;
1294 if (z < 0.91700404320467123175)
1296 z *= 1.0905077326652576592;
1299 if (z < 0.9576032806985736469)
1301 z *= 1.0442737824274138403;
1304 /* Now 0.95 <= z <= 1.01. */
1306 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1307 Four terms are enough to get an approximation with error < 10^-7. */
1308 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1309 /* Finally multiply with log(2)/log(10), yields an approximation for
1311 l *= 0.30102999566398119523;
1312 /* Round down to the next integer. */
1313 return (int) l + (l < 0 ? -1 : 0);
1318 # if NEED_PRINTF_DOUBLE
1320 /* Assuming x is finite and > 0:
1321 Return an approximation for n with 10^n <= x < 10^(n+1).
1322 The approximation is usually the right n, but may be off by 1 sometimes. */
1324 floorlog10 (double x)
1331 /* Split into exponential part and mantissa. */
1332 y = frexp (x, &exp);
1333 if (!(y >= 0.0 && y < 1.0))
1339 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1341 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1342 exp -= GMP_LIMB_BITS;
1344 if (y < (1.0 / (1 << 16)))
1346 y *= 1.0 * (1 << 16);
1349 if (y < (1.0 / (1 << 8)))
1351 y *= 1.0 * (1 << 8);
1354 if (y < (1.0 / (1 << 4)))
1356 y *= 1.0 * (1 << 4);
1359 if (y < (1.0 / (1 << 2)))
1361 y *= 1.0 * (1 << 2);
1364 if (y < (1.0 / (1 << 1)))
1366 y *= 1.0 * (1 << 1);
1370 if (!(y >= 0.5 && y < 1.0))
1372 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1375 if (z < 0.70710678118654752444)
1377 z *= 1.4142135623730950488;
1380 if (z < 0.8408964152537145431)
1382 z *= 1.1892071150027210667;
1385 if (z < 0.91700404320467123175)
1387 z *= 1.0905077326652576592;
1390 if (z < 0.9576032806985736469)
1392 z *= 1.0442737824274138403;
1395 /* Now 0.95 <= z <= 1.01. */
1397 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1398 Four terms are enough to get an approximation with error < 10^-7. */
1399 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1400 /* Finally multiply with log(2)/log(10), yields an approximation for
1402 l *= 0.30102999566398119523;
1403 /* Round down to the next integer. */
1404 return (int) l + (l < 0 ? -1 : 0);
1409 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1410 a single '1' digit. */
1412 is_borderline (const char *digits, size_t precision)
1414 for (; precision > 0; precision--, digits++)
1420 return *digits == '\0';
1426 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1427 const FCHAR_T *format, va_list args)
1432 if (PRINTF_PARSE (format, &d, &a) < 0)
1433 /* errno is already set. */
1441 if (PRINTF_FETCHARGS (args, &a) < 0)
1449 size_t buf_neededlength;
1451 TCHAR_T *buf_malloced;
1455 /* Output string accumulator. */
1460 /* Allocate a small buffer that will hold a directive passed to
1461 sprintf or snprintf. */
1463 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1465 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1467 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1468 buf_malloced = NULL;
1473 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1474 if (size_overflow_p (buf_memsize))
1475 goto out_of_memory_1;
1476 buf = (TCHAR_T *) malloc (buf_memsize);
1478 goto out_of_memory_1;
1482 if (resultbuf != NULL)
1485 allocated = *lengthp;
1494 result is either == resultbuf or == NULL or malloc-allocated.
1495 If length > 0, then result != NULL. */
1497 /* Ensures that allocated >= needed. Aborts through a jump to
1498 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1499 #define ENSURE_ALLOCATION(needed) \
1500 if ((needed) > allocated) \
1502 size_t memory_size; \
1505 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1506 if ((needed) > allocated) \
1507 allocated = (needed); \
1508 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1509 if (size_overflow_p (memory_size)) \
1510 goto out_of_memory; \
1511 if (result == resultbuf || result == NULL) \
1512 memory = (DCHAR_T *) malloc (memory_size); \
1514 memory = (DCHAR_T *) realloc (result, memory_size); \
1515 if (memory == NULL) \
1516 goto out_of_memory; \
1517 if (result == resultbuf && length > 0) \
1518 DCHAR_CPY (memory, result, length); \
1522 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1524 if (cp != dp->dir_start)
1526 size_t n = dp->dir_start - cp;
1527 size_t augmented_length = xsum (length, n);
1529 ENSURE_ALLOCATION (augmented_length);
1530 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1531 need that the format string contains only ASCII characters
1532 if FCHAR_T and DCHAR_T are not the same type. */
1533 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1535 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1536 length = augmented_length;
1541 result[length++] = (unsigned char) *cp++;
1548 /* Execute a single directive. */
1549 if (dp->conversion == '%')
1551 size_t augmented_length;
1553 if (!(dp->arg_index == ARG_NONE))
1555 augmented_length = xsum (length, 1);
1556 ENSURE_ALLOCATION (augmented_length);
1557 result[length] = '%';
1558 length = augmented_length;
1562 if (!(dp->arg_index != ARG_NONE))
1565 if (dp->conversion == 'n')
1567 switch (a.arg[dp->arg_index].type)
1569 case TYPE_COUNT_SCHAR_POINTER:
1570 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1572 case TYPE_COUNT_SHORT_POINTER:
1573 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1575 case TYPE_COUNT_INT_POINTER:
1576 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1578 case TYPE_COUNT_LONGINT_POINTER:
1579 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1581 #if HAVE_LONG_LONG_INT
1582 case TYPE_COUNT_LONGLONGINT_POINTER:
1583 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1591 /* The unistdio extensions. */
1592 else if (dp->conversion == 'U')
1594 arg_type type = a.arg[dp->arg_index].type;
1595 int flags = dp->flags;
1603 if (dp->width_start != dp->width_end)
1605 if (dp->width_arg_index != ARG_NONE)
1609 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1611 arg = a.arg[dp->width_arg_index].a.a_int;
1614 /* "A negative field width is taken as a '-' flag
1615 followed by a positive field width." */
1617 width = (unsigned int) (-arg);
1624 const FCHAR_T *digitp = dp->width_start;
1627 width = xsum (xtimes (width, 10), *digitp++ - '0');
1628 while (digitp != dp->width_end);
1635 if (dp->precision_start != dp->precision_end)
1637 if (dp->precision_arg_index != ARG_NONE)
1641 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1643 arg = a.arg[dp->precision_arg_index].a.a_int;
1644 /* "A negative precision is taken as if the precision
1654 const FCHAR_T *digitp = dp->precision_start + 1;
1657 while (digitp != dp->precision_end)
1658 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1665 case TYPE_U8_STRING:
1667 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1668 const uint8_t *arg_end;
1673 /* Use only PRECISION characters, from the left. */
1676 for (; precision > 0; precision--)
1678 int count = u8_strmblen (arg_end);
1683 if (!(result == resultbuf || result == NULL))
1685 if (buf_malloced != NULL)
1686 free (buf_malloced);
1697 /* Use the entire string, and count the number of
1703 int count = u8_strmblen (arg_end);
1708 if (!(result == resultbuf || result == NULL))
1710 if (buf_malloced != NULL)
1711 free (buf_malloced);
1722 /* Use the entire string. */
1723 arg_end = arg + u8_strlen (arg);
1724 /* The number of characters doesn't matter. */
1728 if (has_width && width > characters
1729 && !(dp->flags & FLAG_LEFT))
1731 size_t n = width - characters;
1732 ENSURE_ALLOCATION (xsum (length, n));
1733 DCHAR_SET (result + length, ' ', n);
1737 # if DCHAR_IS_UINT8_T
1739 size_t n = arg_end - arg;
1740 ENSURE_ALLOCATION (xsum (length, n));
1741 DCHAR_CPY (result + length, arg, n);
1746 DCHAR_T *converted = result + length;
1747 size_t converted_len = allocated - length;
1749 /* Convert from UTF-8 to locale encoding. */
1750 if (u8_conv_to_encoding (locale_charset (),
1751 iconveh_question_mark,
1752 arg, arg_end - arg, NULL,
1753 &converted, &converted_len)
1756 /* Convert from UTF-8 to UTF-16/UTF-32. */
1758 U8_TO_DCHAR (arg, arg_end - arg,
1759 converted, &converted_len);
1760 if (converted == NULL)
1763 int saved_errno = errno;
1764 if (!(result == resultbuf || result == NULL))
1766 if (buf_malloced != NULL)
1767 free (buf_malloced);
1769 errno = saved_errno;
1772 if (converted != result + length)
1774 ENSURE_ALLOCATION (xsum (length, converted_len));
1775 DCHAR_CPY (result + length, converted, converted_len);
1778 length += converted_len;
1782 if (has_width && width > characters
1783 && (dp->flags & FLAG_LEFT))
1785 size_t n = width - characters;
1786 ENSURE_ALLOCATION (xsum (length, n));
1787 DCHAR_SET (result + length, ' ', n);
1793 case TYPE_U16_STRING:
1795 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1796 const uint16_t *arg_end;
1801 /* Use only PRECISION characters, from the left. */
1804 for (; precision > 0; precision--)
1806 int count = u16_strmblen (arg_end);
1811 if (!(result == resultbuf || result == NULL))
1813 if (buf_malloced != NULL)
1814 free (buf_malloced);
1825 /* Use the entire string, and count the number of
1831 int count = u16_strmblen (arg_end);
1836 if (!(result == resultbuf || result == NULL))
1838 if (buf_malloced != NULL)
1839 free (buf_malloced);
1850 /* Use the entire string. */
1851 arg_end = arg + u16_strlen (arg);
1852 /* The number of characters doesn't matter. */
1856 if (has_width && width > characters
1857 && !(dp->flags & FLAG_LEFT))
1859 size_t n = width - characters;
1860 ENSURE_ALLOCATION (xsum (length, n));
1861 DCHAR_SET (result + length, ' ', n);
1865 # if DCHAR_IS_UINT16_T
1867 size_t n = arg_end - arg;
1868 ENSURE_ALLOCATION (xsum (length, n));
1869 DCHAR_CPY (result + length, arg, n);
1874 DCHAR_T *converted = result + length;
1875 size_t converted_len = allocated - length;
1877 /* Convert from UTF-16 to locale encoding. */
1878 if (u16_conv_to_encoding (locale_charset (),
1879 iconveh_question_mark,
1880 arg, arg_end - arg, NULL,
1881 &converted, &converted_len)
1884 /* Convert from UTF-16 to UTF-8/UTF-32. */
1886 U16_TO_DCHAR (arg, arg_end - arg,
1887 converted, &converted_len);
1888 if (converted == NULL)
1891 int saved_errno = errno;
1892 if (!(result == resultbuf || result == NULL))
1894 if (buf_malloced != NULL)
1895 free (buf_malloced);
1897 errno = saved_errno;
1900 if (converted != result + length)
1902 ENSURE_ALLOCATION (xsum (length, converted_len));
1903 DCHAR_CPY (result + length, converted, converted_len);
1906 length += converted_len;
1910 if (has_width && width > characters
1911 && (dp->flags & FLAG_LEFT))
1913 size_t n = width - characters;
1914 ENSURE_ALLOCATION (xsum (length, n));
1915 DCHAR_SET (result + length, ' ', n);
1921 case TYPE_U32_STRING:
1923 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1924 const uint32_t *arg_end;
1929 /* Use only PRECISION characters, from the left. */
1932 for (; precision > 0; precision--)
1934 int count = u32_strmblen (arg_end);
1939 if (!(result == resultbuf || result == NULL))
1941 if (buf_malloced != NULL)
1942 free (buf_malloced);
1953 /* Use the entire string, and count the number of
1959 int count = u32_strmblen (arg_end);
1964 if (!(result == resultbuf || result == NULL))
1966 if (buf_malloced != NULL)
1967 free (buf_malloced);
1978 /* Use the entire string. */
1979 arg_end = arg + u32_strlen (arg);
1980 /* The number of characters doesn't matter. */
1984 if (has_width && width > characters
1985 && !(dp->flags & FLAG_LEFT))
1987 size_t n = width - characters;
1988 ENSURE_ALLOCATION (xsum (length, n));
1989 DCHAR_SET (result + length, ' ', n);
1993 # if DCHAR_IS_UINT32_T
1995 size_t n = arg_end - arg;
1996 ENSURE_ALLOCATION (xsum (length, n));
1997 DCHAR_CPY (result + length, arg, n);
2002 DCHAR_T *converted = result + length;
2003 size_t converted_len = allocated - length;
2005 /* Convert from UTF-32 to locale encoding. */
2006 if (u32_conv_to_encoding (locale_charset (),
2007 iconveh_question_mark,
2008 arg, arg_end - arg, NULL,
2009 &converted, &converted_len)
2012 /* Convert from UTF-32 to UTF-8/UTF-16. */
2014 U32_TO_DCHAR (arg, arg_end - arg,
2015 converted, &converted_len);
2016 if (converted == NULL)
2019 int saved_errno = errno;
2020 if (!(result == resultbuf || result == NULL))
2022 if (buf_malloced != NULL)
2023 free (buf_malloced);
2025 errno = saved_errno;
2028 if (converted != result + length)
2030 ENSURE_ALLOCATION (xsum (length, converted_len));
2031 DCHAR_CPY (result + length, converted, converted_len);
2034 length += converted_len;
2038 if (has_width && width > characters
2039 && (dp->flags & FLAG_LEFT))
2041 size_t n = width - characters;
2042 ENSURE_ALLOCATION (xsum (length, n));
2043 DCHAR_SET (result + length, ' ', n);
2054 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2055 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2056 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2058 # if NEED_PRINTF_DOUBLE
2059 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2061 # if NEED_PRINTF_LONG_DOUBLE
2062 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2068 arg_type type = a.arg[dp->arg_index].type;
2069 int flags = dp->flags;
2075 DCHAR_T tmpbuf[700];
2082 if (dp->width_start != dp->width_end)
2084 if (dp->width_arg_index != ARG_NONE)
2088 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2090 arg = a.arg[dp->width_arg_index].a.a_int;
2093 /* "A negative field width is taken as a '-' flag
2094 followed by a positive field width." */
2096 width = (unsigned int) (-arg);
2103 const FCHAR_T *digitp = dp->width_start;
2106 width = xsum (xtimes (width, 10), *digitp++ - '0');
2107 while (digitp != dp->width_end);
2114 if (dp->precision_start != dp->precision_end)
2116 if (dp->precision_arg_index != ARG_NONE)
2120 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2122 arg = a.arg[dp->precision_arg_index].a.a_int;
2123 /* "A negative precision is taken as if the precision
2133 const FCHAR_T *digitp = dp->precision_start + 1;
2136 while (digitp != dp->precision_end)
2137 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2142 /* Allocate a temporary buffer of sufficient size. */
2143 if (type == TYPE_LONGDOUBLE)
2145 (unsigned int) ((LDBL_DIG + 1)
2146 * 0.831 /* decimal -> hexadecimal */
2148 + 1; /* turn floor into ceil */
2151 (unsigned int) ((DBL_DIG + 1)
2152 * 0.831 /* decimal -> hexadecimal */
2154 + 1; /* turn floor into ceil */
2155 if (tmp_length < precision)
2156 tmp_length = precision;
2157 /* Account for sign, decimal point etc. */
2158 tmp_length = xsum (tmp_length, 12);
2160 if (tmp_length < width)
2163 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2165 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2169 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2171 if (size_overflow_p (tmp_memsize))
2172 /* Overflow, would lead to out of memory. */
2174 tmp = (DCHAR_T *) malloc (tmp_memsize);
2176 /* Out of memory. */
2182 if (type == TYPE_LONGDOUBLE)
2184 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2185 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2189 if (dp->conversion == 'A')
2191 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2195 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2201 DECL_LONG_DOUBLE_ROUNDING
2203 BEGIN_LONG_DOUBLE_ROUNDING ();
2205 if (signbit (arg)) /* arg < 0.0L or negative zero */
2213 else if (flags & FLAG_SHOWSIGN)
2215 else if (flags & FLAG_SPACE)
2218 if (arg > 0.0L && arg + arg == arg)
2220 if (dp->conversion == 'A')
2222 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2226 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2232 long double mantissa;
2235 mantissa = printf_frexpl (arg, &exponent);
2243 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2245 /* Round the mantissa. */
2246 long double tail = mantissa;
2249 for (q = precision; ; q--)
2251 int digit = (int) tail;
2255 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2264 for (q = precision; q > 0; q--)
2270 *p++ = dp->conversion - 'A' + 'X';
2275 digit = (int) mantissa;
2278 if ((flags & FLAG_ALT)
2279 || mantissa > 0.0L || precision > 0)
2281 *p++ = decimal_point_char ();
2282 /* This loop terminates because we assume
2283 that FLT_RADIX is a power of 2. */
2284 while (mantissa > 0.0L)
2287 digit = (int) mantissa;
2292 : dp->conversion - 10);
2296 while (precision > 0)
2303 *p++ = dp->conversion - 'A' + 'P';
2304 # if WIDE_CHAR_VERSION
2306 static const wchar_t decimal_format[] =
2307 { '%', '+', 'd', '\0' };
2308 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2313 if (sizeof (DCHAR_T) == 1)
2315 sprintf ((char *) p, "%+d", exponent);
2323 sprintf (expbuf, "%+d", exponent);
2324 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2330 END_LONG_DOUBLE_ROUNDING ();
2338 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2339 double arg = a.arg[dp->arg_index].a.a_double;
2343 if (dp->conversion == 'A')
2345 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2349 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2356 if (signbit (arg)) /* arg < 0.0 or negative zero */
2364 else if (flags & FLAG_SHOWSIGN)
2366 else if (flags & FLAG_SPACE)
2369 if (arg > 0.0 && arg + arg == arg)
2371 if (dp->conversion == 'A')
2373 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2377 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2386 mantissa = printf_frexp (arg, &exponent);
2394 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2396 /* Round the mantissa. */
2397 double tail = mantissa;
2400 for (q = precision; ; q--)
2402 int digit = (int) tail;
2406 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2415 for (q = precision; q > 0; q--)
2421 *p++ = dp->conversion - 'A' + 'X';
2426 digit = (int) mantissa;
2429 if ((flags & FLAG_ALT)
2430 || mantissa > 0.0 || precision > 0)
2432 *p++ = decimal_point_char ();
2433 /* This loop terminates because we assume
2434 that FLT_RADIX is a power of 2. */
2435 while (mantissa > 0.0)
2438 digit = (int) mantissa;
2443 : dp->conversion - 10);
2447 while (precision > 0)
2454 *p++ = dp->conversion - 'A' + 'P';
2455 # if WIDE_CHAR_VERSION
2457 static const wchar_t decimal_format[] =
2458 { '%', '+', 'd', '\0' };
2459 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2464 if (sizeof (DCHAR_T) == 1)
2466 sprintf ((char *) p, "%+d", exponent);
2474 sprintf (expbuf, "%+d", exponent);
2475 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2485 /* The generated string now extends from tmp to p, with the
2486 zero padding insertion point being at pad_ptr. */
2487 if (has_width && p - tmp < width)
2489 size_t pad = width - (p - tmp);
2490 DCHAR_T *end = p + pad;
2492 if (flags & FLAG_LEFT)
2494 /* Pad with spaces on the right. */
2495 for (; pad > 0; pad--)
2498 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2500 /* Pad with zeroes. */
2505 for (; pad > 0; pad--)
2510 /* Pad with spaces on the left. */
2515 for (; pad > 0; pad--)
2523 size_t count = p - tmp;
2525 if (count >= tmp_length)
2526 /* tmp_length was incorrectly calculated - fix the
2530 /* Make room for the result. */
2531 if (count >= allocated - length)
2533 size_t n = xsum (length, count);
2535 ENSURE_ALLOCATION (n);
2538 /* Append the result. */
2539 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2546 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2547 else if ((dp->conversion == 'f' || dp->conversion == 'F'
2548 || dp->conversion == 'e' || dp->conversion == 'E'
2549 || dp->conversion == 'g' || dp->conversion == 'G'
2550 || dp->conversion == 'a' || dp->conversion == 'A')
2552 # if NEED_PRINTF_DOUBLE
2553 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2554 # elif NEED_PRINTF_INFINITE_DOUBLE
2555 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2556 /* The systems (mingw) which produce wrong output
2557 for Inf, -Inf, and NaN also do so for -0.0.
2558 Therefore we treat this case here as well. */
2559 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2561 # if NEED_PRINTF_LONG_DOUBLE
2562 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2563 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2564 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2565 /* Some systems produce wrong output for Inf,
2567 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
2571 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2572 arg_type type = a.arg[dp->arg_index].type;
2574 int flags = dp->flags;
2580 DCHAR_T tmpbuf[700];
2587 if (dp->width_start != dp->width_end)
2589 if (dp->width_arg_index != ARG_NONE)
2593 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2595 arg = a.arg[dp->width_arg_index].a.a_int;
2598 /* "A negative field width is taken as a '-' flag
2599 followed by a positive field width." */
2601 width = (unsigned int) (-arg);
2608 const FCHAR_T *digitp = dp->width_start;
2611 width = xsum (xtimes (width, 10), *digitp++ - '0');
2612 while (digitp != dp->width_end);
2619 if (dp->precision_start != dp->precision_end)
2621 if (dp->precision_arg_index != ARG_NONE)
2625 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2627 arg = a.arg[dp->precision_arg_index].a.a_int;
2628 /* "A negative precision is taken as if the precision
2638 const FCHAR_T *digitp = dp->precision_start + 1;
2641 while (digitp != dp->precision_end)
2642 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2647 /* POSIX specifies the default precision to be 6 for %f, %F,
2648 %e, %E, but not for %g, %G. Implementations appear to use
2649 the same default precision also for %g, %G. */
2653 /* Allocate a temporary buffer of sufficient size. */
2654 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2655 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
2656 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2657 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2658 # elif NEED_PRINTF_LONG_DOUBLE
2659 tmp_length = LDBL_DIG + 1;
2660 # elif NEED_PRINTF_DOUBLE
2661 tmp_length = DBL_DIG + 1;
2665 if (tmp_length < precision)
2666 tmp_length = precision;
2667 # if NEED_PRINTF_LONG_DOUBLE
2668 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2669 if (type == TYPE_LONGDOUBLE)
2671 if (dp->conversion == 'f' || dp->conversion == 'F')
2673 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2674 if (!(isnanl (arg) || arg + arg == arg))
2676 /* arg is finite and nonzero. */
2677 int exponent = floorlog10l (arg < 0 ? -arg : arg);
2678 if (exponent >= 0 && tmp_length < exponent + precision)
2679 tmp_length = exponent + precision;
2683 # if NEED_PRINTF_DOUBLE
2684 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2685 if (type == TYPE_DOUBLE)
2687 if (dp->conversion == 'f' || dp->conversion == 'F')
2689 double arg = a.arg[dp->arg_index].a.a_double;
2690 if (!(isnand (arg) || arg + arg == arg))
2692 /* arg is finite and nonzero. */
2693 int exponent = floorlog10 (arg < 0 ? -arg : arg);
2694 if (exponent >= 0 && tmp_length < exponent + precision)
2695 tmp_length = exponent + precision;
2699 /* Account for sign, decimal point etc. */
2700 tmp_length = xsum (tmp_length, 12);
2702 if (tmp_length < width)
2705 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2707 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2711 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2713 if (size_overflow_p (tmp_memsize))
2714 /* Overflow, would lead to out of memory. */
2716 tmp = (DCHAR_T *) malloc (tmp_memsize);
2718 /* Out of memory. */
2725 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2726 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2727 if (type == TYPE_LONGDOUBLE)
2730 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2734 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2736 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2740 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2746 DECL_LONG_DOUBLE_ROUNDING
2748 BEGIN_LONG_DOUBLE_ROUNDING ();
2750 if (signbit (arg)) /* arg < 0.0L or negative zero */
2758 else if (flags & FLAG_SHOWSIGN)
2760 else if (flags & FLAG_SPACE)
2763 if (arg > 0.0L && arg + arg == arg)
2765 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2767 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2771 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2776 # if NEED_PRINTF_LONG_DOUBLE
2779 if (dp->conversion == 'f' || dp->conversion == 'F')
2785 scale10_round_decimal_long_double (arg, precision);
2788 END_LONG_DOUBLE_ROUNDING ();
2791 ndigits = strlen (digits);
2793 if (ndigits > precision)
2797 *p++ = digits[ndigits];
2799 while (ndigits > precision);
2802 /* Here ndigits <= precision. */
2803 if ((flags & FLAG_ALT) || precision > 0)
2805 *p++ = decimal_point_char ();
2806 for (; precision > ndigits; precision--)
2811 *p++ = digits[ndigits];
2817 else if (dp->conversion == 'e' || dp->conversion == 'E')
2825 if ((flags & FLAG_ALT) || precision > 0)
2827 *p++ = decimal_point_char ();
2828 for (; precision > 0; precision--)
2839 exponent = floorlog10l (arg);
2844 scale10_round_decimal_long_double (arg,
2845 (int)precision - exponent);
2848 END_LONG_DOUBLE_ROUNDING ();
2851 ndigits = strlen (digits);
2853 if (ndigits == precision + 1)
2855 if (ndigits < precision
2856 || ndigits > precision + 2)
2857 /* The exponent was not guessed
2858 precisely enough. */
2861 /* None of two values of exponent is
2862 the right one. Prevent an endless
2866 if (ndigits == precision)
2872 /* Here ndigits = precision+1. */
2873 if (is_borderline (digits, precision))
2875 /* Maybe the exponent guess was too high
2876 and a smaller exponent can be reached
2877 by turning a 10...0 into 9...9x. */
2879 scale10_round_decimal_long_double (arg,
2880 (int)precision - exponent + 1);
2881 if (digits2 == NULL)
2884 END_LONG_DOUBLE_ROUNDING ();
2887 if (strlen (digits2) == precision + 1)
2896 /* Here ndigits = precision+1. */
2898 *p++ = digits[--ndigits];
2899 if ((flags & FLAG_ALT) || precision > 0)
2901 *p++ = decimal_point_char ();
2905 *p++ = digits[ndigits];
2912 *p++ = dp->conversion; /* 'e' or 'E' */
2913 # if WIDE_CHAR_VERSION
2915 static const wchar_t decimal_format[] =
2916 { '%', '+', '.', '2', 'd', '\0' };
2917 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2922 if (sizeof (DCHAR_T) == 1)
2924 sprintf ((char *) p, "%+.2d", exponent);
2932 sprintf (expbuf, "%+.2d", exponent);
2933 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2938 else if (dp->conversion == 'g' || dp->conversion == 'G')
2942 /* precision >= 1. */
2945 /* The exponent is 0, >= -4, < precision.
2946 Use fixed-point notation. */
2948 size_t ndigits = precision;
2949 /* Number of trailing zeroes that have to be
2952 (flags & FLAG_ALT ? 0 : precision - 1);
2956 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2958 *p++ = decimal_point_char ();
2959 while (ndigits > nzeroes)
2975 exponent = floorlog10l (arg);
2980 scale10_round_decimal_long_double (arg,
2981 (int)(precision - 1) - exponent);
2984 END_LONG_DOUBLE_ROUNDING ();
2987 ndigits = strlen (digits);
2989 if (ndigits == precision)
2991 if (ndigits < precision - 1
2992 || ndigits > precision + 1)
2993 /* The exponent was not guessed
2994 precisely enough. */
2997 /* None of two values of exponent is
2998 the right one. Prevent an endless
3002 if (ndigits < precision)
3008 /* Here ndigits = precision. */
3009 if (is_borderline (digits, precision - 1))
3011 /* Maybe the exponent guess was too high
3012 and a smaller exponent can be reached
3013 by turning a 10...0 into 9...9x. */
3015 scale10_round_decimal_long_double (arg,
3016 (int)(precision - 1) - exponent + 1);
3017 if (digits2 == NULL)
3020 END_LONG_DOUBLE_ROUNDING ();
3023 if (strlen (digits2) == precision)
3032 /* Here ndigits = precision. */
3034 /* Determine the number of trailing zeroes
3035 that have to be dropped. */
3037 if ((flags & FLAG_ALT) == 0)
3038 while (nzeroes < ndigits
3039 && digits[nzeroes] == '0')
3042 /* The exponent is now determined. */
3044 && exponent < (long)precision)
3046 /* Fixed-point notation:
3047 max(exponent,0)+1 digits, then the
3048 decimal point, then the remaining
3049 digits without trailing zeroes. */
3052 size_t count = exponent + 1;
3053 /* Note: count <= precision = ndigits. */
3054 for (; count > 0; count--)
3055 *p++ = digits[--ndigits];
3056 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3058 *p++ = decimal_point_char ();
3059 while (ndigits > nzeroes)
3062 *p++ = digits[ndigits];
3068 size_t count = -exponent - 1;
3070 *p++ = decimal_point_char ();
3071 for (; count > 0; count--)
3073 while (ndigits > nzeroes)
3076 *p++ = digits[ndigits];
3082 /* Exponential notation. */
3083 *p++ = digits[--ndigits];
3084 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3086 *p++ = decimal_point_char ();
3087 while (ndigits > nzeroes)
3090 *p++ = digits[ndigits];
3093 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3094 # if WIDE_CHAR_VERSION
3096 static const wchar_t decimal_format[] =
3097 { '%', '+', '.', '2', 'd', '\0' };
3098 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3103 if (sizeof (DCHAR_T) == 1)
3105 sprintf ((char *) p, "%+.2d", exponent);
3113 sprintf (expbuf, "%+.2d", exponent);
3114 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3126 /* arg is finite. */
3131 END_LONG_DOUBLE_ROUNDING ();
3134 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3138 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3140 double arg = a.arg[dp->arg_index].a.a_double;
3144 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3146 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3150 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3157 if (signbit (arg)) /* arg < 0.0 or negative zero */
3165 else if (flags & FLAG_SHOWSIGN)
3167 else if (flags & FLAG_SPACE)
3170 if (arg > 0.0 && arg + arg == arg)
3172 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3174 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3178 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3183 # if NEED_PRINTF_DOUBLE
3186 if (dp->conversion == 'f' || dp->conversion == 'F')
3192 scale10_round_decimal_double (arg, precision);
3195 ndigits = strlen (digits);
3197 if (ndigits > precision)
3201 *p++ = digits[ndigits];
3203 while (ndigits > precision);
3206 /* Here ndigits <= precision. */
3207 if ((flags & FLAG_ALT) || precision > 0)
3209 *p++ = decimal_point_char ();
3210 for (; precision > ndigits; precision--)
3215 *p++ = digits[ndigits];
3221 else if (dp->conversion == 'e' || dp->conversion == 'E')
3229 if ((flags & FLAG_ALT) || precision > 0)
3231 *p++ = decimal_point_char ();
3232 for (; precision > 0; precision--)
3243 exponent = floorlog10 (arg);
3248 scale10_round_decimal_double (arg,
3249 (int)precision - exponent);
3252 ndigits = strlen (digits);
3254 if (ndigits == precision + 1)
3256 if (ndigits < precision
3257 || ndigits > precision + 2)
3258 /* The exponent was not guessed
3259 precisely enough. */
3262 /* None of two values of exponent is
3263 the right one. Prevent an endless
3267 if (ndigits == precision)
3273 /* Here ndigits = precision+1. */
3274 if (is_borderline (digits, precision))
3276 /* Maybe the exponent guess was too high
3277 and a smaller exponent can be reached
3278 by turning a 10...0 into 9...9x. */
3280 scale10_round_decimal_double (arg,
3281 (int)precision - exponent + 1);
3282 if (digits2 == NULL)
3287 if (strlen (digits2) == precision + 1)
3296 /* Here ndigits = precision+1. */
3298 *p++ = digits[--ndigits];
3299 if ((flags & FLAG_ALT) || precision > 0)
3301 *p++ = decimal_point_char ();
3305 *p++ = digits[ndigits];
3312 *p++ = dp->conversion; /* 'e' or 'E' */
3313 # if WIDE_CHAR_VERSION
3315 static const wchar_t decimal_format[] =
3316 /* Produce the same number of exponent digits
3317 as the native printf implementation. */
3318 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3319 { '%', '+', '.', '3', 'd', '\0' };
3321 { '%', '+', '.', '2', 'd', '\0' };
3323 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3329 static const char decimal_format[] =
3330 /* Produce the same number of exponent digits
3331 as the native printf implementation. */
3332 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3337 if (sizeof (DCHAR_T) == 1)
3339 sprintf ((char *) p, decimal_format, exponent);
3347 sprintf (expbuf, decimal_format, exponent);
3348 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3354 else if (dp->conversion == 'g' || dp->conversion == 'G')
3358 /* precision >= 1. */
3361 /* The exponent is 0, >= -4, < precision.
3362 Use fixed-point notation. */
3364 size_t ndigits = precision;
3365 /* Number of trailing zeroes that have to be
3368 (flags & FLAG_ALT ? 0 : precision - 1);
3372 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3374 *p++ = decimal_point_char ();
3375 while (ndigits > nzeroes)
3391 exponent = floorlog10 (arg);
3396 scale10_round_decimal_double (arg,
3397 (int)(precision - 1) - exponent);
3400 ndigits = strlen (digits);
3402 if (ndigits == precision)
3404 if (ndigits < precision - 1
3405 || ndigits > precision + 1)
3406 /* The exponent was not guessed
3407 precisely enough. */
3410 /* None of two values of exponent is
3411 the right one. Prevent an endless
3415 if (ndigits < precision)
3421 /* Here ndigits = precision. */
3422 if (is_borderline (digits, precision - 1))
3424 /* Maybe the exponent guess was too high
3425 and a smaller exponent can be reached
3426 by turning a 10...0 into 9...9x. */
3428 scale10_round_decimal_double (arg,
3429 (int)(precision - 1) - exponent + 1);
3430 if (digits2 == NULL)
3435 if (strlen (digits2) == precision)
3444 /* Here ndigits = precision. */
3446 /* Determine the number of trailing zeroes
3447 that have to be dropped. */
3449 if ((flags & FLAG_ALT) == 0)
3450 while (nzeroes < ndigits
3451 && digits[nzeroes] == '0')
3454 /* The exponent is now determined. */
3456 && exponent < (long)precision)
3458 /* Fixed-point notation:
3459 max(exponent,0)+1 digits, then the
3460 decimal point, then the remaining
3461 digits without trailing zeroes. */
3464 size_t count = exponent + 1;
3465 /* Note: count <= precision = ndigits. */
3466 for (; count > 0; count--)
3467 *p++ = digits[--ndigits];
3468 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3470 *p++ = decimal_point_char ();
3471 while (ndigits > nzeroes)
3474 *p++ = digits[ndigits];
3480 size_t count = -exponent - 1;
3482 *p++ = decimal_point_char ();
3483 for (; count > 0; count--)
3485 while (ndigits > nzeroes)
3488 *p++ = digits[ndigits];
3494 /* Exponential notation. */
3495 *p++ = digits[--ndigits];
3496 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3498 *p++ = decimal_point_char ();
3499 while (ndigits > nzeroes)
3502 *p++ = digits[ndigits];
3505 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3506 # if WIDE_CHAR_VERSION
3508 static const wchar_t decimal_format[] =
3509 /* Produce the same number of exponent digits
3510 as the native printf implementation. */
3511 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3512 { '%', '+', '.', '3', 'd', '\0' };
3514 { '%', '+', '.', '2', 'd', '\0' };
3516 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3522 static const char decimal_format[] =
3523 /* Produce the same number of exponent digits
3524 as the native printf implementation. */
3525 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3530 if (sizeof (DCHAR_T) == 1)
3532 sprintf ((char *) p, decimal_format, exponent);
3540 sprintf (expbuf, decimal_format, exponent);
3541 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3554 /* arg is finite. */
3560 if (dp->conversion == 'f' || dp->conversion == 'F')
3563 if ((flags & FLAG_ALT) || precision > 0)
3565 *p++ = decimal_point_char ();
3566 for (; precision > 0; precision--)
3570 else if (dp->conversion == 'e' || dp->conversion == 'E')
3573 if ((flags & FLAG_ALT) || precision > 0)
3575 *p++ = decimal_point_char ();
3576 for (; precision > 0; precision--)
3579 *p++ = dp->conversion; /* 'e' or 'E' */
3581 /* Produce the same number of exponent digits as
3582 the native printf implementation. */
3583 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3589 else if (dp->conversion == 'g' || dp->conversion == 'G')
3592 if (flags & FLAG_ALT)
3595 (precision > 0 ? precision - 1 : 0);
3596 *p++ = decimal_point_char ();
3597 for (; ndigits > 0; --ndigits)
3609 /* The generated string now extends from tmp to p, with the
3610 zero padding insertion point being at pad_ptr. */
3611 if (has_width && p - tmp < width)
3613 size_t pad = width - (p - tmp);
3614 DCHAR_T *end = p + pad;
3616 if (flags & FLAG_LEFT)
3618 /* Pad with spaces on the right. */
3619 for (; pad > 0; pad--)
3622 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3624 /* Pad with zeroes. */
3629 for (; pad > 0; pad--)
3634 /* Pad with spaces on the left. */
3639 for (; pad > 0; pad--)
3647 size_t count = p - tmp;
3649 if (count >= tmp_length)
3650 /* tmp_length was incorrectly calculated - fix the
3654 /* Make room for the result. */
3655 if (count >= allocated - length)
3657 size_t n = xsum (length, count);
3659 ENSURE_ALLOCATION (n);
3662 /* Append the result. */
3663 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3672 arg_type type = a.arg[dp->arg_index].type;
3673 int flags = dp->flags;
3674 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3678 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3682 #if NEED_PRINTF_UNBOUNDED_PRECISION
3685 # define prec_ourselves 0
3687 #if NEED_PRINTF_FLAG_LEFTADJUST
3688 # define pad_ourselves 1
3689 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3692 # define pad_ourselves 0
3695 unsigned int prefix_count;
3699 TCHAR_T tmpbuf[700];
3703 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3706 if (dp->width_start != dp->width_end)
3708 if (dp->width_arg_index != ARG_NONE)
3712 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3714 arg = a.arg[dp->width_arg_index].a.a_int;
3717 /* "A negative field width is taken as a '-' flag
3718 followed by a positive field width." */
3720 width = (unsigned int) (-arg);
3727 const FCHAR_T *digitp = dp->width_start;
3730 width = xsum (xtimes (width, 10), *digitp++ - '0');
3731 while (digitp != dp->width_end);
3737 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3740 if (dp->precision_start != dp->precision_end)
3742 if (dp->precision_arg_index != ARG_NONE)
3746 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3748 arg = a.arg[dp->precision_arg_index].a.a_int;
3749 /* "A negative precision is taken as if the precision
3759 const FCHAR_T *digitp = dp->precision_start + 1;
3762 while (digitp != dp->precision_end)
3763 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3769 /* Decide whether to handle the precision ourselves. */
3770 #if NEED_PRINTF_UNBOUNDED_PRECISION
3771 switch (dp->conversion)
3773 case 'd': case 'i': case 'u':
3775 case 'x': case 'X': case 'p':
3776 prec_ourselves = has_precision && (precision > 0);
3784 /* Decide whether to perform the padding ourselves. */
3785 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
3786 switch (dp->conversion)
3788 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
3789 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
3790 to perform the padding after this conversion. Functions
3791 with unistdio extensions perform the padding based on
3792 character count rather than element count. */
3795 # if NEED_PRINTF_FLAG_ZERO
3796 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
3802 pad_ourselves = prec_ourselves;
3808 /* Allocate a temporary buffer of sufficient size for calling
3811 switch (dp->conversion)
3814 case 'd': case 'i': case 'u':
3815 # if HAVE_LONG_LONG_INT
3816 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3818 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3819 * 0.30103 /* binary -> decimal */
3821 + 1; /* turn floor into ceil */
3824 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3826 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3827 * 0.30103 /* binary -> decimal */
3829 + 1; /* turn floor into ceil */
3832 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3833 * 0.30103 /* binary -> decimal */
3835 + 1; /* turn floor into ceil */
3836 if (tmp_length < precision)
3837 tmp_length = precision;
3838 /* Multiply by 2, as an estimate for FLAG_GROUP. */
3839 tmp_length = xsum (tmp_length, tmp_length);
3840 /* Add 1, to account for a leading sign. */
3841 tmp_length = xsum (tmp_length, 1);
3845 # if HAVE_LONG_LONG_INT
3846 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3848 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3849 * 0.333334 /* binary -> octal */
3851 + 1; /* turn floor into ceil */
3854 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3856 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3857 * 0.333334 /* binary -> octal */
3859 + 1; /* turn floor into ceil */
3862 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3863 * 0.333334 /* binary -> octal */
3865 + 1; /* turn floor into ceil */
3866 if (tmp_length < precision)
3867 tmp_length = precision;
3868 /* Add 1, to account for a leading sign. */
3869 tmp_length = xsum (tmp_length, 1);
3873 # if HAVE_LONG_LONG_INT
3874 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3876 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3877 * 0.25 /* binary -> hexadecimal */
3879 + 1; /* turn floor into ceil */
3882 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3884 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3885 * 0.25 /* binary -> hexadecimal */
3887 + 1; /* turn floor into ceil */
3890 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3891 * 0.25 /* binary -> hexadecimal */
3893 + 1; /* turn floor into ceil */
3894 if (tmp_length < precision)
3895 tmp_length = precision;
3896 /* Add 2, to account for a leading sign or alternate form. */
3897 tmp_length = xsum (tmp_length, 2);
3901 if (type == TYPE_LONGDOUBLE)
3903 (unsigned int) (LDBL_MAX_EXP
3904 * 0.30103 /* binary -> decimal */
3905 * 2 /* estimate for FLAG_GROUP */
3907 + 1 /* turn floor into ceil */
3908 + 10; /* sign, decimal point etc. */
3911 (unsigned int) (DBL_MAX_EXP
3912 * 0.30103 /* binary -> decimal */
3913 * 2 /* estimate for FLAG_GROUP */
3915 + 1 /* turn floor into ceil */
3916 + 10; /* sign, decimal point etc. */
3917 tmp_length = xsum (tmp_length, precision);
3920 case 'e': case 'E': case 'g': case 'G':
3922 12; /* sign, decimal point, exponent etc. */
3923 tmp_length = xsum (tmp_length, precision);
3927 if (type == TYPE_LONGDOUBLE)
3929 (unsigned int) (LDBL_DIG
3930 * 0.831 /* decimal -> hexadecimal */
3932 + 1; /* turn floor into ceil */
3935 (unsigned int) (DBL_DIG
3936 * 0.831 /* decimal -> hexadecimal */
3938 + 1; /* turn floor into ceil */
3939 if (tmp_length < precision)
3940 tmp_length = precision;
3941 /* Account for sign, decimal point etc. */
3942 tmp_length = xsum (tmp_length, 12);
3946 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
3947 if (type == TYPE_WIDE_CHAR)
3948 tmp_length = MB_CUR_MAX;
3956 if (type == TYPE_WIDE_STRING)
3959 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
3961 # if !WIDE_CHAR_VERSION
3962 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
3967 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
3972 (unsigned int) (sizeof (void *) * CHAR_BIT
3973 * 0.25 /* binary -> hexadecimal */
3975 + 1 /* turn floor into ceil */
3976 + 2; /* account for leading 0x */
3985 # if ENABLE_UNISTDIO
3986 /* Padding considers the number of characters, therefore
3987 the number of elements after padding may be
3988 > max (tmp_length, width)
3990 <= tmp_length + width. */
3991 tmp_length = xsum (tmp_length, width);
3993 /* Padding considers the number of elements,
3995 if (tmp_length < width)
4000 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
4003 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4007 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4009 if (size_overflow_p (tmp_memsize))
4010 /* Overflow, would lead to out of memory. */
4012 tmp = (TCHAR_T *) malloc (tmp_memsize);
4014 /* Out of memory. */
4019 /* Construct the format string for calling snprintf or
4023 #if NEED_PRINTF_FLAG_GROUPING
4024 /* The underlying implementation doesn't support the ' flag.
4025 Produce no grouping characters in this case; this is
4026 acceptable because the grouping is locale dependent. */
4028 if (flags & FLAG_GROUP)
4031 if (flags & FLAG_LEFT)
4033 if (flags & FLAG_SHOWSIGN)
4035 if (flags & FLAG_SPACE)
4037 if (flags & FLAG_ALT)
4041 if (flags & FLAG_ZERO)
4043 if (dp->width_start != dp->width_end)
4045 size_t n = dp->width_end - dp->width_start;
4046 /* The width specification is known to consist only
4047 of standard ASCII characters. */
4048 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4050 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4055 const FCHAR_T *mp = dp->width_start;
4057 *fbp++ = (unsigned char) *mp++;
4062 if (!prec_ourselves)
4064 if (dp->precision_start != dp->precision_end)
4066 size_t n = dp->precision_end - dp->precision_start;
4067 /* The precision specification is known to consist only
4068 of standard ASCII characters. */
4069 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4071 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4076 const FCHAR_T *mp = dp->precision_start;
4078 *fbp++ = (unsigned char) *mp++;
4086 #if HAVE_LONG_LONG_INT
4087 case TYPE_LONGLONGINT:
4088 case TYPE_ULONGLONGINT:
4089 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4102 case TYPE_WIDE_CHAR:
4105 case TYPE_WIDE_STRING:
4109 case TYPE_LONGDOUBLE:
4115 #if NEED_PRINTF_DIRECTIVE_F
4116 if (dp->conversion == 'F')
4120 *fbp = dp->conversion;
4122 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4127 /* On glibc2 systems from glibc >= 2.3 - probably also older
4128 ones - we know that snprintf's returns value conforms to
4129 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4130 Therefore we can avoid using %n in this situation.
4131 On glibc2 systems from 2004-10-18 or newer, the use of %n
4132 in format strings in writable memory may crash the program
4133 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4134 in this situation. */
4135 /* On native Win32 systems (such as mingw), we can avoid using
4137 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4138 snprintf does not write more than the specified number
4139 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4140 '4', '5', '6' into buf, not '4', '5', '\0'.)
4141 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4142 allows us to recognize the case of an insufficient
4143 buffer size: it returns -1 in this case.
4144 On native Win32 systems (such as mingw) where the OS is
4145 Windows Vista, the use of %n in format strings by default
4146 crashes the program. See
4147 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4148 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4149 So we should avoid %n in this situation. */
4156 /* Construct the arguments for calling snprintf or sprintf. */
4158 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4160 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4162 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4164 if (dp->precision_arg_index != ARG_NONE)
4166 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4168 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4172 /* The SNPRINTF result is appended after result[0..length].
4173 The latter is an array of DCHAR_T; SNPRINTF appends an
4174 array of TCHAR_T to it. This is possible because
4175 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4176 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4177 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4178 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4179 where an snprintf() with maxlen==1 acts like sprintf(). */
4180 ENSURE_ALLOCATION (xsum (length,
4181 (2 + TCHARS_PER_DCHAR - 1)
4182 / TCHARS_PER_DCHAR));
4183 /* Prepare checking whether snprintf returns the count
4185 *(TCHAR_T *) (result + length) = '\0';
4194 size_t maxlen = allocated - length;
4195 /* SNPRINTF can fail if its second argument is
4197 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4198 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4199 maxlen = maxlen * TCHARS_PER_DCHAR;
4200 # define SNPRINTF_BUF(arg) \
4201 switch (prefix_count) \
4204 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4209 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4211 prefixes[0], arg, &count); \
4214 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4216 prefixes[0], prefixes[1], arg, \
4223 # define SNPRINTF_BUF(arg) \
4224 switch (prefix_count) \
4227 count = sprintf (tmp, buf, arg); \
4230 count = sprintf (tmp, buf, prefixes[0], arg); \
4233 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4245 int arg = a.arg[dp->arg_index].a.a_schar;
4251 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4257 int arg = a.arg[dp->arg_index].a.a_short;
4263 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4269 int arg = a.arg[dp->arg_index].a.a_int;
4275 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4281 long int arg = a.arg[dp->arg_index].a.a_longint;
4287 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4291 #if HAVE_LONG_LONG_INT
4292 case TYPE_LONGLONGINT:
4294 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4298 case TYPE_ULONGLONGINT:
4300 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4307 double arg = a.arg[dp->arg_index].a.a_double;
4311 case TYPE_LONGDOUBLE:
4313 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4319 int arg = a.arg[dp->arg_index].a.a_char;
4324 case TYPE_WIDE_CHAR:
4326 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
4333 const char *arg = a.arg[dp->arg_index].a.a_string;
4338 case TYPE_WIDE_STRING:
4340 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
4347 void *arg = a.arg[dp->arg_index].a.a_pointer;
4356 /* Portability: Not all implementations of snprintf()
4357 are ISO C 99 compliant. Determine the number of
4358 bytes that snprintf() has produced or would have
4362 /* Verify that snprintf() has NUL-terminated its
4365 && ((TCHAR_T *) (result + length)) [count] != '\0')
4367 /* Portability hack. */
4368 if (retcount > count)
4373 /* snprintf() doesn't understand the '%n'
4377 /* Don't use the '%n' directive; instead, look
4378 at the snprintf() return value. */
4384 /* Look at the snprintf() return value. */
4387 /* HP-UX 10.20 snprintf() is doubly deficient:
4388 It doesn't understand the '%n' directive,
4389 *and* it returns -1 (rather than the length
4390 that would have been required) when the
4391 buffer is too small. */
4392 size_t bigger_need =
4393 xsum (xtimes (allocated, 2), 12);
4394 ENSURE_ALLOCATION (bigger_need);
4403 /* Attempt to handle failure. */
4406 if (!(result == resultbuf || result == NULL))
4408 if (buf_malloced != NULL)
4409 free (buf_malloced);
4416 /* Handle overflow of the allocated buffer.
4417 If such an overflow occurs, a C99 compliant snprintf()
4418 returns a count >= maxlen. However, a non-compliant
4419 snprintf() function returns only count = maxlen - 1. To
4420 cover both cases, test whether count >= maxlen - 1. */
4421 if ((unsigned int) count + 1 >= maxlen)
4423 /* If maxlen already has attained its allowed maximum,
4424 allocating more memory will not increase maxlen.
4425 Instead of looping, bail out. */
4426 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
4430 /* Need at least (count + 1) * sizeof (TCHAR_T)
4431 bytes. (The +1 is for the trailing NUL.)
4432 But ask for (count + 2) * sizeof (TCHAR_T)
4433 bytes, so that in the next round, we likely get
4434 maxlen > (unsigned int) count + 1
4435 and so we don't get here again.
4436 And allocate proportionally, to avoid looping
4437 eternally if snprintf() reports a too small
4441 ((unsigned int) count + 2
4442 + TCHARS_PER_DCHAR - 1)
4443 / TCHARS_PER_DCHAR),
4444 xtimes (allocated, 2));
4446 ENSURE_ALLOCATION (n);
4452 #if NEED_PRINTF_UNBOUNDED_PRECISION
4455 /* Handle the precision. */
4458 (TCHAR_T *) (result + length);
4462 size_t prefix_count;
4466 /* Put the additional zeroes after the sign. */
4468 && (*prec_ptr == '-' || *prec_ptr == '+'
4469 || *prec_ptr == ' '))
4471 /* Put the additional zeroes after the 0x prefix if
4472 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
4474 && prec_ptr[0] == '0'
4475 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
4478 move = count - prefix_count;
4479 if (precision > move)
4481 /* Insert zeroes. */
4482 size_t insert = precision - move;
4488 (count + insert + TCHARS_PER_DCHAR - 1)
4489 / TCHARS_PER_DCHAR);
4490 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4491 ENSURE_ALLOCATION (n);
4492 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4493 prec_ptr = (TCHAR_T *) (result + length);
4496 prec_end = prec_ptr + count;
4497 prec_ptr += prefix_count;
4499 while (prec_end > prec_ptr)
4502 prec_end[insert] = prec_end[0];
4508 while (prec_end > prec_ptr);
4516 if (count >= tmp_length)
4517 /* tmp_length was incorrectly calculated - fix the
4523 /* Convert from TCHAR_T[] to DCHAR_T[]. */
4524 if (dp->conversion == 'c' || dp->conversion == 's')
4526 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
4528 The result string is not certainly ASCII. */
4529 const TCHAR_T *tmpsrc;
4532 /* This code assumes that TCHAR_T is 'char'. */
4533 typedef int TCHAR_T_verify
4534 [2 * (sizeof (TCHAR_T) == 1) - 1];
4536 tmpsrc = (TCHAR_T *) (result + length);
4542 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
4543 iconveh_question_mark,
4546 &tmpdst, &tmpdst_len)
4549 int saved_errno = errno;
4550 if (!(result == resultbuf || result == NULL))
4552 if (buf_malloced != NULL)
4553 free (buf_malloced);
4555 errno = saved_errno;
4558 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
4559 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
4565 /* The result string is ASCII.
4566 Simple 1:1 conversion. */
4568 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
4569 no-op conversion, in-place on the array starting
4570 at (result + length). */
4571 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
4574 const TCHAR_T *tmpsrc;
4579 if (result == resultbuf)
4581 tmpsrc = (TCHAR_T *) (result + length);
4582 /* ENSURE_ALLOCATION will not move tmpsrc
4583 (because it's part of resultbuf). */
4584 ENSURE_ALLOCATION (xsum (length, count));
4588 /* ENSURE_ALLOCATION will move the array
4589 (because it uses realloc(). */
4590 ENSURE_ALLOCATION (xsum (length, count));
4591 tmpsrc = (TCHAR_T *) (result + length);
4595 ENSURE_ALLOCATION (xsum (length, count));
4597 tmpdst = result + length;
4598 /* Copy backwards, because of overlapping. */
4601 for (n = count; n > 0; n--)
4602 *--tmpdst = (unsigned char) *--tmpsrc;
4607 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4608 /* Make room for the result. */
4609 if (count > allocated - length)
4611 /* Need at least count elements. But allocate
4614 xmax (xsum (length, count), xtimes (allocated, 2));
4616 ENSURE_ALLOCATION (n);
4620 /* Here count <= allocated - length. */
4622 /* Perform padding. */
4623 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4624 if (pad_ourselves && has_width)
4627 # if ENABLE_UNISTDIO
4628 /* Outside POSIX, it's preferrable to compare the width
4629 against the number of _characters_ of the converted
4631 w = DCHAR_MBSNLEN (result + length, count);
4633 /* The width is compared against the number of _bytes_
4634 of the converted value, says POSIX. */
4639 size_t pad = width - w;
4641 /* Make room for the result. */
4642 if (xsum (count, pad) > allocated - length)
4644 /* Need at least count + pad elements. But
4645 allocate proportionally. */
4647 xmax (xsum3 (length, count, pad),
4648 xtimes (allocated, 2));
4652 ENSURE_ALLOCATION (n);
4655 ENSURE_ALLOCATION (n);
4658 /* Here count + pad <= allocated - length. */
4661 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
4662 DCHAR_T * const rp = result + length;
4664 DCHAR_T * const rp = tmp;
4666 DCHAR_T *p = rp + count;
4667 DCHAR_T *end = p + pad;
4669 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4670 if (dp->conversion == 'c'
4671 || dp->conversion == 's')
4672 /* No zero-padding for string directives. */
4677 pad_ptr = (*rp == '-' ? rp + 1 : rp);
4678 /* No zero-padding of "inf" and "nan". */
4679 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
4680 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
4683 /* The generated string now extends from rp to p,
4684 with the zero padding insertion point being at
4687 count = count + pad; /* = end - rp */
4689 if (flags & FLAG_LEFT)
4691 /* Pad with spaces on the right. */
4692 for (; pad > 0; pad--)
4695 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4697 /* Pad with zeroes. */
4702 for (; pad > 0; pad--)
4707 /* Pad with spaces on the left. */
4712 for (; pad > 0; pad--)
4720 /* Here still count <= allocated - length. */
4722 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
4723 /* The snprintf() result did fit. */
4725 /* Append the sprintf() result. */
4726 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4733 #if NEED_PRINTF_DIRECTIVE_F
4734 if (dp->conversion == 'F')
4736 /* Convert the %f result to upper case for %F. */
4737 DCHAR_T *rp = result + length;
4739 for (rc = count; rc > 0; rc--, rp++)
4740 if (*rp >= 'a' && *rp <= 'z')
4741 *rp = *rp - 'a' + 'A';
4752 /* Add the final NUL. */
4753 ENSURE_ALLOCATION (xsum (length, 1));
4754 result[length] = '\0';
4756 if (result != resultbuf && length + 1 < allocated)
4758 /* Shrink the allocated memory if possible. */
4761 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
4766 if (buf_malloced != NULL)
4767 free (buf_malloced);
4770 /* Note that we can produce a big string of a length > INT_MAX. POSIX
4771 says that snprintf() fails with errno = EOVERFLOW in this case, but
4772 that's only because snprintf() returns an 'int'. This function does
4773 not have this limitation. */
4778 if (!(result == resultbuf || result == NULL))
4780 if (buf_malloced != NULL)
4781 free (buf_malloced);
4788 if (!(result == resultbuf || result == NULL))
4790 if (buf_malloced != NULL)
4791 free (buf_malloced);
4799 #undef TCHARS_PER_DCHAR
4806 #undef DCHAR_IS_TCHAR