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);
1407 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1408 a single '1' digit. */
1410 is_borderline (const char *digits, size_t precision)
1412 for (; precision > 0; precision--, digits++)
1418 return *digits == '\0';
1424 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1425 const FCHAR_T *format, va_list args)
1430 if (PRINTF_PARSE (format, &d, &a) < 0)
1431 /* errno is already set. */
1439 if (PRINTF_FETCHARGS (args, &a) < 0)
1447 size_t buf_neededlength;
1449 TCHAR_T *buf_malloced;
1453 /* Output string accumulator. */
1458 /* Allocate a small buffer that will hold a directive passed to
1459 sprintf or snprintf. */
1461 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1463 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1465 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1466 buf_malloced = NULL;
1471 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1472 if (size_overflow_p (buf_memsize))
1473 goto out_of_memory_1;
1474 buf = (TCHAR_T *) malloc (buf_memsize);
1476 goto out_of_memory_1;
1480 if (resultbuf != NULL)
1483 allocated = *lengthp;
1492 result is either == resultbuf or == NULL or malloc-allocated.
1493 If length > 0, then result != NULL. */
1495 /* Ensures that allocated >= needed. Aborts through a jump to
1496 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1497 #define ENSURE_ALLOCATION(needed) \
1498 if ((needed) > allocated) \
1500 size_t memory_size; \
1503 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1504 if ((needed) > allocated) \
1505 allocated = (needed); \
1506 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1507 if (size_overflow_p (memory_size)) \
1508 goto out_of_memory; \
1509 if (result == resultbuf || result == NULL) \
1510 memory = (DCHAR_T *) malloc (memory_size); \
1512 memory = (DCHAR_T *) realloc (result, memory_size); \
1513 if (memory == NULL) \
1514 goto out_of_memory; \
1515 if (result == resultbuf && length > 0) \
1516 DCHAR_CPY (memory, result, length); \
1520 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1522 if (cp != dp->dir_start)
1524 size_t n = dp->dir_start - cp;
1525 size_t augmented_length = xsum (length, n);
1527 ENSURE_ALLOCATION (augmented_length);
1528 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1529 need that the format string contains only ASCII characters
1530 if FCHAR_T and DCHAR_T are not the same type. */
1531 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1533 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1534 length = augmented_length;
1539 result[length++] = (unsigned char) *cp++;
1546 /* Execute a single directive. */
1547 if (dp->conversion == '%')
1549 size_t augmented_length;
1551 if (!(dp->arg_index == ARG_NONE))
1553 augmented_length = xsum (length, 1);
1554 ENSURE_ALLOCATION (augmented_length);
1555 result[length] = '%';
1556 length = augmented_length;
1560 if (!(dp->arg_index != ARG_NONE))
1563 if (dp->conversion == 'n')
1565 switch (a.arg[dp->arg_index].type)
1567 case TYPE_COUNT_SCHAR_POINTER:
1568 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1570 case TYPE_COUNT_SHORT_POINTER:
1571 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1573 case TYPE_COUNT_INT_POINTER:
1574 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1576 case TYPE_COUNT_LONGINT_POINTER:
1577 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1579 #if HAVE_LONG_LONG_INT
1580 case TYPE_COUNT_LONGLONGINT_POINTER:
1581 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1589 /* The unistdio extensions. */
1590 else if (dp->conversion == 'U')
1592 arg_type type = a.arg[dp->arg_index].type;
1593 int flags = dp->flags;
1601 if (dp->width_start != dp->width_end)
1603 if (dp->width_arg_index != ARG_NONE)
1607 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1609 arg = a.arg[dp->width_arg_index].a.a_int;
1612 /* "A negative field width is taken as a '-' flag
1613 followed by a positive field width." */
1615 width = (unsigned int) (-arg);
1622 const FCHAR_T *digitp = dp->width_start;
1625 width = xsum (xtimes (width, 10), *digitp++ - '0');
1626 while (digitp != dp->width_end);
1633 if (dp->precision_start != dp->precision_end)
1635 if (dp->precision_arg_index != ARG_NONE)
1639 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1641 arg = a.arg[dp->precision_arg_index].a.a_int;
1642 /* "A negative precision is taken as if the precision
1652 const FCHAR_T *digitp = dp->precision_start + 1;
1655 while (digitp != dp->precision_end)
1656 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1663 case TYPE_U8_STRING:
1665 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1666 const uint8_t *arg_end;
1671 /* Use only PRECISION characters, from the left. */
1674 for (; precision > 0; precision--)
1676 int count = u8_strmblen (arg_end);
1681 if (!(result == resultbuf || result == NULL))
1683 if (buf_malloced != NULL)
1684 free (buf_malloced);
1695 /* Use the entire string, and count the number of
1701 int count = u8_strmblen (arg_end);
1706 if (!(result == resultbuf || result == NULL))
1708 if (buf_malloced != NULL)
1709 free (buf_malloced);
1720 /* Use the entire string. */
1721 arg_end = arg + u8_strlen (arg);
1722 /* The number of characters doesn't matter. */
1726 if (has_width && width > characters
1727 && !(dp->flags & FLAG_LEFT))
1729 size_t n = width - characters;
1730 ENSURE_ALLOCATION (xsum (length, n));
1731 DCHAR_SET (result + length, ' ', n);
1735 # if DCHAR_IS_UINT8_T
1737 size_t n = arg_end - arg;
1738 ENSURE_ALLOCATION (xsum (length, n));
1739 DCHAR_CPY (result + length, arg, n);
1744 DCHAR_T *converted = result + length;
1745 size_t converted_len = allocated - length;
1747 /* Convert from UTF-8 to locale encoding. */
1748 if (u8_conv_to_encoding (locale_charset (),
1749 iconveh_question_mark,
1750 arg, arg_end - arg, NULL,
1751 &converted, &converted_len)
1754 /* Convert from UTF-8 to UTF-16/UTF-32. */
1756 U8_TO_DCHAR (arg, arg_end - arg,
1757 converted, &converted_len);
1758 if (converted == NULL)
1761 int saved_errno = errno;
1762 if (!(result == resultbuf || result == NULL))
1764 if (buf_malloced != NULL)
1765 free (buf_malloced);
1767 errno = saved_errno;
1770 if (converted != result + length)
1772 ENSURE_ALLOCATION (xsum (length, converted_len));
1773 DCHAR_CPY (result + length, converted, converted_len);
1776 length += converted_len;
1780 if (has_width && width > characters
1781 && (dp->flags & FLAG_LEFT))
1783 size_t n = width - characters;
1784 ENSURE_ALLOCATION (xsum (length, n));
1785 DCHAR_SET (result + length, ' ', n);
1791 case TYPE_U16_STRING:
1793 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1794 const uint16_t *arg_end;
1799 /* Use only PRECISION characters, from the left. */
1802 for (; precision > 0; precision--)
1804 int count = u16_strmblen (arg_end);
1809 if (!(result == resultbuf || result == NULL))
1811 if (buf_malloced != NULL)
1812 free (buf_malloced);
1823 /* Use the entire string, and count the number of
1829 int count = u16_strmblen (arg_end);
1834 if (!(result == resultbuf || result == NULL))
1836 if (buf_malloced != NULL)
1837 free (buf_malloced);
1848 /* Use the entire string. */
1849 arg_end = arg + u16_strlen (arg);
1850 /* The number of characters doesn't matter. */
1854 if (has_width && width > characters
1855 && !(dp->flags & FLAG_LEFT))
1857 size_t n = width - characters;
1858 ENSURE_ALLOCATION (xsum (length, n));
1859 DCHAR_SET (result + length, ' ', n);
1863 # if DCHAR_IS_UINT16_T
1865 size_t n = arg_end - arg;
1866 ENSURE_ALLOCATION (xsum (length, n));
1867 DCHAR_CPY (result + length, arg, n);
1872 DCHAR_T *converted = result + length;
1873 size_t converted_len = allocated - length;
1875 /* Convert from UTF-16 to locale encoding. */
1876 if (u16_conv_to_encoding (locale_charset (),
1877 iconveh_question_mark,
1878 arg, arg_end - arg, NULL,
1879 &converted, &converted_len)
1882 /* Convert from UTF-16 to UTF-8/UTF-32. */
1884 U16_TO_DCHAR (arg, arg_end - arg,
1885 converted, &converted_len);
1886 if (converted == NULL)
1889 int saved_errno = errno;
1890 if (!(result == resultbuf || result == NULL))
1892 if (buf_malloced != NULL)
1893 free (buf_malloced);
1895 errno = saved_errno;
1898 if (converted != result + length)
1900 ENSURE_ALLOCATION (xsum (length, converted_len));
1901 DCHAR_CPY (result + length, converted, converted_len);
1904 length += converted_len;
1908 if (has_width && width > characters
1909 && (dp->flags & FLAG_LEFT))
1911 size_t n = width - characters;
1912 ENSURE_ALLOCATION (xsum (length, n));
1913 DCHAR_SET (result + length, ' ', n);
1919 case TYPE_U32_STRING:
1921 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1922 const uint32_t *arg_end;
1927 /* Use only PRECISION characters, from the left. */
1930 for (; precision > 0; precision--)
1932 int count = u32_strmblen (arg_end);
1937 if (!(result == resultbuf || result == NULL))
1939 if (buf_malloced != NULL)
1940 free (buf_malloced);
1951 /* Use the entire string, and count the number of
1957 int count = u32_strmblen (arg_end);
1962 if (!(result == resultbuf || result == NULL))
1964 if (buf_malloced != NULL)
1965 free (buf_malloced);
1976 /* Use the entire string. */
1977 arg_end = arg + u32_strlen (arg);
1978 /* The number of characters doesn't matter. */
1982 if (has_width && width > characters
1983 && !(dp->flags & FLAG_LEFT))
1985 size_t n = width - characters;
1986 ENSURE_ALLOCATION (xsum (length, n));
1987 DCHAR_SET (result + length, ' ', n);
1991 # if DCHAR_IS_UINT32_T
1993 size_t n = arg_end - arg;
1994 ENSURE_ALLOCATION (xsum (length, n));
1995 DCHAR_CPY (result + length, arg, n);
2000 DCHAR_T *converted = result + length;
2001 size_t converted_len = allocated - length;
2003 /* Convert from UTF-32 to locale encoding. */
2004 if (u32_conv_to_encoding (locale_charset (),
2005 iconveh_question_mark,
2006 arg, arg_end - arg, NULL,
2007 &converted, &converted_len)
2010 /* Convert from UTF-32 to UTF-8/UTF-16. */
2012 U32_TO_DCHAR (arg, arg_end - arg,
2013 converted, &converted_len);
2014 if (converted == NULL)
2017 int saved_errno = errno;
2018 if (!(result == resultbuf || result == NULL))
2020 if (buf_malloced != NULL)
2021 free (buf_malloced);
2023 errno = saved_errno;
2026 if (converted != result + length)
2028 ENSURE_ALLOCATION (xsum (length, converted_len));
2029 DCHAR_CPY (result + length, converted, converted_len);
2032 length += converted_len;
2036 if (has_width && width > characters
2037 && (dp->flags & FLAG_LEFT))
2039 size_t n = width - characters;
2040 ENSURE_ALLOCATION (xsum (length, n));
2041 DCHAR_SET (result + length, ' ', n);
2052 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2053 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2054 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2056 # if NEED_PRINTF_DOUBLE
2057 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2059 # if NEED_PRINTF_LONG_DOUBLE
2060 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2066 arg_type type = a.arg[dp->arg_index].type;
2067 int flags = dp->flags;
2073 DCHAR_T tmpbuf[700];
2080 if (dp->width_start != dp->width_end)
2082 if (dp->width_arg_index != ARG_NONE)
2086 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2088 arg = a.arg[dp->width_arg_index].a.a_int;
2091 /* "A negative field width is taken as a '-' flag
2092 followed by a positive field width." */
2094 width = (unsigned int) (-arg);
2101 const FCHAR_T *digitp = dp->width_start;
2104 width = xsum (xtimes (width, 10), *digitp++ - '0');
2105 while (digitp != dp->width_end);
2112 if (dp->precision_start != dp->precision_end)
2114 if (dp->precision_arg_index != ARG_NONE)
2118 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2120 arg = a.arg[dp->precision_arg_index].a.a_int;
2121 /* "A negative precision is taken as if the precision
2131 const FCHAR_T *digitp = dp->precision_start + 1;
2134 while (digitp != dp->precision_end)
2135 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2140 /* Allocate a temporary buffer of sufficient size. */
2141 if (type == TYPE_LONGDOUBLE)
2143 (unsigned int) ((LDBL_DIG + 1)
2144 * 0.831 /* decimal -> hexadecimal */
2146 + 1; /* turn floor into ceil */
2149 (unsigned int) ((DBL_DIG + 1)
2150 * 0.831 /* decimal -> hexadecimal */
2152 + 1; /* turn floor into ceil */
2153 if (tmp_length < precision)
2154 tmp_length = precision;
2155 /* Account for sign, decimal point etc. */
2156 tmp_length = xsum (tmp_length, 12);
2158 if (tmp_length < width)
2161 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2163 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2167 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2169 if (size_overflow_p (tmp_memsize))
2170 /* Overflow, would lead to out of memory. */
2172 tmp = (DCHAR_T *) malloc (tmp_memsize);
2174 /* Out of memory. */
2180 if (type == TYPE_LONGDOUBLE)
2182 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2183 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2187 if (dp->conversion == 'A')
2189 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2193 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2199 DECL_LONG_DOUBLE_ROUNDING
2201 BEGIN_LONG_DOUBLE_ROUNDING ();
2203 if (signbit (arg)) /* arg < 0.0L or negative zero */
2211 else if (flags & FLAG_SHOWSIGN)
2213 else if (flags & FLAG_SPACE)
2216 if (arg > 0.0L && arg + arg == arg)
2218 if (dp->conversion == 'A')
2220 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2224 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2230 long double mantissa;
2233 mantissa = printf_frexpl (arg, &exponent);
2241 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2243 /* Round the mantissa. */
2244 long double tail = mantissa;
2247 for (q = precision; ; q--)
2249 int digit = (int) tail;
2253 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2262 for (q = precision; q > 0; q--)
2268 *p++ = dp->conversion - 'A' + 'X';
2273 digit = (int) mantissa;
2276 if ((flags & FLAG_ALT)
2277 || mantissa > 0.0L || precision > 0)
2279 *p++ = decimal_point_char ();
2280 /* This loop terminates because we assume
2281 that FLT_RADIX is a power of 2. */
2282 while (mantissa > 0.0L)
2285 digit = (int) mantissa;
2290 : dp->conversion - 10);
2294 while (precision > 0)
2301 *p++ = dp->conversion - 'A' + 'P';
2302 # if WIDE_CHAR_VERSION
2304 static const wchar_t decimal_format[] =
2305 { '%', '+', 'd', '\0' };
2306 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2311 if (sizeof (DCHAR_T) == 1)
2313 sprintf ((char *) p, "%+d", exponent);
2321 sprintf (expbuf, "%+d", exponent);
2322 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2328 END_LONG_DOUBLE_ROUNDING ();
2336 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2337 double arg = a.arg[dp->arg_index].a.a_double;
2341 if (dp->conversion == 'A')
2343 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2347 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2354 if (signbit (arg)) /* arg < 0.0 or negative zero */
2362 else if (flags & FLAG_SHOWSIGN)
2364 else if (flags & FLAG_SPACE)
2367 if (arg > 0.0 && arg + arg == arg)
2369 if (dp->conversion == 'A')
2371 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2375 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2384 mantissa = printf_frexp (arg, &exponent);
2392 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2394 /* Round the mantissa. */
2395 double tail = mantissa;
2398 for (q = precision; ; q--)
2400 int digit = (int) tail;
2404 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2413 for (q = precision; q > 0; q--)
2419 *p++ = dp->conversion - 'A' + 'X';
2424 digit = (int) mantissa;
2427 if ((flags & FLAG_ALT)
2428 || mantissa > 0.0 || precision > 0)
2430 *p++ = decimal_point_char ();
2431 /* This loop terminates because we assume
2432 that FLT_RADIX is a power of 2. */
2433 while (mantissa > 0.0)
2436 digit = (int) mantissa;
2441 : dp->conversion - 10);
2445 while (precision > 0)
2452 *p++ = dp->conversion - 'A' + 'P';
2453 # if WIDE_CHAR_VERSION
2455 static const wchar_t decimal_format[] =
2456 { '%', '+', 'd', '\0' };
2457 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2462 if (sizeof (DCHAR_T) == 1)
2464 sprintf ((char *) p, "%+d", exponent);
2472 sprintf (expbuf, "%+d", exponent);
2473 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2483 /* The generated string now extends from tmp to p, with the
2484 zero padding insertion point being at pad_ptr. */
2485 if (has_width && p - tmp < width)
2487 size_t pad = width - (p - tmp);
2488 DCHAR_T *end = p + pad;
2490 if (flags & FLAG_LEFT)
2492 /* Pad with spaces on the right. */
2493 for (; pad > 0; pad--)
2496 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2498 /* Pad with zeroes. */
2503 for (; pad > 0; pad--)
2508 /* Pad with spaces on the left. */
2513 for (; pad > 0; pad--)
2521 size_t count = p - tmp;
2523 if (count >= tmp_length)
2524 /* tmp_length was incorrectly calculated - fix the
2528 /* Make room for the result. */
2529 if (count >= allocated - length)
2531 size_t n = xsum (length, count);
2533 ENSURE_ALLOCATION (n);
2536 /* Append the result. */
2537 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2544 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2545 else if ((dp->conversion == 'f' || dp->conversion == 'F'
2546 || dp->conversion == 'e' || dp->conversion == 'E'
2547 || dp->conversion == 'g' || dp->conversion == 'G'
2548 || dp->conversion == 'a' || dp->conversion == 'A')
2550 # if NEED_PRINTF_DOUBLE
2551 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2552 # elif NEED_PRINTF_INFINITE_DOUBLE
2553 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2554 /* The systems (mingw) which produce wrong output
2555 for Inf, -Inf, and NaN also do so for -0.0.
2556 Therefore we treat this case here as well. */
2557 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2559 # if NEED_PRINTF_LONG_DOUBLE
2560 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2561 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2562 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2563 /* Some systems produce wrong output for Inf,
2565 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
2569 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2570 arg_type type = a.arg[dp->arg_index].type;
2572 int flags = dp->flags;
2578 DCHAR_T tmpbuf[700];
2585 if (dp->width_start != dp->width_end)
2587 if (dp->width_arg_index != ARG_NONE)
2591 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2593 arg = a.arg[dp->width_arg_index].a.a_int;
2596 /* "A negative field width is taken as a '-' flag
2597 followed by a positive field width." */
2599 width = (unsigned int) (-arg);
2606 const FCHAR_T *digitp = dp->width_start;
2609 width = xsum (xtimes (width, 10), *digitp++ - '0');
2610 while (digitp != dp->width_end);
2617 if (dp->precision_start != dp->precision_end)
2619 if (dp->precision_arg_index != ARG_NONE)
2623 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2625 arg = a.arg[dp->precision_arg_index].a.a_int;
2626 /* "A negative precision is taken as if the precision
2636 const FCHAR_T *digitp = dp->precision_start + 1;
2639 while (digitp != dp->precision_end)
2640 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2645 /* POSIX specifies the default precision to be 6 for %f, %F,
2646 %e, %E, but not for %g, %G. Implementations appear to use
2647 the same default precision also for %g, %G. */
2651 /* Allocate a temporary buffer of sufficient size. */
2652 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2653 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
2654 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2655 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2656 # elif NEED_PRINTF_LONG_DOUBLE
2657 tmp_length = LDBL_DIG + 1;
2658 # elif NEED_PRINTF_DOUBLE
2659 tmp_length = DBL_DIG + 1;
2663 if (tmp_length < precision)
2664 tmp_length = precision;
2665 # if NEED_PRINTF_LONG_DOUBLE
2666 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2667 if (type == TYPE_LONGDOUBLE)
2669 if (dp->conversion == 'f' || dp->conversion == 'F')
2671 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2672 if (!(isnanl (arg) || arg + arg == arg))
2674 /* arg is finite and nonzero. */
2675 int exponent = floorlog10l (arg < 0 ? -arg : arg);
2676 if (exponent >= 0 && tmp_length < exponent + precision)
2677 tmp_length = exponent + precision;
2681 # if NEED_PRINTF_DOUBLE
2682 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2683 if (type == TYPE_DOUBLE)
2685 if (dp->conversion == 'f' || dp->conversion == 'F')
2687 double arg = a.arg[dp->arg_index].a.a_double;
2688 if (!(isnand (arg) || arg + arg == arg))
2690 /* arg is finite and nonzero. */
2691 int exponent = floorlog10 (arg < 0 ? -arg : arg);
2692 if (exponent >= 0 && tmp_length < exponent + precision)
2693 tmp_length = exponent + precision;
2697 /* Account for sign, decimal point etc. */
2698 tmp_length = xsum (tmp_length, 12);
2700 if (tmp_length < width)
2703 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2705 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2709 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2711 if (size_overflow_p (tmp_memsize))
2712 /* Overflow, would lead to out of memory. */
2714 tmp = (DCHAR_T *) malloc (tmp_memsize);
2716 /* Out of memory. */
2723 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2724 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2725 if (type == TYPE_LONGDOUBLE)
2728 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2732 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2734 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2738 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2744 DECL_LONG_DOUBLE_ROUNDING
2746 BEGIN_LONG_DOUBLE_ROUNDING ();
2748 if (signbit (arg)) /* arg < 0.0L or negative zero */
2756 else if (flags & FLAG_SHOWSIGN)
2758 else if (flags & FLAG_SPACE)
2761 if (arg > 0.0L && arg + arg == arg)
2763 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2765 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2769 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2774 # if NEED_PRINTF_LONG_DOUBLE
2777 if (dp->conversion == 'f' || dp->conversion == 'F')
2783 scale10_round_decimal_long_double (arg, precision);
2786 END_LONG_DOUBLE_ROUNDING ();
2789 ndigits = strlen (digits);
2791 if (ndigits > precision)
2795 *p++ = digits[ndigits];
2797 while (ndigits > precision);
2800 /* Here ndigits <= precision. */
2801 if ((flags & FLAG_ALT) || precision > 0)
2803 *p++ = decimal_point_char ();
2804 for (; precision > ndigits; precision--)
2809 *p++ = digits[ndigits];
2815 else if (dp->conversion == 'e' || dp->conversion == 'E')
2823 if ((flags & FLAG_ALT) || precision > 0)
2825 *p++ = decimal_point_char ();
2826 for (; precision > 0; precision--)
2837 exponent = floorlog10l (arg);
2842 scale10_round_decimal_long_double (arg,
2843 (int)precision - exponent);
2846 END_LONG_DOUBLE_ROUNDING ();
2849 ndigits = strlen (digits);
2851 if (ndigits == precision + 1)
2853 if (ndigits < precision
2854 || ndigits > precision + 2)
2855 /* The exponent was not guessed
2856 precisely enough. */
2859 /* None of two values of exponent is
2860 the right one. Prevent an endless
2864 if (ndigits == precision)
2870 /* Here ndigits = precision+1. */
2871 if (is_borderline (digits, precision))
2873 /* Maybe the exponent guess was too high
2874 and a smaller exponent can be reached
2875 by turning a 10...0 into 9...9x. */
2877 scale10_round_decimal_long_double (arg,
2878 (int)precision - exponent + 1);
2879 if (digits2 == NULL)
2882 END_LONG_DOUBLE_ROUNDING ();
2885 if (strlen (digits2) == precision + 1)
2894 /* Here ndigits = precision+1. */
2896 *p++ = digits[--ndigits];
2897 if ((flags & FLAG_ALT) || precision > 0)
2899 *p++ = decimal_point_char ();
2903 *p++ = digits[ndigits];
2910 *p++ = dp->conversion; /* 'e' or 'E' */
2911 # if WIDE_CHAR_VERSION
2913 static const wchar_t decimal_format[] =
2914 { '%', '+', '.', '2', 'd', '\0' };
2915 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2920 if (sizeof (DCHAR_T) == 1)
2922 sprintf ((char *) p, "%+.2d", exponent);
2930 sprintf (expbuf, "%+.2d", exponent);
2931 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2936 else if (dp->conversion == 'g' || dp->conversion == 'G')
2940 /* precision >= 1. */
2943 /* The exponent is 0, >= -4, < precision.
2944 Use fixed-point notation. */
2946 size_t ndigits = precision;
2947 /* Number of trailing zeroes that have to be
2950 (flags & FLAG_ALT ? 0 : precision - 1);
2954 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2956 *p++ = decimal_point_char ();
2957 while (ndigits > nzeroes)
2973 exponent = floorlog10l (arg);
2978 scale10_round_decimal_long_double (arg,
2979 (int)(precision - 1) - exponent);
2982 END_LONG_DOUBLE_ROUNDING ();
2985 ndigits = strlen (digits);
2987 if (ndigits == precision)
2989 if (ndigits < precision - 1
2990 || ndigits > precision + 1)
2991 /* The exponent was not guessed
2992 precisely enough. */
2995 /* None of two values of exponent is
2996 the right one. Prevent an endless
3000 if (ndigits < precision)
3006 /* Here ndigits = precision. */
3007 if (is_borderline (digits, precision - 1))
3009 /* Maybe the exponent guess was too high
3010 and a smaller exponent can be reached
3011 by turning a 10...0 into 9...9x. */
3013 scale10_round_decimal_long_double (arg,
3014 (int)(precision - 1) - exponent + 1);
3015 if (digits2 == NULL)
3018 END_LONG_DOUBLE_ROUNDING ();
3021 if (strlen (digits2) == precision)
3030 /* Here ndigits = precision. */
3032 /* Determine the number of trailing zeroes
3033 that have to be dropped. */
3035 if ((flags & FLAG_ALT) == 0)
3036 while (nzeroes < ndigits
3037 && digits[nzeroes] == '0')
3040 /* The exponent is now determined. */
3042 && exponent < (long)precision)
3044 /* Fixed-point notation:
3045 max(exponent,0)+1 digits, then the
3046 decimal point, then the remaining
3047 digits without trailing zeroes. */
3050 size_t count = exponent + 1;
3051 /* Note: count <= precision = ndigits. */
3052 for (; count > 0; count--)
3053 *p++ = digits[--ndigits];
3054 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3056 *p++ = decimal_point_char ();
3057 while (ndigits > nzeroes)
3060 *p++ = digits[ndigits];
3066 size_t count = -exponent - 1;
3068 *p++ = decimal_point_char ();
3069 for (; count > 0; count--)
3071 while (ndigits > nzeroes)
3074 *p++ = digits[ndigits];
3080 /* Exponential notation. */
3081 *p++ = digits[--ndigits];
3082 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3084 *p++ = decimal_point_char ();
3085 while (ndigits > nzeroes)
3088 *p++ = digits[ndigits];
3091 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3092 # if WIDE_CHAR_VERSION
3094 static const wchar_t decimal_format[] =
3095 { '%', '+', '.', '2', 'd', '\0' };
3096 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3101 if (sizeof (DCHAR_T) == 1)
3103 sprintf ((char *) p, "%+.2d", exponent);
3111 sprintf (expbuf, "%+.2d", exponent);
3112 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3124 /* arg is finite. */
3129 END_LONG_DOUBLE_ROUNDING ();
3132 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3136 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3138 double arg = a.arg[dp->arg_index].a.a_double;
3142 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3144 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3148 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3155 if (signbit (arg)) /* arg < 0.0 or negative zero */
3163 else if (flags & FLAG_SHOWSIGN)
3165 else if (flags & FLAG_SPACE)
3168 if (arg > 0.0 && arg + arg == arg)
3170 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3172 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3176 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3181 # if NEED_PRINTF_DOUBLE
3184 if (dp->conversion == 'f' || dp->conversion == 'F')
3190 scale10_round_decimal_double (arg, precision);
3193 ndigits = strlen (digits);
3195 if (ndigits > precision)
3199 *p++ = digits[ndigits];
3201 while (ndigits > precision);
3204 /* Here ndigits <= precision. */
3205 if ((flags & FLAG_ALT) || precision > 0)
3207 *p++ = decimal_point_char ();
3208 for (; precision > ndigits; precision--)
3213 *p++ = digits[ndigits];
3219 else if (dp->conversion == 'e' || dp->conversion == 'E')
3227 if ((flags & FLAG_ALT) || precision > 0)
3229 *p++ = decimal_point_char ();
3230 for (; precision > 0; precision--)
3241 exponent = floorlog10 (arg);
3246 scale10_round_decimal_double (arg,
3247 (int)precision - exponent);
3250 ndigits = strlen (digits);
3252 if (ndigits == precision + 1)
3254 if (ndigits < precision
3255 || ndigits > precision + 2)
3256 /* The exponent was not guessed
3257 precisely enough. */
3260 /* None of two values of exponent is
3261 the right one. Prevent an endless
3265 if (ndigits == precision)
3271 /* Here ndigits = precision+1. */
3272 if (is_borderline (digits, precision))
3274 /* Maybe the exponent guess was too high
3275 and a smaller exponent can be reached
3276 by turning a 10...0 into 9...9x. */
3278 scale10_round_decimal_double (arg,
3279 (int)precision - exponent + 1);
3280 if (digits2 == NULL)
3285 if (strlen (digits2) == precision + 1)
3294 /* Here ndigits = precision+1. */
3296 *p++ = digits[--ndigits];
3297 if ((flags & FLAG_ALT) || precision > 0)
3299 *p++ = decimal_point_char ();
3303 *p++ = digits[ndigits];
3310 *p++ = dp->conversion; /* 'e' or 'E' */
3311 # if WIDE_CHAR_VERSION
3313 static const wchar_t decimal_format[] =
3314 /* Produce the same number of exponent digits
3315 as the native printf implementation. */
3316 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3317 { '%', '+', '.', '3', 'd', '\0' };
3319 { '%', '+', '.', '2', 'd', '\0' };
3321 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3327 static const char decimal_format[] =
3328 /* Produce the same number of exponent digits
3329 as the native printf implementation. */
3330 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3335 if (sizeof (DCHAR_T) == 1)
3337 sprintf ((char *) p, decimal_format, exponent);
3345 sprintf (expbuf, decimal_format, exponent);
3346 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3352 else if (dp->conversion == 'g' || dp->conversion == 'G')
3356 /* precision >= 1. */
3359 /* The exponent is 0, >= -4, < precision.
3360 Use fixed-point notation. */
3362 size_t ndigits = precision;
3363 /* Number of trailing zeroes that have to be
3366 (flags & FLAG_ALT ? 0 : precision - 1);
3370 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3372 *p++ = decimal_point_char ();
3373 while (ndigits > nzeroes)
3389 exponent = floorlog10 (arg);
3394 scale10_round_decimal_double (arg,
3395 (int)(precision - 1) - exponent);
3398 ndigits = strlen (digits);
3400 if (ndigits == precision)
3402 if (ndigits < precision - 1
3403 || ndigits > precision + 1)
3404 /* The exponent was not guessed
3405 precisely enough. */
3408 /* None of two values of exponent is
3409 the right one. Prevent an endless
3413 if (ndigits < precision)
3419 /* Here ndigits = precision. */
3420 if (is_borderline (digits, precision - 1))
3422 /* Maybe the exponent guess was too high
3423 and a smaller exponent can be reached
3424 by turning a 10...0 into 9...9x. */
3426 scale10_round_decimal_double (arg,
3427 (int)(precision - 1) - exponent + 1);
3428 if (digits2 == NULL)
3433 if (strlen (digits2) == precision)
3442 /* Here ndigits = precision. */
3444 /* Determine the number of trailing zeroes
3445 that have to be dropped. */
3447 if ((flags & FLAG_ALT) == 0)
3448 while (nzeroes < ndigits
3449 && digits[nzeroes] == '0')
3452 /* The exponent is now determined. */
3454 && exponent < (long)precision)
3456 /* Fixed-point notation:
3457 max(exponent,0)+1 digits, then the
3458 decimal point, then the remaining
3459 digits without trailing zeroes. */
3462 size_t count = exponent + 1;
3463 /* Note: count <= precision = ndigits. */
3464 for (; count > 0; count--)
3465 *p++ = digits[--ndigits];
3466 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3468 *p++ = decimal_point_char ();
3469 while (ndigits > nzeroes)
3472 *p++ = digits[ndigits];
3478 size_t count = -exponent - 1;
3480 *p++ = decimal_point_char ();
3481 for (; count > 0; count--)
3483 while (ndigits > nzeroes)
3486 *p++ = digits[ndigits];
3492 /* Exponential notation. */
3493 *p++ = digits[--ndigits];
3494 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3496 *p++ = decimal_point_char ();
3497 while (ndigits > nzeroes)
3500 *p++ = digits[ndigits];
3503 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3504 # if WIDE_CHAR_VERSION
3506 static const wchar_t decimal_format[] =
3507 /* Produce the same number of exponent digits
3508 as the native printf implementation. */
3509 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3510 { '%', '+', '.', '3', 'd', '\0' };
3512 { '%', '+', '.', '2', 'd', '\0' };
3514 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3520 static const char decimal_format[] =
3521 /* Produce the same number of exponent digits
3522 as the native printf implementation. */
3523 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3528 if (sizeof (DCHAR_T) == 1)
3530 sprintf ((char *) p, decimal_format, exponent);
3538 sprintf (expbuf, decimal_format, exponent);
3539 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3552 /* arg is finite. */
3558 if (dp->conversion == 'f' || dp->conversion == 'F')
3561 if ((flags & FLAG_ALT) || precision > 0)
3563 *p++ = decimal_point_char ();
3564 for (; precision > 0; precision--)
3568 else if (dp->conversion == 'e' || dp->conversion == 'E')
3571 if ((flags & FLAG_ALT) || precision > 0)
3573 *p++ = decimal_point_char ();
3574 for (; precision > 0; precision--)
3577 *p++ = dp->conversion; /* 'e' or 'E' */
3579 /* Produce the same number of exponent digits as
3580 the native printf implementation. */
3581 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3587 else if (dp->conversion == 'g' || dp->conversion == 'G')
3590 if (flags & FLAG_ALT)
3593 (precision > 0 ? precision - 1 : 0);
3594 *p++ = decimal_point_char ();
3595 for (; ndigits > 0; --ndigits)
3607 /* The generated string now extends from tmp to p, with the
3608 zero padding insertion point being at pad_ptr. */
3609 if (has_width && p - tmp < width)
3611 size_t pad = width - (p - tmp);
3612 DCHAR_T *end = p + pad;
3614 if (flags & FLAG_LEFT)
3616 /* Pad with spaces on the right. */
3617 for (; pad > 0; pad--)
3620 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3622 /* Pad with zeroes. */
3627 for (; pad > 0; pad--)
3632 /* Pad with spaces on the left. */
3637 for (; pad > 0; pad--)
3645 size_t count = p - tmp;
3647 if (count >= tmp_length)
3648 /* tmp_length was incorrectly calculated - fix the
3652 /* Make room for the result. */
3653 if (count >= allocated - length)
3655 size_t n = xsum (length, count);
3657 ENSURE_ALLOCATION (n);
3660 /* Append the result. */
3661 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3670 arg_type type = a.arg[dp->arg_index].type;
3671 int flags = dp->flags;
3672 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3676 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3680 #if NEED_PRINTF_UNBOUNDED_PRECISION
3683 # define prec_ourselves 0
3685 #if NEED_PRINTF_FLAG_LEFTADJUST
3686 # define pad_ourselves 1
3687 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3690 # define pad_ourselves 0
3693 unsigned int prefix_count;
3697 TCHAR_T tmpbuf[700];
3701 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3704 if (dp->width_start != dp->width_end)
3706 if (dp->width_arg_index != ARG_NONE)
3710 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3712 arg = a.arg[dp->width_arg_index].a.a_int;
3715 /* "A negative field width is taken as a '-' flag
3716 followed by a positive field width." */
3718 width = (unsigned int) (-arg);
3725 const FCHAR_T *digitp = dp->width_start;
3728 width = xsum (xtimes (width, 10), *digitp++ - '0');
3729 while (digitp != dp->width_end);
3735 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3738 if (dp->precision_start != dp->precision_end)
3740 if (dp->precision_arg_index != ARG_NONE)
3744 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3746 arg = a.arg[dp->precision_arg_index].a.a_int;
3747 /* "A negative precision is taken as if the precision
3757 const FCHAR_T *digitp = dp->precision_start + 1;
3760 while (digitp != dp->precision_end)
3761 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3767 /* Decide whether to handle the precision ourselves. */
3768 #if NEED_PRINTF_UNBOUNDED_PRECISION
3769 switch (dp->conversion)
3771 case 'd': case 'i': case 'u':
3773 case 'x': case 'X': case 'p':
3774 prec_ourselves = has_precision && (precision > 0);
3782 /* Decide whether to perform the padding ourselves. */
3783 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
3784 switch (dp->conversion)
3786 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
3787 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
3788 to perform the padding after this conversion. Functions
3789 with unistdio extensions perform the padding based on
3790 character count rather than element count. */
3793 # if NEED_PRINTF_FLAG_ZERO
3794 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
3800 pad_ourselves = prec_ourselves;
3806 /* Allocate a temporary buffer of sufficient size for calling
3809 switch (dp->conversion)
3812 case 'd': case 'i': case 'u':
3813 # if HAVE_LONG_LONG_INT
3814 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3816 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3817 * 0.30103 /* binary -> decimal */
3819 + 1; /* turn floor into ceil */
3822 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3824 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3825 * 0.30103 /* binary -> decimal */
3827 + 1; /* turn floor into ceil */
3830 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3831 * 0.30103 /* binary -> decimal */
3833 + 1; /* turn floor into ceil */
3834 if (tmp_length < precision)
3835 tmp_length = precision;
3836 /* Multiply by 2, as an estimate for FLAG_GROUP. */
3837 tmp_length = xsum (tmp_length, tmp_length);
3838 /* Add 1, to account for a leading sign. */
3839 tmp_length = xsum (tmp_length, 1);
3843 # if HAVE_LONG_LONG_INT
3844 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3846 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3847 * 0.333334 /* binary -> octal */
3849 + 1; /* turn floor into ceil */
3852 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3854 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3855 * 0.333334 /* binary -> octal */
3857 + 1; /* turn floor into ceil */
3860 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3861 * 0.333334 /* binary -> octal */
3863 + 1; /* turn floor into ceil */
3864 if (tmp_length < precision)
3865 tmp_length = precision;
3866 /* Add 1, to account for a leading sign. */
3867 tmp_length = xsum (tmp_length, 1);
3871 # if HAVE_LONG_LONG_INT
3872 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3874 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3875 * 0.25 /* binary -> hexadecimal */
3877 + 1; /* turn floor into ceil */
3880 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3882 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3883 * 0.25 /* binary -> hexadecimal */
3885 + 1; /* turn floor into ceil */
3888 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3889 * 0.25 /* binary -> hexadecimal */
3891 + 1; /* turn floor into ceil */
3892 if (tmp_length < precision)
3893 tmp_length = precision;
3894 /* Add 2, to account for a leading sign or alternate form. */
3895 tmp_length = xsum (tmp_length, 2);
3899 if (type == TYPE_LONGDOUBLE)
3901 (unsigned int) (LDBL_MAX_EXP
3902 * 0.30103 /* binary -> decimal */
3903 * 2 /* estimate for FLAG_GROUP */
3905 + 1 /* turn floor into ceil */
3906 + 10; /* sign, decimal point etc. */
3909 (unsigned int) (DBL_MAX_EXP
3910 * 0.30103 /* binary -> decimal */
3911 * 2 /* estimate for FLAG_GROUP */
3913 + 1 /* turn floor into ceil */
3914 + 10; /* sign, decimal point etc. */
3915 tmp_length = xsum (tmp_length, precision);
3918 case 'e': case 'E': case 'g': case 'G':
3920 12; /* sign, decimal point, exponent etc. */
3921 tmp_length = xsum (tmp_length, precision);
3925 if (type == TYPE_LONGDOUBLE)
3927 (unsigned int) (LDBL_DIG
3928 * 0.831 /* decimal -> hexadecimal */
3930 + 1; /* turn floor into ceil */
3933 (unsigned int) (DBL_DIG
3934 * 0.831 /* decimal -> hexadecimal */
3936 + 1; /* turn floor into ceil */
3937 if (tmp_length < precision)
3938 tmp_length = precision;
3939 /* Account for sign, decimal point etc. */
3940 tmp_length = xsum (tmp_length, 12);
3944 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
3945 if (type == TYPE_WIDE_CHAR)
3946 tmp_length = MB_CUR_MAX;
3954 if (type == TYPE_WIDE_STRING)
3957 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
3959 # if !WIDE_CHAR_VERSION
3960 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
3965 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
3970 (unsigned int) (sizeof (void *) * CHAR_BIT
3971 * 0.25 /* binary -> hexadecimal */
3973 + 1 /* turn floor into ceil */
3974 + 2; /* account for leading 0x */
3983 # if ENABLE_UNISTDIO
3984 /* Padding considers the number of characters, therefore
3985 the number of elements after padding may be
3986 > max (tmp_length, width)
3988 <= tmp_length + width. */
3989 tmp_length = xsum (tmp_length, width);
3991 /* Padding considers the number of elements,
3993 if (tmp_length < width)
3998 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
4001 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4005 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4007 if (size_overflow_p (tmp_memsize))
4008 /* Overflow, would lead to out of memory. */
4010 tmp = (TCHAR_T *) malloc (tmp_memsize);
4012 /* Out of memory. */
4017 /* Construct the format string for calling snprintf or
4021 #if NEED_PRINTF_FLAG_GROUPING
4022 /* The underlying implementation doesn't support the ' flag.
4023 Produce no grouping characters in this case; this is
4024 acceptable because the grouping is locale dependent. */
4026 if (flags & FLAG_GROUP)
4029 if (flags & FLAG_LEFT)
4031 if (flags & FLAG_SHOWSIGN)
4033 if (flags & FLAG_SPACE)
4035 if (flags & FLAG_ALT)
4039 if (flags & FLAG_ZERO)
4041 if (dp->width_start != dp->width_end)
4043 size_t n = dp->width_end - dp->width_start;
4044 /* The width specification is known to consist only
4045 of standard ASCII characters. */
4046 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4048 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4053 const FCHAR_T *mp = dp->width_start;
4055 *fbp++ = (unsigned char) *mp++;
4060 if (!prec_ourselves)
4062 if (dp->precision_start != dp->precision_end)
4064 size_t n = dp->precision_end - dp->precision_start;
4065 /* The precision specification is known to consist only
4066 of standard ASCII characters. */
4067 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4069 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4074 const FCHAR_T *mp = dp->precision_start;
4076 *fbp++ = (unsigned char) *mp++;
4084 #if HAVE_LONG_LONG_INT
4085 case TYPE_LONGLONGINT:
4086 case TYPE_ULONGLONGINT:
4087 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4100 case TYPE_WIDE_CHAR:
4103 case TYPE_WIDE_STRING:
4107 case TYPE_LONGDOUBLE:
4113 #if NEED_PRINTF_DIRECTIVE_F
4114 if (dp->conversion == 'F')
4118 *fbp = dp->conversion;
4120 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4125 /* On glibc2 systems from glibc >= 2.3 - probably also older
4126 ones - we know that snprintf's returns value conforms to
4127 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4128 Therefore we can avoid using %n in this situation.
4129 On glibc2 systems from 2004-10-18 or newer, the use of %n
4130 in format strings in writable memory may crash the program
4131 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4132 in this situation. */
4133 /* On native Win32 systems (such as mingw), we can avoid using
4135 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4136 snprintf does not write more than the specified number
4137 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4138 '4', '5', '6' into buf, not '4', '5', '\0'.)
4139 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4140 allows us to recognize the case of an insufficient
4141 buffer size: it returns -1 in this case.
4142 On native Win32 systems (such as mingw) where the OS is
4143 Windows Vista, the use of %n in format strings by default
4144 crashes the program. See
4145 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4146 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4147 So we should avoid %n in this situation. */
4154 /* Construct the arguments for calling snprintf or sprintf. */
4156 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4158 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4160 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4162 if (dp->precision_arg_index != ARG_NONE)
4164 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4166 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4170 /* The SNPRINTF result is appended after result[0..length].
4171 The latter is an array of DCHAR_T; SNPRINTF appends an
4172 array of TCHAR_T to it. This is possible because
4173 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4174 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4175 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4176 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4177 where an snprintf() with maxlen==1 acts like sprintf(). */
4178 ENSURE_ALLOCATION (xsum (length,
4179 (2 + TCHARS_PER_DCHAR - 1)
4180 / TCHARS_PER_DCHAR));
4181 /* Prepare checking whether snprintf returns the count
4183 *(TCHAR_T *) (result + length) = '\0';
4192 size_t maxlen = allocated - length;
4193 /* SNPRINTF can fail if its second argument is
4195 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4196 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4197 maxlen = maxlen * TCHARS_PER_DCHAR;
4198 # define SNPRINTF_BUF(arg) \
4199 switch (prefix_count) \
4202 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4207 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4209 prefixes[0], arg, &count); \
4212 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4214 prefixes[0], prefixes[1], arg, \
4221 # define SNPRINTF_BUF(arg) \
4222 switch (prefix_count) \
4225 count = sprintf (tmp, buf, arg); \
4228 count = sprintf (tmp, buf, prefixes[0], arg); \
4231 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4243 int arg = a.arg[dp->arg_index].a.a_schar;
4249 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4255 int arg = a.arg[dp->arg_index].a.a_short;
4261 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4267 int arg = a.arg[dp->arg_index].a.a_int;
4273 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4279 long int arg = a.arg[dp->arg_index].a.a_longint;
4285 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4289 #if HAVE_LONG_LONG_INT
4290 case TYPE_LONGLONGINT:
4292 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4296 case TYPE_ULONGLONGINT:
4298 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4305 double arg = a.arg[dp->arg_index].a.a_double;
4309 case TYPE_LONGDOUBLE:
4311 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4317 int arg = a.arg[dp->arg_index].a.a_char;
4322 case TYPE_WIDE_CHAR:
4324 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
4331 const char *arg = a.arg[dp->arg_index].a.a_string;
4336 case TYPE_WIDE_STRING:
4338 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
4345 void *arg = a.arg[dp->arg_index].a.a_pointer;
4354 /* Portability: Not all implementations of snprintf()
4355 are ISO C 99 compliant. Determine the number of
4356 bytes that snprintf() has produced or would have
4360 /* Verify that snprintf() has NUL-terminated its
4363 && ((TCHAR_T *) (result + length)) [count] != '\0')
4365 /* Portability hack. */
4366 if (retcount > count)
4371 /* snprintf() doesn't understand the '%n'
4375 /* Don't use the '%n' directive; instead, look
4376 at the snprintf() return value. */
4382 /* Look at the snprintf() return value. */
4385 /* HP-UX 10.20 snprintf() is doubly deficient:
4386 It doesn't understand the '%n' directive,
4387 *and* it returns -1 (rather than the length
4388 that would have been required) when the
4389 buffer is too small. */
4390 size_t bigger_need =
4391 xsum (xtimes (allocated, 2), 12);
4392 ENSURE_ALLOCATION (bigger_need);
4401 /* Attempt to handle failure. */
4404 if (!(result == resultbuf || result == NULL))
4406 if (buf_malloced != NULL)
4407 free (buf_malloced);
4414 /* Handle overflow of the allocated buffer.
4415 If such an overflow occurs, a C99 compliant snprintf()
4416 returns a count >= maxlen. However, a non-compliant
4417 snprintf() function returns only count = maxlen - 1. To
4418 cover both cases, test whether count >= maxlen - 1. */
4419 if ((unsigned int) count + 1 >= maxlen)
4421 /* If maxlen already has attained its allowed maximum,
4422 allocating more memory will not increase maxlen.
4423 Instead of looping, bail out. */
4424 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
4428 /* Need at least (count + 1) * sizeof (TCHAR_T)
4429 bytes. (The +1 is for the trailing NUL.)
4430 But ask for (count + 2) * sizeof (TCHAR_T)
4431 bytes, so that in the next round, we likely get
4432 maxlen > (unsigned int) count + 1
4433 and so we don't get here again.
4434 And allocate proportionally, to avoid looping
4435 eternally if snprintf() reports a too small
4439 ((unsigned int) count + 2
4440 + TCHARS_PER_DCHAR - 1)
4441 / TCHARS_PER_DCHAR),
4442 xtimes (allocated, 2));
4444 ENSURE_ALLOCATION (n);
4450 #if NEED_PRINTF_UNBOUNDED_PRECISION
4453 /* Handle the precision. */
4456 (TCHAR_T *) (result + length);
4460 size_t prefix_count;
4464 /* Put the additional zeroes after the sign. */
4466 && (*prec_ptr == '-' || *prec_ptr == '+'
4467 || *prec_ptr == ' '))
4469 /* Put the additional zeroes after the 0x prefix if
4470 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
4472 && prec_ptr[0] == '0'
4473 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
4476 move = count - prefix_count;
4477 if (precision > move)
4479 /* Insert zeroes. */
4480 size_t insert = precision - move;
4486 (count + insert + TCHARS_PER_DCHAR - 1)
4487 / TCHARS_PER_DCHAR);
4488 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4489 ENSURE_ALLOCATION (n);
4490 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4491 prec_ptr = (TCHAR_T *) (result + length);
4494 prec_end = prec_ptr + count;
4495 prec_ptr += prefix_count;
4497 while (prec_end > prec_ptr)
4500 prec_end[insert] = prec_end[0];
4506 while (prec_end > prec_ptr);
4514 if (count >= tmp_length)
4515 /* tmp_length was incorrectly calculated - fix the
4521 /* Convert from TCHAR_T[] to DCHAR_T[]. */
4522 if (dp->conversion == 'c' || dp->conversion == 's')
4524 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
4526 The result string is not certainly ASCII. */
4527 const TCHAR_T *tmpsrc;
4530 /* This code assumes that TCHAR_T is 'char'. */
4531 typedef int TCHAR_T_verify
4532 [2 * (sizeof (TCHAR_T) == 1) - 1];
4534 tmpsrc = (TCHAR_T *) (result + length);
4540 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
4541 iconveh_question_mark,
4544 &tmpdst, &tmpdst_len)
4547 int saved_errno = errno;
4548 if (!(result == resultbuf || result == NULL))
4550 if (buf_malloced != NULL)
4551 free (buf_malloced);
4553 errno = saved_errno;
4556 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
4557 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
4563 /* The result string is ASCII.
4564 Simple 1:1 conversion. */
4566 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
4567 no-op conversion, in-place on the array starting
4568 at (result + length). */
4569 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
4572 const TCHAR_T *tmpsrc;
4577 if (result == resultbuf)
4579 tmpsrc = (TCHAR_T *) (result + length);
4580 /* ENSURE_ALLOCATION will not move tmpsrc
4581 (because it's part of resultbuf). */
4582 ENSURE_ALLOCATION (xsum (length, count));
4586 /* ENSURE_ALLOCATION will move the array
4587 (because it uses realloc(). */
4588 ENSURE_ALLOCATION (xsum (length, count));
4589 tmpsrc = (TCHAR_T *) (result + length);
4593 ENSURE_ALLOCATION (xsum (length, count));
4595 tmpdst = result + length;
4596 /* Copy backwards, because of overlapping. */
4599 for (n = count; n > 0; n--)
4600 *--tmpdst = (unsigned char) *--tmpsrc;
4605 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4606 /* Make room for the result. */
4607 if (count > allocated - length)
4609 /* Need at least count elements. But allocate
4612 xmax (xsum (length, count), xtimes (allocated, 2));
4614 ENSURE_ALLOCATION (n);
4618 /* Here count <= allocated - length. */
4620 /* Perform padding. */
4621 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4622 if (pad_ourselves && has_width)
4625 # if ENABLE_UNISTDIO
4626 /* Outside POSIX, it's preferrable to compare the width
4627 against the number of _characters_ of the converted
4629 w = DCHAR_MBSNLEN (result + length, count);
4631 /* The width is compared against the number of _bytes_
4632 of the converted value, says POSIX. */
4637 size_t pad = width - w;
4639 /* Make room for the result. */
4640 if (xsum (count, pad) > allocated - length)
4642 /* Need at least count + pad elements. But
4643 allocate proportionally. */
4645 xmax (xsum3 (length, count, pad),
4646 xtimes (allocated, 2));
4650 ENSURE_ALLOCATION (n);
4653 ENSURE_ALLOCATION (n);
4656 /* Here count + pad <= allocated - length. */
4659 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
4660 DCHAR_T * const rp = result + length;
4662 DCHAR_T * const rp = tmp;
4664 DCHAR_T *p = rp + count;
4665 DCHAR_T *end = p + pad;
4667 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4668 if (dp->conversion == 'c'
4669 || dp->conversion == 's')
4670 /* No zero-padding for string directives. */
4675 pad_ptr = (*rp == '-' ? rp + 1 : rp);
4676 /* No zero-padding of "inf" and "nan". */
4677 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
4678 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
4681 /* The generated string now extends from rp to p,
4682 with the zero padding insertion point being at
4685 count = count + pad; /* = end - rp */
4687 if (flags & FLAG_LEFT)
4689 /* Pad with spaces on the right. */
4690 for (; pad > 0; pad--)
4693 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4695 /* Pad with zeroes. */
4700 for (; pad > 0; pad--)
4705 /* Pad with spaces on the left. */
4710 for (; pad > 0; pad--)
4718 /* Here still count <= allocated - length. */
4720 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
4721 /* The snprintf() result did fit. */
4723 /* Append the sprintf() result. */
4724 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4731 #if NEED_PRINTF_DIRECTIVE_F
4732 if (dp->conversion == 'F')
4734 /* Convert the %f result to upper case for %F. */
4735 DCHAR_T *rp = result + length;
4737 for (rc = count; rc > 0; rc--, rp++)
4738 if (*rp >= 'a' && *rp <= 'z')
4739 *rp = *rp - 'a' + 'A';
4750 /* Add the final NUL. */
4751 ENSURE_ALLOCATION (xsum (length, 1));
4752 result[length] = '\0';
4754 if (result != resultbuf && length + 1 < allocated)
4756 /* Shrink the allocated memory if possible. */
4759 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
4764 if (buf_malloced != NULL)
4765 free (buf_malloced);
4768 /* Note that we can produce a big string of a length > INT_MAX. POSIX
4769 says that snprintf() fails with errno = EOVERFLOW in this case, but
4770 that's only because snprintf() returns an 'int'. This function does
4771 not have this limitation. */
4776 if (!(result == resultbuf || result == NULL))
4778 if (buf_malloced != NULL)
4779 free (buf_malloced);
4786 if (!(result == resultbuf || result == NULL))
4788 if (buf_malloced != NULL)
4789 free (buf_malloced);
4797 #undef TCHARS_PER_DCHAR
4804 #undef DCHAR_IS_TCHAR