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 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
184 # define USE_SNPRINTF 1
186 # define USE_SNPRINTF 0
188 # if HAVE_DECL__SNPRINTF
190 # define SNPRINTF _snprintf
193 # define SNPRINTF snprintf
194 /* Here we need to call the native snprintf, not rpl_snprintf. */
198 /* Here we need to call the native sprintf, not rpl_sprintf. */
201 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
202 /* Determine the decimal-point character according to the current locale. */
203 # ifndef decimal_point_char_defined
204 # define decimal_point_char_defined 1
206 decimal_point_char ()
209 /* Determine it in a multithread-safe way. We know nl_langinfo is
210 multithread-safe on glibc systems, but is not required to be multithread-
211 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
212 is rarely multithread-safe. */
213 # if HAVE_NL_LANGINFO && __GLIBC__
214 point = nl_langinfo (RADIXCHAR);
217 sprintf (pointbuf, "%#.0f", 1.0);
218 point = &pointbuf[1];
220 point = localeconv () -> decimal_point;
222 /* The decimal point is always a single byte: either '.' or ','. */
223 return (point[0] != '\0' ? point[0] : '.');
228 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
230 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
232 is_infinite_or_zero (double x)
234 return isnand (x) || x + x == x;
239 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
241 /* Equivalent to !isfinite(x), but does not require libm. */
243 is_infinitel (long double x)
245 return isnanl (x) || (x + x == x && x != 0.0L);
250 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
252 /* Converting 'long double' to decimal without rare rounding bugs requires
253 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
254 (and slower) algorithms. */
256 typedef unsigned int mp_limb_t;
257 # define GMP_LIMB_BITS 32
258 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
260 typedef unsigned long long mp_twolimb_t;
261 # define GMP_TWOLIMB_BITS 64
262 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
264 /* Representation of a bignum >= 0. */
268 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
271 /* Compute the product of two bignums >= 0.
272 Return the allocated memory in case of success, NULL in case of memory
273 allocation failure. */
275 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
282 if (src1.nlimbs <= src2.nlimbs)
296 /* Now 0 <= len1 <= len2. */
299 /* src1 or src2 is zero. */
301 dest->limbs = (mp_limb_t *) malloc (1);
305 /* Here 1 <= len1 <= len2. */
311 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
314 for (k = len2; k > 0; )
316 for (i = 0; i < len1; i++)
318 mp_limb_t digit1 = p1[i];
319 mp_twolimb_t carry = 0;
320 for (j = 0; j < len2; j++)
322 mp_limb_t digit2 = p2[j];
323 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
325 dp[i + j] = (mp_limb_t) carry;
326 carry = carry >> GMP_LIMB_BITS;
328 dp[i + len2] = (mp_limb_t) carry;
331 while (dlen > 0 && dp[dlen - 1] == 0)
339 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
340 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
342 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
344 Return the allocated memory in case of success, NULL in case of memory
345 allocation failure. */
347 divide (mpn_t a, mpn_t b, mpn_t *q)
350 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
351 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
352 If m<n, then q:=0 and r:=a.
353 If m>=n=1, perform a single-precision division:
356 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
357 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
358 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
359 Normalise [q[m-1],...,q[0]], yields q.
360 If m>=n>1, perform a multiple-precision division:
361 We have a/b < beta^(m-n+1).
362 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
363 Shift a and b left by s bits, copying them. r:=a.
364 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
365 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
367 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
368 In case of overflow (q* >= beta) set q* := beta-1.
369 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
370 and c3 := b[n-2] * q*.
371 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
372 occurred. Furthermore 0 <= c3 < beta^2.
373 If there was overflow and
374 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
375 the next test can be skipped.}
376 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
377 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
379 Put r := r - b * q* * beta^j. In detail:
380 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
381 hence: u:=0, for i:=0 to n-1 do
383 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
384 u:=u div beta (+ 1, if carry in subtraction)
386 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
388 the carry u does not overflow.}
389 If a negative carry occurs, put q* := q* - 1
390 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
392 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
393 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
395 The room for q[j] can be allocated at the memory location of r[n+j].
396 Finally, round-to-even:
397 Shift r left by 1 bit.
398 If r > b or if r = b and q[0] is odd, q := q+1.
400 const mp_limb_t *a_ptr = a.limbs;
401 size_t a_len = a.nlimbs;
402 const mp_limb_t *b_ptr = b.limbs;
403 size_t b_len = b.nlimbs;
405 mp_limb_t *tmp_roomptr = NULL;
411 /* Allocate room for a_len+2 digits.
412 (Need a_len+1 digits for the real division and 1 more digit for the
413 final rounding of q.) */
414 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
419 while (a_len > 0 && a_ptr[a_len - 1] == 0)
426 /* Division by zero. */
428 if (b_ptr[b_len - 1] == 0)
434 /* Here m = a_len >= 0 and n = b_len > 0. */
438 /* m<n: trivial case. q=0, r := copy of a. */
441 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
442 q_ptr = roomptr + a_len;
447 /* n=1: single precision division.
448 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
452 mp_limb_t den = b_ptr[0];
453 mp_limb_t remainder = 0;
454 const mp_limb_t *sourceptr = a_ptr + a_len;
455 mp_limb_t *destptr = q_ptr + a_len;
457 for (count = a_len; count > 0; count--)
460 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
461 *--destptr = num / den;
462 remainder = num % den;
464 /* Normalise and store r. */
467 r_ptr[0] = remainder;
474 if (q_ptr[q_len - 1] == 0)
480 /* n>1: multiple precision division.
481 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
482 beta^(m-n-1) <= a/b < beta^(m-n+1). */
486 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
514 /* 0 <= s < GMP_LIMB_BITS.
515 Copy b, shifting it left by s bits. */
518 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
519 if (tmp_roomptr == NULL)
525 const mp_limb_t *sourceptr = b_ptr;
526 mp_limb_t *destptr = tmp_roomptr;
527 mp_twolimb_t accu = 0;
529 for (count = b_len; count > 0; count--)
531 accu += (mp_twolimb_t) *sourceptr++ << s;
532 *destptr++ = (mp_limb_t) accu;
533 accu = accu >> GMP_LIMB_BITS;
535 /* accu must be zero, since that was how s was determined. */
541 /* Copy a, shifting it left by s bits, yields r.
543 At the beginning: r = roomptr[0..a_len],
544 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
548 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
553 const mp_limb_t *sourceptr = a_ptr;
554 mp_limb_t *destptr = r_ptr;
555 mp_twolimb_t accu = 0;
557 for (count = a_len; count > 0; count--)
559 accu += (mp_twolimb_t) *sourceptr++ << s;
560 *destptr++ = (mp_limb_t) accu;
561 accu = accu >> GMP_LIMB_BITS;
563 *destptr++ = (mp_limb_t) accu;
565 q_ptr = roomptr + b_len;
566 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
568 size_t j = a_len - b_len; /* m-n */
569 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
570 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
571 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
572 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
573 /* Division loop, traversed m-n+1 times.
574 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
579 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
581 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
583 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
584 | r_ptr[j + b_len - 1];
585 q_star = num / b_msd;
590 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
591 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
592 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
593 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
594 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
596 If yes, jump directly to the subtraction loop.
597 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
598 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
599 if (r_ptr[j + b_len] > b_msd
600 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
601 /* r[j+n] >= b[n-1]+1 or
602 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
607 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
609 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
610 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
611 mp_twolimb_t c3 = /* b[n-2] * q* */
612 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
613 /* While c2 < c3, increase c2 and decrease c3.
614 Consider c3-c2. While it is > 0, decrease it by
615 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
616 this can happen only twice. */
619 q_star = q_star - 1; /* q* := q* - 1 */
620 if (c3 - c2 > b_msdd)
621 q_star = q_star - 1; /* q* := q* - 1 */
627 /* Subtract r := r - b * q* * beta^j. */
630 const mp_limb_t *sourceptr = b_ptr;
631 mp_limb_t *destptr = r_ptr + j;
632 mp_twolimb_t carry = 0;
634 for (count = b_len; count > 0; count--)
636 /* Here 0 <= carry <= q*. */
639 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
640 + (mp_limb_t) ~(*destptr);
641 /* Here 0 <= carry <= beta*q* + beta-1. */
642 *destptr++ = ~(mp_limb_t) carry;
643 carry = carry >> GMP_LIMB_BITS; /* <= q* */
645 cr = (mp_limb_t) carry;
647 /* Subtract cr from r_ptr[j + b_len], then forget about
649 if (cr > r_ptr[j + b_len])
651 /* Subtraction gave a carry. */
652 q_star = q_star - 1; /* q* := q* - 1 */
655 const mp_limb_t *sourceptr = b_ptr;
656 mp_limb_t *destptr = r_ptr + j;
659 for (count = b_len; count > 0; count--)
661 mp_limb_t source1 = *sourceptr++;
662 mp_limb_t source2 = *destptr;
663 *destptr++ = source1 + source2 + carry;
666 ? source1 >= (mp_limb_t) ~source2
667 : source1 > (mp_limb_t) ~source2);
670 /* Forget about the carry and about r[j+n]. */
673 /* q* is determined. Store it as q[j]. */
682 if (q_ptr[q_len - 1] == 0)
684 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
685 b is shifted left by s bits. */
686 /* Shift r right by s bits. */
689 mp_limb_t ptr = r_ptr + r_len;
690 mp_twolimb_t accu = 0;
692 for (count = r_len; count > 0; count--)
694 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
695 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
696 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
701 while (r_len > 0 && r_ptr[r_len - 1] == 0)
704 /* Compare r << 1 with b. */
712 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
713 | (i < r_len ? r_ptr[i] << 1 : 0);
714 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
724 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
729 for (i = 0; i < q_len; i++)
730 if (++(q_ptr[i]) != 0)
735 if (tmp_roomptr != NULL)
742 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
744 Destroys the contents of a.
745 Return the allocated memory - containing the decimal digits in low-to-high
746 order, terminated with a NUL character - in case of success, NULL in case
747 of memory allocation failure. */
749 convert_to_decimal (mpn_t a, size_t extra_zeroes)
751 mp_limb_t *a_ptr = a.limbs;
752 size_t a_len = a.nlimbs;
753 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
754 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
755 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
759 for (; extra_zeroes > 0; extra_zeroes--)
763 /* Divide a by 10^9, in-place. */
764 mp_limb_t remainder = 0;
765 mp_limb_t *ptr = a_ptr + a_len;
767 for (count = a_len; count > 0; count--)
770 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
771 *ptr = num / 1000000000;
772 remainder = num % 1000000000;
774 /* Store the remainder as 9 decimal digits. */
775 for (count = 9; count > 0; count--)
777 *d_ptr++ = '0' + (remainder % 10);
778 remainder = remainder / 10;
781 if (a_ptr[a_len - 1] == 0)
784 /* Remove leading zeroes. */
785 while (d_ptr > c_ptr && d_ptr[-1] == '0')
787 /* But keep at least one zero. */
790 /* Terminate the string. */
796 # if NEED_PRINTF_LONG_DOUBLE
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;
869 #if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
875 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
878 *ep = exp - LDBL_MANT_BIT;
884 # if NEED_PRINTF_DOUBLE
886 /* Assuming x is finite and >= 0:
887 write x as x = 2^e * m, where m is a bignum.
888 Return the allocated memory in case of success, NULL in case of memory
889 allocation failure. */
891 decode_double (double x, int *ep, mpn_t *mp)
898 /* Allocate memory for result. */
899 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
900 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
903 /* Split into exponential part and mantissa. */
905 if (!(y >= 0.0 && y < 1.0))
907 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
908 latter is an integer. */
909 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
910 I'm not sure whether it's safe to cast a 'double' value between
911 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
912 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
914 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
915 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
918 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
921 if (!(y >= 0.0 && y < 1.0))
923 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
926 if (!(y >= 0.0 && y < 1.0))
928 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
933 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
936 if (!(y >= 0.0 && y < 1.0))
938 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
942 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
945 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
948 if (!(y >= 0.0 && y < 1.0))
950 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
953 if (!(y >= 0.0 && y < 1.0))
955 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
960 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
963 *ep = exp - DBL_MANT_BIT;
969 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
970 Returns the decimal representation of round (x * 10^n).
971 Return the allocated memory - containing the decimal digits in low-to-high
972 order, terminated with a NUL character - in case of success, NULL in case
973 of memory allocation failure. */
975 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
983 unsigned int s_limbs;
992 /* x = 2^e * m, hence
993 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
994 = round (2^s * 5^n * m). */
997 /* Factor out a common power of 10 if possible. */
1000 extra_zeroes = (s < n ? s : n);
1004 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1005 Before converting to decimal, we need to compute
1006 z = round (2^s * 5^n * m). */
1007 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1008 sign. 2.322 is slightly larger than log(5)/log(2). */
1009 abs_n = (n >= 0 ? n : -n);
1010 abs_s = (s >= 0 ? s : -s);
1011 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1012 + abs_s / GMP_LIMB_BITS + 1)
1013 * sizeof (mp_limb_t));
1014 if (pow5_ptr == NULL)
1019 /* Initialize with 1. */
1022 /* Multiply with 5^|n|. */
1025 static mp_limb_t const small_pow5[13 + 1] =
1027 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1028 48828125, 244140625, 1220703125
1031 for (n13 = 0; n13 <= abs_n; n13 += 13)
1033 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1035 mp_twolimb_t carry = 0;
1036 for (j = 0; j < pow5_len; j++)
1038 mp_limb_t digit2 = pow5_ptr[j];
1039 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1040 pow5_ptr[j] = (mp_limb_t) carry;
1041 carry = carry >> GMP_LIMB_BITS;
1044 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1047 s_limbs = abs_s / GMP_LIMB_BITS;
1048 s_bits = abs_s % GMP_LIMB_BITS;
1049 if (n >= 0 ? s >= 0 : s <= 0)
1051 /* Multiply with 2^|s|. */
1054 mp_limb_t *ptr = pow5_ptr;
1055 mp_twolimb_t accu = 0;
1057 for (count = pow5_len; count > 0; count--)
1059 accu += (mp_twolimb_t) *ptr << s_bits;
1060 *ptr++ = (mp_limb_t) accu;
1061 accu = accu >> GMP_LIMB_BITS;
1065 *ptr = (mp_limb_t) accu;
1072 for (count = pow5_len; count > 0;)
1075 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1077 for (count = s_limbs; count > 0;)
1080 pow5_ptr[count] = 0;
1082 pow5_len += s_limbs;
1084 pow5.limbs = pow5_ptr;
1085 pow5.nlimbs = pow5_len;
1088 /* Multiply m with pow5. No division needed. */
1089 z_memory = multiply (m, pow5, &z);
1093 /* Divide m by pow5 and round. */
1094 z_memory = divide (m, pow5, &z);
1099 pow5.limbs = pow5_ptr;
1100 pow5.nlimbs = pow5_len;
1104 Multiply m with pow5, then divide by 2^|s|. */
1108 tmp_memory = multiply (m, pow5, &numerator);
1109 if (tmp_memory == NULL)
1115 /* Construct 2^|s|. */
1117 mp_limb_t *ptr = pow5_ptr + pow5_len;
1119 for (i = 0; i < s_limbs; i++)
1121 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1122 denominator.limbs = ptr;
1123 denominator.nlimbs = s_limbs + 1;
1125 z_memory = divide (numerator, denominator, &z);
1131 Multiply m with 2^s, then divide by pow5. */
1134 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1135 * sizeof (mp_limb_t));
1136 if (num_ptr == NULL)
1143 mp_limb_t *destptr = num_ptr;
1146 for (i = 0; i < s_limbs; i++)
1151 const mp_limb_t *sourceptr = m.limbs;
1152 mp_twolimb_t accu = 0;
1154 for (count = m.nlimbs; count > 0; count--)
1156 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1157 *destptr++ = (mp_limb_t) accu;
1158 accu = accu >> GMP_LIMB_BITS;
1161 *destptr++ = (mp_limb_t) accu;
1165 const mp_limb_t *sourceptr = m.limbs;
1167 for (count = m.nlimbs; count > 0; count--)
1168 *destptr++ = *sourceptr++;
1170 numerator.limbs = num_ptr;
1171 numerator.nlimbs = destptr - num_ptr;
1173 z_memory = divide (numerator, pow5, &z);
1180 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1182 if (z_memory == NULL)
1184 digits = convert_to_decimal (z, extra_zeroes);
1189 # if NEED_PRINTF_LONG_DOUBLE
1191 /* Assuming x is finite and >= 0, and n is an integer:
1192 Returns the decimal representation of round (x * 10^n).
1193 Return the allocated memory - containing the decimal digits in low-to-high
1194 order, terminated with a NUL character - in case of success, NULL in case
1195 of memory allocation failure. */
1197 scale10_round_decimal_long_double (long double x, int n)
1201 void *memory = decode_long_double (x, &e, &m);
1202 return scale10_round_decimal_decoded (e, m, memory, n);
1207 # if NEED_PRINTF_DOUBLE
1209 /* Assuming x is finite and >= 0, and n is an integer:
1210 Returns the decimal representation of round (x * 10^n).
1211 Return the allocated memory - containing the decimal digits in low-to-high
1212 order, terminated with a NUL character - in case of success, NULL in case
1213 of memory allocation failure. */
1215 scale10_round_decimal_double (double x, int n)
1219 void *memory = decode_double (x, &e, &m);
1220 return scale10_round_decimal_decoded (e, m, memory, n);
1225 # if NEED_PRINTF_LONG_DOUBLE
1227 /* Assuming x is finite and > 0:
1228 Return an approximation for n with 10^n <= x < 10^(n+1).
1229 The approximation is usually the right n, but may be off by 1 sometimes. */
1231 floorlog10l (long double x)
1238 /* Split into exponential part and mantissa. */
1239 y = frexpl (x, &exp);
1240 if (!(y >= 0.0L && y < 1.0L))
1246 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1248 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1249 exp -= GMP_LIMB_BITS;
1251 if (y < (1.0L / (1 << 16)))
1253 y *= 1.0L * (1 << 16);
1256 if (y < (1.0L / (1 << 8)))
1258 y *= 1.0L * (1 << 8);
1261 if (y < (1.0L / (1 << 4)))
1263 y *= 1.0L * (1 << 4);
1266 if (y < (1.0L / (1 << 2)))
1268 y *= 1.0L * (1 << 2);
1271 if (y < (1.0L / (1 << 1)))
1273 y *= 1.0L * (1 << 1);
1277 if (!(y >= 0.5L && y < 1.0L))
1279 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1282 if (z < 0.70710678118654752444)
1284 z *= 1.4142135623730950488;
1287 if (z < 0.8408964152537145431)
1289 z *= 1.1892071150027210667;
1292 if (z < 0.91700404320467123175)
1294 z *= 1.0905077326652576592;
1297 if (z < 0.9576032806985736469)
1299 z *= 1.0442737824274138403;
1302 /* Now 0.95 <= z <= 1.01. */
1304 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1305 Four terms are enough to get an approximation with error < 10^-7. */
1306 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1307 /* Finally multiply with log(2)/log(10), yields an approximation for
1309 l *= 0.30102999566398119523;
1310 /* Round down to the next integer. */
1311 return (int) l + (l < 0 ? -1 : 0);
1316 # if NEED_PRINTF_DOUBLE
1318 /* Assuming x is finite and > 0:
1319 Return an approximation for n with 10^n <= x < 10^(n+1).
1320 The approximation is usually the right n, but may be off by 1 sometimes. */
1322 floorlog10 (double x)
1329 /* Split into exponential part and mantissa. */
1330 y = frexp (x, &exp);
1331 if (!(y >= 0.0 && y < 1.0))
1337 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1339 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1340 exp -= GMP_LIMB_BITS;
1342 if (y < (1.0 / (1 << 16)))
1344 y *= 1.0 * (1 << 16);
1347 if (y < (1.0 / (1 << 8)))
1349 y *= 1.0 * (1 << 8);
1352 if (y < (1.0 / (1 << 4)))
1354 y *= 1.0 * (1 << 4);
1357 if (y < (1.0 / (1 << 2)))
1359 y *= 1.0 * (1 << 2);
1362 if (y < (1.0 / (1 << 1)))
1364 y *= 1.0 * (1 << 1);
1368 if (!(y >= 0.5 && y < 1.0))
1370 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1373 if (z < 0.70710678118654752444)
1375 z *= 1.4142135623730950488;
1378 if (z < 0.8408964152537145431)
1380 z *= 1.1892071150027210667;
1383 if (z < 0.91700404320467123175)
1385 z *= 1.0905077326652576592;
1388 if (z < 0.9576032806985736469)
1390 z *= 1.0442737824274138403;
1393 /* Now 0.95 <= z <= 1.01. */
1395 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1396 Four terms are enough to get an approximation with error < 10^-7. */
1397 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1398 /* Finally multiply with log(2)/log(10), yields an approximation for
1400 l *= 0.30102999566398119523;
1401 /* Round down to the next integer. */
1402 return (int) l + (l < 0 ? -1 : 0);
1410 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1411 const FCHAR_T *format, va_list args)
1416 if (PRINTF_PARSE (format, &d, &a) < 0)
1417 /* errno is already set. */
1425 if (PRINTF_FETCHARGS (args, &a) < 0)
1433 size_t buf_neededlength;
1435 TCHAR_T *buf_malloced;
1439 /* Output string accumulator. */
1444 /* Allocate a small buffer that will hold a directive passed to
1445 sprintf or snprintf. */
1447 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1449 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1451 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1452 buf_malloced = NULL;
1457 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1458 if (size_overflow_p (buf_memsize))
1459 goto out_of_memory_1;
1460 buf = (TCHAR_T *) malloc (buf_memsize);
1462 goto out_of_memory_1;
1466 if (resultbuf != NULL)
1469 allocated = *lengthp;
1478 result is either == resultbuf or == NULL or malloc-allocated.
1479 If length > 0, then result != NULL. */
1481 /* Ensures that allocated >= needed. Aborts through a jump to
1482 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1483 #define ENSURE_ALLOCATION(needed) \
1484 if ((needed) > allocated) \
1486 size_t memory_size; \
1489 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1490 if ((needed) > allocated) \
1491 allocated = (needed); \
1492 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1493 if (size_overflow_p (memory_size)) \
1494 goto out_of_memory; \
1495 if (result == resultbuf || result == NULL) \
1496 memory = (DCHAR_T *) malloc (memory_size); \
1498 memory = (DCHAR_T *) realloc (result, memory_size); \
1499 if (memory == NULL) \
1500 goto out_of_memory; \
1501 if (result == resultbuf && length > 0) \
1502 DCHAR_CPY (memory, result, length); \
1506 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1508 if (cp != dp->dir_start)
1510 size_t n = dp->dir_start - cp;
1511 size_t augmented_length = xsum (length, n);
1513 ENSURE_ALLOCATION (augmented_length);
1514 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1515 need that the format string contains only ASCII characters
1516 if FCHAR_T and DCHAR_T are not the same type. */
1517 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1519 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1520 length = augmented_length;
1525 result[length++] = (unsigned char) *cp++;
1532 /* Execute a single directive. */
1533 if (dp->conversion == '%')
1535 size_t augmented_length;
1537 if (!(dp->arg_index == ARG_NONE))
1539 augmented_length = xsum (length, 1);
1540 ENSURE_ALLOCATION (augmented_length);
1541 result[length] = '%';
1542 length = augmented_length;
1546 if (!(dp->arg_index != ARG_NONE))
1549 if (dp->conversion == 'n')
1551 switch (a.arg[dp->arg_index].type)
1553 case TYPE_COUNT_SCHAR_POINTER:
1554 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1556 case TYPE_COUNT_SHORT_POINTER:
1557 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1559 case TYPE_COUNT_INT_POINTER:
1560 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1562 case TYPE_COUNT_LONGINT_POINTER:
1563 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1565 #if HAVE_LONG_LONG_INT
1566 case TYPE_COUNT_LONGLONGINT_POINTER:
1567 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1575 /* The unistdio extensions. */
1576 else if (dp->conversion == 'U')
1578 arg_type type = a.arg[dp->arg_index].type;
1579 int flags = dp->flags;
1587 if (dp->width_start != dp->width_end)
1589 if (dp->width_arg_index != ARG_NONE)
1593 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1595 arg = a.arg[dp->width_arg_index].a.a_int;
1598 /* "A negative field width is taken as a '-' flag
1599 followed by a positive field width." */
1601 width = (unsigned int) (-arg);
1608 const FCHAR_T *digitp = dp->width_start;
1611 width = xsum (xtimes (width, 10), *digitp++ - '0');
1612 while (digitp != dp->width_end);
1619 if (dp->precision_start != dp->precision_end)
1621 if (dp->precision_arg_index != ARG_NONE)
1625 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1627 arg = a.arg[dp->precision_arg_index].a.a_int;
1628 /* "A negative precision is taken as if the precision
1638 const FCHAR_T *digitp = dp->precision_start + 1;
1641 while (digitp != dp->precision_end)
1642 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1649 case TYPE_U8_STRING:
1651 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1652 const uint8_t *arg_end;
1657 /* Use only PRECISION characters, from the left. */
1660 for (; precision > 0; precision--)
1662 int count = u8_strmblen (arg_end);
1667 if (!(result == resultbuf || result == NULL))
1669 if (buf_malloced != NULL)
1670 free (buf_malloced);
1681 /* Use the entire string, and count the number of
1687 int count = u8_strmblen (arg_end);
1692 if (!(result == resultbuf || result == NULL))
1694 if (buf_malloced != NULL)
1695 free (buf_malloced);
1706 /* Use the entire string. */
1707 arg_end = arg + u8_strlen (arg);
1708 /* The number of characters doesn't matter. */
1712 if (has_width && width > characters
1713 && !(dp->flags & FLAG_LEFT))
1715 size_t n = width - characters;
1716 ENSURE_ALLOCATION (xsum (length, n));
1717 DCHAR_SET (result + length, ' ', n);
1721 # if DCHAR_IS_UINT8_T
1723 size_t n = arg_end - arg;
1724 ENSURE_ALLOCATION (xsum (length, n));
1725 DCHAR_CPY (result + length, arg, n);
1730 DCHAR_T *converted = result + length;
1731 size_t converted_len = allocated - length;
1733 /* Convert from UTF-8 to locale encoding. */
1734 if (u8_conv_to_encoding (locale_charset (),
1735 iconveh_question_mark,
1736 arg, arg_end - arg, NULL,
1737 &converted, &converted_len)
1740 /* Convert from UTF-8 to UTF-16/UTF-32. */
1742 U8_TO_DCHAR (arg, arg_end - arg,
1743 converted, &converted_len);
1744 if (converted == NULL)
1747 int saved_errno = errno;
1748 if (!(result == resultbuf || result == NULL))
1750 if (buf_malloced != NULL)
1751 free (buf_malloced);
1753 errno = saved_errno;
1756 if (converted != result + length)
1758 ENSURE_ALLOCATION (xsum (length, converted_len));
1759 DCHAR_CPY (result + length, converted, converted_len);
1762 length += converted_len;
1766 if (has_width && width > characters
1767 && (dp->flags & FLAG_LEFT))
1769 size_t n = width - characters;
1770 ENSURE_ALLOCATION (xsum (length, n));
1771 DCHAR_SET (result + length, ' ', n);
1777 case TYPE_U16_STRING:
1779 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1780 const uint16_t *arg_end;
1785 /* Use only PRECISION characters, from the left. */
1788 for (; precision > 0; precision--)
1790 int count = u16_strmblen (arg_end);
1795 if (!(result == resultbuf || result == NULL))
1797 if (buf_malloced != NULL)
1798 free (buf_malloced);
1809 /* Use the entire string, and count the number of
1815 int count = u16_strmblen (arg_end);
1820 if (!(result == resultbuf || result == NULL))
1822 if (buf_malloced != NULL)
1823 free (buf_malloced);
1834 /* Use the entire string. */
1835 arg_end = arg + u16_strlen (arg);
1836 /* The number of characters doesn't matter. */
1840 if (has_width && width > characters
1841 && !(dp->flags & FLAG_LEFT))
1843 size_t n = width - characters;
1844 ENSURE_ALLOCATION (xsum (length, n));
1845 DCHAR_SET (result + length, ' ', n);
1849 # if DCHAR_IS_UINT16_T
1851 size_t n = arg_end - arg;
1852 ENSURE_ALLOCATION (xsum (length, n));
1853 DCHAR_CPY (result + length, arg, n);
1858 DCHAR_T *converted = result + length;
1859 size_t converted_len = allocated - length;
1861 /* Convert from UTF-16 to locale encoding. */
1862 if (u16_conv_to_encoding (locale_charset (),
1863 iconveh_question_mark,
1864 arg, arg_end - arg, NULL,
1865 &converted, &converted_len)
1868 /* Convert from UTF-16 to UTF-8/UTF-32. */
1870 U16_TO_DCHAR (arg, arg_end - arg,
1871 converted, &converted_len);
1872 if (converted == NULL)
1875 int saved_errno = errno;
1876 if (!(result == resultbuf || result == NULL))
1878 if (buf_malloced != NULL)
1879 free (buf_malloced);
1881 errno = saved_errno;
1884 if (converted != result + length)
1886 ENSURE_ALLOCATION (xsum (length, converted_len));
1887 DCHAR_CPY (result + length, converted, converted_len);
1890 length += converted_len;
1894 if (has_width && width > characters
1895 && (dp->flags & FLAG_LEFT))
1897 size_t n = width - characters;
1898 ENSURE_ALLOCATION (xsum (length, n));
1899 DCHAR_SET (result + length, ' ', n);
1905 case TYPE_U32_STRING:
1907 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1908 const uint32_t *arg_end;
1913 /* Use only PRECISION characters, from the left. */
1916 for (; precision > 0; precision--)
1918 int count = u32_strmblen (arg_end);
1923 if (!(result == resultbuf || result == NULL))
1925 if (buf_malloced != NULL)
1926 free (buf_malloced);
1937 /* Use the entire string, and count the number of
1943 int count = u32_strmblen (arg_end);
1948 if (!(result == resultbuf || result == NULL))
1950 if (buf_malloced != NULL)
1951 free (buf_malloced);
1962 /* Use the entire string. */
1963 arg_end = arg + u32_strlen (arg);
1964 /* The number of characters doesn't matter. */
1968 if (has_width && width > characters
1969 && !(dp->flags & FLAG_LEFT))
1971 size_t n = width - characters;
1972 ENSURE_ALLOCATION (xsum (length, n));
1973 DCHAR_SET (result + length, ' ', n);
1977 # if DCHAR_IS_UINT32_T
1979 size_t n = arg_end - arg;
1980 ENSURE_ALLOCATION (xsum (length, n));
1981 DCHAR_CPY (result + length, arg, n);
1986 DCHAR_T *converted = result + length;
1987 size_t converted_len = allocated - length;
1989 /* Convert from UTF-32 to locale encoding. */
1990 if (u32_conv_to_encoding (locale_charset (),
1991 iconveh_question_mark,
1992 arg, arg_end - arg, NULL,
1993 &converted, &converted_len)
1996 /* Convert from UTF-32 to UTF-8/UTF-16. */
1998 U32_TO_DCHAR (arg, arg_end - arg,
1999 converted, &converted_len);
2000 if (converted == NULL)
2003 int saved_errno = errno;
2004 if (!(result == resultbuf || result == NULL))
2006 if (buf_malloced != NULL)
2007 free (buf_malloced);
2009 errno = saved_errno;
2012 if (converted != result + length)
2014 ENSURE_ALLOCATION (xsum (length, converted_len));
2015 DCHAR_CPY (result + length, converted, converted_len);
2018 length += converted_len;
2022 if (has_width && width > characters
2023 && (dp->flags & FLAG_LEFT))
2025 size_t n = width - characters;
2026 ENSURE_ALLOCATION (xsum (length, n));
2027 DCHAR_SET (result + length, ' ', n);
2038 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2039 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2040 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2042 # if NEED_PRINTF_DOUBLE
2043 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2045 # if NEED_PRINTF_LONG_DOUBLE
2046 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2052 arg_type type = a.arg[dp->arg_index].type;
2053 int flags = dp->flags;
2059 DCHAR_T tmpbuf[700];
2066 if (dp->width_start != dp->width_end)
2068 if (dp->width_arg_index != ARG_NONE)
2072 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2074 arg = a.arg[dp->width_arg_index].a.a_int;
2077 /* "A negative field width is taken as a '-' flag
2078 followed by a positive field width." */
2080 width = (unsigned int) (-arg);
2087 const FCHAR_T *digitp = dp->width_start;
2090 width = xsum (xtimes (width, 10), *digitp++ - '0');
2091 while (digitp != dp->width_end);
2098 if (dp->precision_start != dp->precision_end)
2100 if (dp->precision_arg_index != ARG_NONE)
2104 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2106 arg = a.arg[dp->precision_arg_index].a.a_int;
2107 /* "A negative precision is taken as if the precision
2117 const FCHAR_T *digitp = dp->precision_start + 1;
2120 while (digitp != dp->precision_end)
2121 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2126 /* Allocate a temporary buffer of sufficient size. */
2127 if (type == TYPE_LONGDOUBLE)
2129 (unsigned int) ((LDBL_DIG + 1)
2130 * 0.831 /* decimal -> hexadecimal */
2132 + 1; /* turn floor into ceil */
2135 (unsigned int) ((DBL_DIG + 1)
2136 * 0.831 /* decimal -> hexadecimal */
2138 + 1; /* turn floor into ceil */
2139 if (tmp_length < precision)
2140 tmp_length = precision;
2141 /* Account for sign, decimal point etc. */
2142 tmp_length = xsum (tmp_length, 12);
2144 if (tmp_length < width)
2147 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2149 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2153 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2155 if (size_overflow_p (tmp_memsize))
2156 /* Overflow, would lead to out of memory. */
2158 tmp = (DCHAR_T *) malloc (tmp_memsize);
2160 /* Out of memory. */
2166 if (type == TYPE_LONGDOUBLE)
2168 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2169 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2173 if (dp->conversion == 'A')
2175 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2179 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2185 DECL_LONG_DOUBLE_ROUNDING
2187 BEGIN_LONG_DOUBLE_ROUNDING ();
2189 if (signbit (arg)) /* arg < 0.0L or negative zero */
2197 else if (flags & FLAG_SHOWSIGN)
2199 else if (flags & FLAG_SPACE)
2202 if (arg > 0.0L && arg + arg == arg)
2204 if (dp->conversion == 'A')
2206 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2210 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2216 long double mantissa;
2219 mantissa = printf_frexpl (arg, &exponent);
2227 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2229 /* Round the mantissa. */
2230 long double tail = mantissa;
2233 for (q = precision; ; q--)
2235 int digit = (int) tail;
2239 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2248 for (q = precision; q > 0; q--)
2254 *p++ = dp->conversion - 'A' + 'X';
2259 digit = (int) mantissa;
2262 if ((flags & FLAG_ALT)
2263 || mantissa > 0.0L || precision > 0)
2265 *p++ = decimal_point_char ();
2266 /* This loop terminates because we assume
2267 that FLT_RADIX is a power of 2. */
2268 while (mantissa > 0.0L)
2271 digit = (int) mantissa;
2276 : dp->conversion - 10);
2280 while (precision > 0)
2287 *p++ = dp->conversion - 'A' + 'P';
2288 # if WIDE_CHAR_VERSION
2290 static const wchar_t decimal_format[] =
2291 { '%', '+', 'd', '\0' };
2292 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2297 if (sizeof (DCHAR_T) == 1)
2299 sprintf ((char *) p, "%+d", exponent);
2307 sprintf (expbuf, "%+d", exponent);
2308 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2314 END_LONG_DOUBLE_ROUNDING ();
2322 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2323 double arg = a.arg[dp->arg_index].a.a_double;
2327 if (dp->conversion == 'A')
2329 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2333 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2340 if (signbit (arg)) /* arg < 0.0 or negative zero */
2348 else if (flags & FLAG_SHOWSIGN)
2350 else if (flags & FLAG_SPACE)
2353 if (arg > 0.0 && arg + arg == arg)
2355 if (dp->conversion == 'A')
2357 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2361 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2370 mantissa = printf_frexp (arg, &exponent);
2378 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2380 /* Round the mantissa. */
2381 double tail = mantissa;
2384 for (q = precision; ; q--)
2386 int digit = (int) tail;
2390 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2399 for (q = precision; q > 0; q--)
2405 *p++ = dp->conversion - 'A' + 'X';
2410 digit = (int) mantissa;
2413 if ((flags & FLAG_ALT)
2414 || mantissa > 0.0 || precision > 0)
2416 *p++ = decimal_point_char ();
2417 /* This loop terminates because we assume
2418 that FLT_RADIX is a power of 2. */
2419 while (mantissa > 0.0)
2422 digit = (int) mantissa;
2427 : dp->conversion - 10);
2431 while (precision > 0)
2438 *p++ = dp->conversion - 'A' + 'P';
2439 # if WIDE_CHAR_VERSION
2441 static const wchar_t decimal_format[] =
2442 { '%', '+', 'd', '\0' };
2443 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2448 if (sizeof (DCHAR_T) == 1)
2450 sprintf ((char *) p, "%+d", exponent);
2458 sprintf (expbuf, "%+d", exponent);
2459 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2469 /* The generated string now extends from tmp to p, with the
2470 zero padding insertion point being at pad_ptr. */
2471 if (has_width && p - tmp < width)
2473 size_t pad = width - (p - tmp);
2474 DCHAR_T *end = p + pad;
2476 if (flags & FLAG_LEFT)
2478 /* Pad with spaces on the right. */
2479 for (; pad > 0; pad--)
2482 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2484 /* Pad with zeroes. */
2489 for (; pad > 0; pad--)
2494 /* Pad with spaces on the left. */
2499 for (; pad > 0; pad--)
2507 size_t count = p - tmp;
2509 if (count >= tmp_length)
2510 /* tmp_length was incorrectly calculated - fix the
2514 /* Make room for the result. */
2515 if (count >= allocated - length)
2517 size_t n = xsum (length, count);
2519 ENSURE_ALLOCATION (n);
2522 /* Append the result. */
2523 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2530 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2531 else if ((dp->conversion == 'f' || dp->conversion == 'F'
2532 || dp->conversion == 'e' || dp->conversion == 'E'
2533 || dp->conversion == 'g' || dp->conversion == 'G'
2534 || dp->conversion == 'a' || dp->conversion == 'A')
2536 # if NEED_PRINTF_DOUBLE
2537 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2538 # elif NEED_PRINTF_INFINITE_DOUBLE
2539 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2540 /* The systems (mingw) which produce wrong output
2541 for Inf, -Inf, and NaN also do so for -0.0.
2542 Therefore we treat this case here as well. */
2543 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2545 # if NEED_PRINTF_LONG_DOUBLE
2546 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2547 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2548 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2549 /* Some systems produce wrong output for Inf,
2551 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
2555 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2556 arg_type type = a.arg[dp->arg_index].type;
2558 int flags = dp->flags;
2564 DCHAR_T tmpbuf[700];
2571 if (dp->width_start != dp->width_end)
2573 if (dp->width_arg_index != ARG_NONE)
2577 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2579 arg = a.arg[dp->width_arg_index].a.a_int;
2582 /* "A negative field width is taken as a '-' flag
2583 followed by a positive field width." */
2585 width = (unsigned int) (-arg);
2592 const FCHAR_T *digitp = dp->width_start;
2595 width = xsum (xtimes (width, 10), *digitp++ - '0');
2596 while (digitp != dp->width_end);
2603 if (dp->precision_start != dp->precision_end)
2605 if (dp->precision_arg_index != ARG_NONE)
2609 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2611 arg = a.arg[dp->precision_arg_index].a.a_int;
2612 /* "A negative precision is taken as if the precision
2622 const FCHAR_T *digitp = dp->precision_start + 1;
2625 while (digitp != dp->precision_end)
2626 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2631 /* POSIX specifies the default precision to be 6 for %f, %F,
2632 %e, %E, but not for %g, %G. Implementations appear to use
2633 the same default precision also for %g, %G. */
2637 /* Allocate a temporary buffer of sufficient size. */
2638 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2639 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
2640 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2641 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2642 # elif NEED_PRINTF_LONG_DOUBLE
2643 tmp_length = LDBL_DIG + 1;
2644 # elif NEED_PRINTF_DOUBLE
2645 tmp_length = DBL_DIG + 1;
2649 if (tmp_length < precision)
2650 tmp_length = precision;
2651 # if NEED_PRINTF_LONG_DOUBLE
2652 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2653 if (type == TYPE_LONGDOUBLE)
2655 if (dp->conversion == 'f' || dp->conversion == 'F')
2657 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2658 if (!(isnanl (arg) || arg + arg == arg))
2660 /* arg is finite and nonzero. */
2661 int exponent = floorlog10l (arg < 0 ? -arg : arg);
2662 if (exponent >= 0 && tmp_length < exponent + precision)
2663 tmp_length = exponent + precision;
2667 # if NEED_PRINTF_DOUBLE
2668 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2669 if (type == TYPE_DOUBLE)
2671 if (dp->conversion == 'f' || dp->conversion == 'F')
2673 double arg = a.arg[dp->arg_index].a.a_double;
2674 if (!(isnand (arg) || arg + arg == arg))
2676 /* arg is finite and nonzero. */
2677 int exponent = floorlog10 (arg < 0 ? -arg : arg);
2678 if (exponent >= 0 && tmp_length < exponent + precision)
2679 tmp_length = exponent + precision;
2683 /* Account for sign, decimal point etc. */
2684 tmp_length = xsum (tmp_length, 12);
2686 if (tmp_length < width)
2689 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2691 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2695 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2697 if (size_overflow_p (tmp_memsize))
2698 /* Overflow, would lead to out of memory. */
2700 tmp = (DCHAR_T *) malloc (tmp_memsize);
2702 /* Out of memory. */
2709 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2710 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2711 if (type == TYPE_LONGDOUBLE)
2714 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2718 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2720 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2724 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2730 DECL_LONG_DOUBLE_ROUNDING
2732 BEGIN_LONG_DOUBLE_ROUNDING ();
2734 if (signbit (arg)) /* arg < 0.0L or negative zero */
2742 else if (flags & FLAG_SHOWSIGN)
2744 else if (flags & FLAG_SPACE)
2747 if (arg > 0.0L && arg + arg == arg)
2749 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2751 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2755 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2760 # if NEED_PRINTF_LONG_DOUBLE
2763 if (dp->conversion == 'f' || dp->conversion == 'F')
2769 scale10_round_decimal_long_double (arg, precision);
2772 END_LONG_DOUBLE_ROUNDING ();
2775 ndigits = strlen (digits);
2777 if (ndigits > precision)
2781 *p++ = digits[ndigits];
2783 while (ndigits > precision);
2786 /* Here ndigits <= precision. */
2787 if ((flags & FLAG_ALT) || precision > 0)
2789 *p++ = decimal_point_char ();
2790 for (; precision > ndigits; precision--)
2795 *p++ = digits[ndigits];
2801 else if (dp->conversion == 'e' || dp->conversion == 'E')
2809 if ((flags & FLAG_ALT) || precision > 0)
2811 *p++ = decimal_point_char ();
2812 for (; precision > 0; precision--)
2823 exponent = floorlog10l (arg);
2828 scale10_round_decimal_long_double (arg,
2829 (int)precision - exponent);
2832 END_LONG_DOUBLE_ROUNDING ();
2835 ndigits = strlen (digits);
2837 if (ndigits == precision + 1)
2839 if (ndigits < precision
2840 || ndigits > precision + 2)
2841 /* The exponent was not guessed
2842 precisely enough. */
2845 /* None of two values of exponent is
2846 the right one. Prevent an endless
2850 if (ndigits == precision)
2857 /* Here ndigits = precision+1. */
2858 *p++ = digits[--ndigits];
2859 if ((flags & FLAG_ALT) || precision > 0)
2861 *p++ = decimal_point_char ();
2865 *p++ = digits[ndigits];
2872 *p++ = dp->conversion; /* 'e' or 'E' */
2873 # if WIDE_CHAR_VERSION
2875 static const wchar_t decimal_format[] =
2876 { '%', '+', '.', '2', 'd', '\0' };
2877 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2882 if (sizeof (DCHAR_T) == 1)
2884 sprintf ((char *) p, "%+.2d", exponent);
2892 sprintf (expbuf, "%+.2d", exponent);
2893 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2898 else if (dp->conversion == 'g' || dp->conversion == 'G')
2902 /* precision >= 1. */
2905 /* The exponent is 0, >= -4, < precision.
2906 Use fixed-point notation. */
2908 size_t ndigits = precision;
2909 /* Number of trailing zeroes that have to be
2912 (flags & FLAG_ALT ? 0 : precision - 1);
2916 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2918 *p++ = decimal_point_char ();
2919 while (ndigits > nzeroes)
2935 exponent = floorlog10l (arg);
2940 scale10_round_decimal_long_double (arg,
2941 (int)(precision - 1) - exponent);
2944 END_LONG_DOUBLE_ROUNDING ();
2947 ndigits = strlen (digits);
2949 if (ndigits == precision)
2951 if (ndigits < precision - 1
2952 || ndigits > precision + 1)
2953 /* The exponent was not guessed
2954 precisely enough. */
2957 /* None of two values of exponent is
2958 the right one. Prevent an endless
2962 if (ndigits < precision)
2968 /* Here ndigits = precision. */
2970 /* Determine the number of trailing zeroes
2971 that have to be dropped. */
2973 if ((flags & FLAG_ALT) == 0)
2974 while (nzeroes < ndigits
2975 && digits[nzeroes] == '0')
2978 /* The exponent is now determined. */
2980 && exponent < (long)precision)
2982 /* Fixed-point notation:
2983 max(exponent,0)+1 digits, then the
2984 decimal point, then the remaining
2985 digits without trailing zeroes. */
2988 size_t count = exponent + 1;
2989 /* Note: count <= precision = ndigits. */
2990 for (; count > 0; count--)
2991 *p++ = digits[--ndigits];
2992 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2994 *p++ = decimal_point_char ();
2995 while (ndigits > nzeroes)
2998 *p++ = digits[ndigits];
3004 size_t count = -exponent - 1;
3006 *p++ = decimal_point_char ();
3007 for (; count > 0; count--)
3009 while (ndigits > nzeroes)
3012 *p++ = digits[ndigits];
3018 /* Exponential notation. */
3019 *p++ = digits[--ndigits];
3020 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3022 *p++ = decimal_point_char ();
3023 while (ndigits > nzeroes)
3026 *p++ = digits[ndigits];
3029 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3030 # if WIDE_CHAR_VERSION
3032 static const wchar_t decimal_format[] =
3033 { '%', '+', '.', '2', 'd', '\0' };
3034 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3039 if (sizeof (DCHAR_T) == 1)
3041 sprintf ((char *) p, "%+.2d", exponent);
3049 sprintf (expbuf, "%+.2d", exponent);
3050 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3062 /* arg is finite. */
3067 END_LONG_DOUBLE_ROUNDING ();
3070 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3074 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3076 double arg = a.arg[dp->arg_index].a.a_double;
3080 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3082 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3086 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3093 if (signbit (arg)) /* arg < 0.0 or negative zero */
3101 else if (flags & FLAG_SHOWSIGN)
3103 else if (flags & FLAG_SPACE)
3106 if (arg > 0.0 && arg + arg == arg)
3108 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3110 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3114 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3119 # if NEED_PRINTF_DOUBLE
3122 if (dp->conversion == 'f' || dp->conversion == 'F')
3128 scale10_round_decimal_double (arg, precision);
3131 ndigits = strlen (digits);
3133 if (ndigits > precision)
3137 *p++ = digits[ndigits];
3139 while (ndigits > precision);
3142 /* Here ndigits <= precision. */
3143 if ((flags & FLAG_ALT) || precision > 0)
3145 *p++ = decimal_point_char ();
3146 for (; precision > ndigits; precision--)
3151 *p++ = digits[ndigits];
3157 else if (dp->conversion == 'e' || dp->conversion == 'E')
3165 if ((flags & FLAG_ALT) || precision > 0)
3167 *p++ = decimal_point_char ();
3168 for (; precision > 0; precision--)
3179 exponent = floorlog10 (arg);
3184 scale10_round_decimal_double (arg,
3185 (int)precision - exponent);
3188 ndigits = strlen (digits);
3190 if (ndigits == precision + 1)
3192 if (ndigits < precision
3193 || ndigits > precision + 2)
3194 /* The exponent was not guessed
3195 precisely enough. */
3198 /* None of two values of exponent is
3199 the right one. Prevent an endless
3203 if (ndigits == precision)
3210 /* Here ndigits = precision+1. */
3211 *p++ = digits[--ndigits];
3212 if ((flags & FLAG_ALT) || precision > 0)
3214 *p++ = decimal_point_char ();
3218 *p++ = digits[ndigits];
3225 *p++ = dp->conversion; /* 'e' or 'E' */
3226 # if WIDE_CHAR_VERSION
3228 static const wchar_t decimal_format[] =
3229 /* Produce the same number of exponent digits
3230 as the native printf implementation. */
3231 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3232 { '%', '+', '.', '3', 'd', '\0' };
3234 { '%', '+', '.', '2', 'd', '\0' };
3236 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3242 static const char decimal_format[] =
3243 /* Produce the same number of exponent digits
3244 as the native printf implementation. */
3245 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3250 if (sizeof (DCHAR_T) == 1)
3252 sprintf ((char *) p, decimal_format, exponent);
3260 sprintf (expbuf, decimal_format, exponent);
3261 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3267 else if (dp->conversion == 'g' || dp->conversion == 'G')
3271 /* precision >= 1. */
3274 /* The exponent is 0, >= -4, < precision.
3275 Use fixed-point notation. */
3277 size_t ndigits = precision;
3278 /* Number of trailing zeroes that have to be
3281 (flags & FLAG_ALT ? 0 : precision - 1);
3285 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3287 *p++ = decimal_point_char ();
3288 while (ndigits > nzeroes)
3304 exponent = floorlog10 (arg);
3309 scale10_round_decimal_double (arg,
3310 (int)(precision - 1) - exponent);
3313 ndigits = strlen (digits);
3315 if (ndigits == precision)
3317 if (ndigits < precision - 1
3318 || ndigits > precision + 1)
3319 /* The exponent was not guessed
3320 precisely enough. */
3323 /* None of two values of exponent is
3324 the right one. Prevent an endless
3328 if (ndigits < precision)
3334 /* Here ndigits = precision. */
3336 /* Determine the number of trailing zeroes
3337 that have to be dropped. */
3339 if ((flags & FLAG_ALT) == 0)
3340 while (nzeroes < ndigits
3341 && digits[nzeroes] == '0')
3344 /* The exponent is now determined. */
3346 && exponent < (long)precision)
3348 /* Fixed-point notation:
3349 max(exponent,0)+1 digits, then the
3350 decimal point, then the remaining
3351 digits without trailing zeroes. */
3354 size_t count = exponent + 1;
3355 /* Note: count <= precision = ndigits. */
3356 for (; count > 0; count--)
3357 *p++ = digits[--ndigits];
3358 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3360 *p++ = decimal_point_char ();
3361 while (ndigits > nzeroes)
3364 *p++ = digits[ndigits];
3370 size_t count = -exponent - 1;
3372 *p++ = decimal_point_char ();
3373 for (; count > 0; count--)
3375 while (ndigits > nzeroes)
3378 *p++ = digits[ndigits];
3384 /* Exponential notation. */
3385 *p++ = digits[--ndigits];
3386 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3388 *p++ = decimal_point_char ();
3389 while (ndigits > nzeroes)
3392 *p++ = digits[ndigits];
3395 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3396 # if WIDE_CHAR_VERSION
3398 static const wchar_t decimal_format[] =
3399 /* Produce the same number of exponent digits
3400 as the native printf implementation. */
3401 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3402 { '%', '+', '.', '3', 'd', '\0' };
3404 { '%', '+', '.', '2', 'd', '\0' };
3406 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3412 static const char decimal_format[] =
3413 /* Produce the same number of exponent digits
3414 as the native printf implementation. */
3415 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3420 if (sizeof (DCHAR_T) == 1)
3422 sprintf ((char *) p, decimal_format, exponent);
3430 sprintf (expbuf, decimal_format, exponent);
3431 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3444 /* arg is finite. */
3450 if (dp->conversion == 'f' || dp->conversion == 'F')
3453 if ((flags & FLAG_ALT) || precision > 0)
3455 *p++ = decimal_point_char ();
3456 for (; precision > 0; precision--)
3460 else if (dp->conversion == 'e' || dp->conversion == 'E')
3463 if ((flags & FLAG_ALT) || precision > 0)
3465 *p++ = decimal_point_char ();
3466 for (; precision > 0; precision--)
3469 *p++ = dp->conversion; /* 'e' or 'E' */
3471 /* Produce the same number of exponent digits as
3472 the native printf implementation. */
3473 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3479 else if (dp->conversion == 'g' || dp->conversion == 'G')
3482 if (flags & FLAG_ALT)
3485 (precision > 0 ? precision - 1 : 0);
3486 *p++ = decimal_point_char ();
3487 for (; ndigits > 0; --ndigits)
3499 /* The generated string now extends from tmp to p, with the
3500 zero padding insertion point being at pad_ptr. */
3501 if (has_width && p - tmp < width)
3503 size_t pad = width - (p - tmp);
3504 DCHAR_T *end = p + pad;
3506 if (flags & FLAG_LEFT)
3508 /* Pad with spaces on the right. */
3509 for (; pad > 0; pad--)
3512 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3514 /* Pad with zeroes. */
3519 for (; pad > 0; pad--)
3524 /* Pad with spaces on the left. */
3529 for (; pad > 0; pad--)
3537 size_t count = p - tmp;
3539 if (count >= tmp_length)
3540 /* tmp_length was incorrectly calculated - fix the
3544 /* Make room for the result. */
3545 if (count >= allocated - length)
3547 size_t n = xsum (length, count);
3549 ENSURE_ALLOCATION (n);
3552 /* Append the result. */
3553 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3562 arg_type type = a.arg[dp->arg_index].type;
3563 int flags = dp->flags;
3564 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3568 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3572 #if NEED_PRINTF_UNBOUNDED_PRECISION
3575 # define prec_ourselves 0
3577 #if NEED_PRINTF_FLAG_LEFTADJUST
3578 # define pad_ourselves 1
3579 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3582 # define pad_ourselves 0
3585 unsigned int prefix_count;
3589 TCHAR_T tmpbuf[700];
3593 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3596 if (dp->width_start != dp->width_end)
3598 if (dp->width_arg_index != ARG_NONE)
3602 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3604 arg = a.arg[dp->width_arg_index].a.a_int;
3607 /* "A negative field width is taken as a '-' flag
3608 followed by a positive field width." */
3610 width = (unsigned int) (-arg);
3617 const FCHAR_T *digitp = dp->width_start;
3620 width = xsum (xtimes (width, 10), *digitp++ - '0');
3621 while (digitp != dp->width_end);
3627 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3630 if (dp->precision_start != dp->precision_end)
3632 if (dp->precision_arg_index != ARG_NONE)
3636 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3638 arg = a.arg[dp->precision_arg_index].a.a_int;
3639 /* "A negative precision is taken as if the precision
3649 const FCHAR_T *digitp = dp->precision_start + 1;
3652 while (digitp != dp->precision_end)
3653 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3660 /* Allocate a temporary buffer of sufficient size for calling
3663 switch (dp->conversion)
3666 case 'd': case 'i': case 'u':
3667 # if HAVE_LONG_LONG_INT
3668 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3670 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3671 * 0.30103 /* binary -> decimal */
3673 + 1; /* turn floor into ceil */
3676 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3678 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3679 * 0.30103 /* binary -> decimal */
3681 + 1; /* turn floor into ceil */
3684 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3685 * 0.30103 /* binary -> decimal */
3687 + 1; /* turn floor into ceil */
3688 if (tmp_length < precision)
3689 tmp_length = precision;
3690 /* Multiply by 2, as an estimate for FLAG_GROUP. */
3691 tmp_length = xsum (tmp_length, tmp_length);
3692 /* Add 1, to account for a leading sign. */
3693 tmp_length = xsum (tmp_length, 1);
3697 # if HAVE_LONG_LONG_INT
3698 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3700 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3701 * 0.333334 /* binary -> octal */
3703 + 1; /* turn floor into ceil */
3706 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3708 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3709 * 0.333334 /* binary -> octal */
3711 + 1; /* turn floor into ceil */
3714 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3715 * 0.333334 /* binary -> octal */
3717 + 1; /* turn floor into ceil */
3718 if (tmp_length < precision)
3719 tmp_length = precision;
3720 /* Add 1, to account for a leading sign. */
3721 tmp_length = xsum (tmp_length, 1);
3725 # if HAVE_LONG_LONG_INT
3726 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3728 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3729 * 0.25 /* binary -> hexadecimal */
3731 + 1; /* turn floor into ceil */
3734 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3736 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3737 * 0.25 /* binary -> hexadecimal */
3739 + 1; /* turn floor into ceil */
3742 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3743 * 0.25 /* binary -> hexadecimal */
3745 + 1; /* turn floor into ceil */
3746 if (tmp_length < precision)
3747 tmp_length = precision;
3748 /* Add 2, to account for a leading sign or alternate form. */
3749 tmp_length = xsum (tmp_length, 2);
3753 if (type == TYPE_LONGDOUBLE)
3755 (unsigned int) (LDBL_MAX_EXP
3756 * 0.30103 /* binary -> decimal */
3757 * 2 /* estimate for FLAG_GROUP */
3759 + 1 /* turn floor into ceil */
3760 + 10; /* sign, decimal point etc. */
3763 (unsigned int) (DBL_MAX_EXP
3764 * 0.30103 /* binary -> decimal */
3765 * 2 /* estimate for FLAG_GROUP */
3767 + 1 /* turn floor into ceil */
3768 + 10; /* sign, decimal point etc. */
3769 tmp_length = xsum (tmp_length, precision);
3772 case 'e': case 'E': case 'g': case 'G':
3774 12; /* sign, decimal point, exponent etc. */
3775 tmp_length = xsum (tmp_length, precision);
3779 if (type == TYPE_LONGDOUBLE)
3781 (unsigned int) (LDBL_DIG
3782 * 0.831 /* decimal -> hexadecimal */
3784 + 1; /* turn floor into ceil */
3787 (unsigned int) (DBL_DIG
3788 * 0.831 /* decimal -> hexadecimal */
3790 + 1; /* turn floor into ceil */
3791 if (tmp_length < precision)
3792 tmp_length = precision;
3793 /* Account for sign, decimal point etc. */
3794 tmp_length = xsum (tmp_length, 12);
3798 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
3799 if (type == TYPE_WIDE_CHAR)
3800 tmp_length = MB_CUR_MAX;
3808 if (type == TYPE_WIDE_STRING)
3811 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
3813 # if !WIDE_CHAR_VERSION
3814 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
3819 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
3824 (unsigned int) (sizeof (void *) * CHAR_BIT
3825 * 0.25 /* binary -> hexadecimal */
3827 + 1 /* turn floor into ceil */
3828 + 2; /* account for leading 0x */
3835 # if ENABLE_UNISTDIO
3836 /* Padding considers the number of characters, therefore the
3837 number of elements after padding may be
3838 > max (tmp_length, width)
3840 <= tmp_length + width. */
3841 tmp_length = xsum (tmp_length, width);
3843 /* Padding considers the number of elements, says POSIX. */
3844 if (tmp_length < width)
3848 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3851 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
3855 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
3857 if (size_overflow_p (tmp_memsize))
3858 /* Overflow, would lead to out of memory. */
3860 tmp = (TCHAR_T *) malloc (tmp_memsize);
3862 /* Out of memory. */
3867 /* Decide whether to handle the precision ourselves. */
3868 #if NEED_PRINTF_UNBOUNDED_PRECISION
3869 switch (dp->conversion)
3871 case 'd': case 'i': case 'u':
3873 case 'x': case 'X': case 'p':
3874 prec_ourselves = has_precision && (precision > 0);
3882 /* Decide whether to perform the padding ourselves. */
3883 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
3884 switch (dp->conversion)
3886 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
3887 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
3888 to perform the padding after this conversion. Functions
3889 with unistdio extensions perform the padding based on
3890 character count rather than element count. */
3893 # if NEED_PRINTF_FLAG_ZERO
3894 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
3900 pad_ourselves = prec_ourselves;
3905 /* Construct the format string for calling snprintf or
3909 #if NEED_PRINTF_FLAG_GROUPING
3910 /* The underlying implementation doesn't support the ' flag.
3911 Produce no grouping characters in this case; this is
3912 acceptable because the grouping is locale dependent. */
3914 if (flags & FLAG_GROUP)
3917 if (flags & FLAG_LEFT)
3919 if (flags & FLAG_SHOWSIGN)
3921 if (flags & FLAG_SPACE)
3923 if (flags & FLAG_ALT)
3927 if (flags & FLAG_ZERO)
3929 if (dp->width_start != dp->width_end)
3931 size_t n = dp->width_end - dp->width_start;
3932 /* The width specification is known to consist only
3933 of standard ASCII characters. */
3934 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
3936 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
3941 const FCHAR_T *mp = dp->width_start;
3943 *fbp++ = (unsigned char) *mp++;
3948 if (!prec_ourselves)
3950 if (dp->precision_start != dp->precision_end)
3952 size_t n = dp->precision_end - dp->precision_start;
3953 /* The precision specification is known to consist only
3954 of standard ASCII characters. */
3955 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
3957 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
3962 const FCHAR_T *mp = dp->precision_start;
3964 *fbp++ = (unsigned char) *mp++;
3972 #if HAVE_LONG_LONG_INT
3973 case TYPE_LONGLONGINT:
3974 case TYPE_ULONGLONGINT:
3975 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3988 case TYPE_WIDE_CHAR:
3991 case TYPE_WIDE_STRING:
3995 case TYPE_LONGDOUBLE:
4001 #if NEED_PRINTF_DIRECTIVE_F
4002 if (dp->conversion == 'F')
4006 *fbp = dp->conversion;
4008 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4013 /* On glibc2 systems from glibc >= 2.3 - probably also older
4014 ones - we know that snprintf's returns value conforms to
4015 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4016 Therefore we can avoid using %n in this situation.
4017 On glibc2 systems from 2004-10-18 or newer, the use of %n
4018 in format strings in writable memory may crash the program
4019 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4020 in this situation. */
4021 /* On native Win32 systems (such as mingw), we can avoid using
4023 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4024 snprintf does not write more than the specified number
4025 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4026 '4', '5', '6' into buf, not '4', '5', '\0'.)
4027 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4028 allows us to recognize the case of an insufficient
4029 buffer size: it returns -1 in this case.
4030 On native Win32 systems (such as mingw) where the OS is
4031 Windows Vista, the use of %n in format strings by default
4032 crashes the program. See
4033 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4034 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4035 So we should avoid %n in this situation. */
4042 /* Construct the arguments for calling snprintf or sprintf. */
4044 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4046 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4048 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4050 if (dp->precision_arg_index != ARG_NONE)
4052 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4054 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4058 /* The SNPRINTF result is appended after result[0..length].
4059 The latter is an array of DCHAR_T; SNPRINTF appends an
4060 array of TCHAR_T to it. This is possible because
4061 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4062 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4063 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4064 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4065 where an snprintf() with maxlen==1 acts like sprintf(). */
4066 ENSURE_ALLOCATION (xsum (length,
4067 (2 + TCHARS_PER_DCHAR - 1)
4068 / TCHARS_PER_DCHAR));
4069 /* Prepare checking whether snprintf returns the count
4071 *(TCHAR_T *) (result + length) = '\0';
4080 size_t maxlen = allocated - length;
4081 /* SNPRINTF can fail if its second argument is
4083 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4084 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4085 maxlen = maxlen * TCHARS_PER_DCHAR;
4086 # define SNPRINTF_BUF(arg) \
4087 switch (prefix_count) \
4090 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4095 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4097 prefixes[0], arg, &count); \
4100 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4102 prefixes[0], prefixes[1], arg, \
4109 # define SNPRINTF_BUF(arg) \
4110 switch (prefix_count) \
4113 count = sprintf (tmp, buf, arg); \
4116 count = sprintf (tmp, buf, prefixes[0], arg); \
4119 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4131 int arg = a.arg[dp->arg_index].a.a_schar;
4137 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4143 int arg = a.arg[dp->arg_index].a.a_short;
4149 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4155 int arg = a.arg[dp->arg_index].a.a_int;
4161 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4167 long int arg = a.arg[dp->arg_index].a.a_longint;
4173 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4177 #if HAVE_LONG_LONG_INT
4178 case TYPE_LONGLONGINT:
4180 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4184 case TYPE_ULONGLONGINT:
4186 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4193 double arg = a.arg[dp->arg_index].a.a_double;
4197 case TYPE_LONGDOUBLE:
4199 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4205 int arg = a.arg[dp->arg_index].a.a_char;
4210 case TYPE_WIDE_CHAR:
4212 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
4219 const char *arg = a.arg[dp->arg_index].a.a_string;
4224 case TYPE_WIDE_STRING:
4226 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
4233 void *arg = a.arg[dp->arg_index].a.a_pointer;
4242 /* Portability: Not all implementations of snprintf()
4243 are ISO C 99 compliant. Determine the number of
4244 bytes that snprintf() has produced or would have
4248 /* Verify that snprintf() has NUL-terminated its
4251 && ((TCHAR_T *) (result + length)) [count] != '\0')
4253 /* Portability hack. */
4254 if (retcount > count)
4259 /* snprintf() doesn't understand the '%n'
4263 /* Don't use the '%n' directive; instead, look
4264 at the snprintf() return value. */
4270 /* Look at the snprintf() return value. */
4273 /* HP-UX 10.20 snprintf() is doubly deficient:
4274 It doesn't understand the '%n' directive,
4275 *and* it returns -1 (rather than the length
4276 that would have been required) when the
4277 buffer is too small. */
4278 size_t bigger_need =
4279 xsum (xtimes (allocated, 2), 12);
4280 ENSURE_ALLOCATION (bigger_need);
4289 /* Attempt to handle failure. */
4292 if (!(result == resultbuf || result == NULL))
4294 if (buf_malloced != NULL)
4295 free (buf_malloced);
4302 /* Handle overflow of the allocated buffer.
4303 If such an overflow occurs, a C99 compliant snprintf()
4304 returns a count >= maxlen. However, a non-compliant
4305 snprintf() function returns only count = maxlen - 1. To
4306 cover both cases, test whether count >= maxlen - 1. */
4307 if ((unsigned int) count + 1 >= maxlen)
4309 /* If maxlen already has attained its allowed maximum,
4310 allocating more memory will not increase maxlen.
4311 Instead of looping, bail out. */
4312 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
4316 /* Need at least (count + 1) * sizeof (TCHAR_T)
4317 bytes. (The +1 is for the trailing NUL.)
4318 But ask for (count + 2) * sizeof (TCHAR_T)
4319 bytes, so that in the next round, we likely get
4320 maxlen > (unsigned int) count + 1
4321 and so we don't get here again.
4322 And allocate proportionally, to avoid looping
4323 eternally if snprintf() reports a too small
4327 ((unsigned int) count + 2
4328 + TCHARS_PER_DCHAR - 1)
4329 / TCHARS_PER_DCHAR),
4330 xtimes (allocated, 2));
4332 ENSURE_ALLOCATION (n);
4338 #if NEED_PRINTF_UNBOUNDED_PRECISION
4341 /* Handle the precision. */
4344 (TCHAR_T *) (result + length);
4348 size_t prefix_count;
4352 /* Put the additional zeroes after the sign. */
4354 && (*prec_ptr == '-' || *prec_ptr == '+'
4355 || *prec_ptr == ' '))
4357 /* Put the additional zeroes after the 0x prefix if
4358 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
4360 && prec_ptr[0] == '0'
4361 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
4364 move = count - prefix_count;
4365 if (precision > move)
4367 /* Insert zeroes. */
4368 size_t insert = precision - move;
4374 (count + insert + TCHARS_PER_DCHAR - 1)
4375 / TCHARS_PER_DCHAR);
4376 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4377 ENSURE_ALLOCATION (n);
4378 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4379 prec_ptr = (TCHAR_T *) (result + length);
4382 prec_end = prec_ptr + count;
4383 prec_ptr += prefix_count;
4385 while (prec_end > prec_ptr)
4388 prec_end[insert] = prec_end[0];
4394 while (prec_end > prec_ptr);
4403 if (count >= tmp_length)
4404 /* tmp_length was incorrectly calculated - fix the
4409 /* Convert from TCHAR_T[] to DCHAR_T[]. */
4410 if (dp->conversion == 'c' || dp->conversion == 's')
4412 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
4414 The result string is not certainly ASCII. */
4415 const TCHAR_T *tmpsrc;
4418 /* This code assumes that TCHAR_T is 'char'. */
4419 typedef int TCHAR_T_verify
4420 [2 * (sizeof (TCHAR_T) == 1) - 1];
4422 tmpsrc = (TCHAR_T *) (result + length);
4428 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
4429 iconveh_question_mark,
4432 &tmpdst, &tmpdst_len)
4435 int saved_errno = errno;
4436 if (!(result == resultbuf || result == NULL))
4438 if (buf_malloced != NULL)
4439 free (buf_malloced);
4441 errno = saved_errno;
4444 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
4445 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
4451 /* The result string is ASCII.
4452 Simple 1:1 conversion. */
4454 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
4455 no-op conversion, in-place on the array starting
4456 at (result + length). */
4457 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
4460 const TCHAR_T *tmpsrc;
4465 if (result == resultbuf)
4467 tmpsrc = (TCHAR_T *) (result + length);
4468 /* ENSURE_ALLOCATION will not move tmpsrc
4469 (because it's part of resultbuf). */
4470 ENSURE_ALLOCATION (xsum (length, count));
4474 /* ENSURE_ALLOCATION will move the array
4475 (because it uses realloc(). */
4476 ENSURE_ALLOCATION (xsum (length, count));
4477 tmpsrc = (TCHAR_T *) (result + length);
4481 ENSURE_ALLOCATION (xsum (length, count));
4483 tmpdst = result + length;
4484 /* Copy backwards, because of overlapping. */
4487 for (n = count; n > 0; n--)
4488 *--tmpdst = (unsigned char) *--tmpsrc;
4493 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4494 /* Make room for the result. */
4495 if (count > allocated - length)
4497 /* Need at least count elements. But allocate
4500 xmax (xsum (length, count), xtimes (allocated, 2));
4502 ENSURE_ALLOCATION (n);
4506 /* Here count <= allocated - length. */
4508 /* Perform padding. */
4509 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4510 if (pad_ourselves && has_width)
4513 # if ENABLE_UNISTDIO
4514 /* Outside POSIX, it's preferrable to compare the width
4515 against the number of _characters_ of the converted
4517 w = DCHAR_MBSNLEN (result + length, count);
4519 /* The width is compared against the number of _bytes_
4520 of the converted value, says POSIX. */
4525 size_t pad = width - w;
4527 /* Make room for the result. */
4528 if (xsum (count, pad) > allocated - length)
4530 /* Need at least count + pad elements. But
4531 allocate proportionally. */
4533 xmax (xsum3 (length, count, pad),
4534 xtimes (allocated, 2));
4537 ENSURE_ALLOCATION (n);
4540 /* Here count + pad <= allocated - length. */
4543 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
4544 DCHAR_T * const rp = result + length;
4546 DCHAR_T * const rp = tmp;
4548 DCHAR_T *p = rp + count;
4549 DCHAR_T *end = p + pad;
4551 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4552 if (dp->conversion == 'c'
4553 || dp->conversion == 's')
4554 /* No zero-padding for string directives. */
4559 pad_ptr = (*rp == '-' ? rp + 1 : rp);
4560 /* No zero-padding of "inf" and "nan". */
4561 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
4562 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
4565 /* The generated string now extends from rp to p,
4566 with the zero padding insertion point being at
4569 count = count + pad; /* = end - rp */
4571 if (flags & FLAG_LEFT)
4573 /* Pad with spaces on the right. */
4574 for (; pad > 0; pad--)
4577 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4579 /* Pad with zeroes. */
4584 for (; pad > 0; pad--)
4589 /* Pad with spaces on the left. */
4594 for (; pad > 0; pad--)
4602 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4603 if (count >= tmp_length)
4604 /* tmp_length was incorrectly calculated - fix the
4609 /* Here still count <= allocated - length. */
4611 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
4612 /* The snprintf() result did fit. */
4614 /* Append the sprintf() result. */
4615 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4622 #if NEED_PRINTF_DIRECTIVE_F
4623 if (dp->conversion == 'F')
4625 /* Convert the %f result to upper case for %F. */
4626 DCHAR_T *rp = result + length;
4628 for (rc = count; rc > 0; rc--, rp++)
4629 if (*rp >= 'a' && *rp <= 'z')
4630 *rp = *rp - 'a' + 'A';
4641 /* Add the final NUL. */
4642 ENSURE_ALLOCATION (xsum (length, 1));
4643 result[length] = '\0';
4645 if (result != resultbuf && length + 1 < allocated)
4647 /* Shrink the allocated memory if possible. */
4650 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
4655 if (buf_malloced != NULL)
4656 free (buf_malloced);
4659 /* Note that we can produce a big string of a length > INT_MAX. POSIX
4660 says that snprintf() fails with errno = EOVERFLOW in this case, but
4661 that's only because snprintf() returns an 'int'. This function does
4662 not have this limitation. */
4667 if (!(result == resultbuf || result == NULL))
4669 if (buf_malloced != NULL)
4670 free (buf_malloced);
4677 if (!(result == resultbuf || result == NULL))
4679 if (buf_malloced != NULL)
4680 free (buf_malloced);
4688 #undef TCHARS_PER_DCHAR
4695 #undef DCHAR_IS_TCHAR