1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2007 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* This file can be parametrized with the following macros:
19 VASNPRINTF The name of the function being defined.
20 FCHAR_T The element type of the format string.
21 DCHAR_T The element type of the destination (result) string.
22 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
23 in the format string are ASCII. MUST be set if
24 FCHAR_T and DCHAR_T are not the same type.
25 DIRECTIVE Structure denoting a format directive.
27 DIRECTIVES Structure denoting the set of format directives of a
28 format string. Depends on FCHAR_T.
29 PRINTF_PARSE Function that parses a format string.
31 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
32 DCHAR_SET memset like function for DCHAR_T[] arrays.
33 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
34 SNPRINTF The system's snprintf (or similar) function.
35 This may be either snprintf or swprintf.
36 TCHAR_T The element type of the argument and result string
37 of the said SNPRINTF function. This may be either
38 char or wchar_t. The code exploits that
39 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
40 alignof (TCHAR_T) <= alignof (DCHAR_T).
41 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
42 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
43 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
44 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
45 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
47 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
48 This must come before <config.h> because <config.h> may include
49 <features.h>, and once <features.h> has been included, it's too late. */
51 # define _GNU_SOURCE 1
63 # if WIDE_CHAR_VERSION
64 # include "vasnwprintf.h"
66 # include "vasnprintf.h"
70 #include <locale.h> /* localeconv() */
71 #include <stdio.h> /* snprintf(), sprintf() */
72 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
73 #include <string.h> /* memcpy(), strlen() */
74 #include <errno.h> /* errno */
75 #include <limits.h> /* CHAR_BIT */
76 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
78 # include <langinfo.h>
81 # if WIDE_CHAR_VERSION
82 # include "wprintf-parse.h"
84 # include "printf-parse.h"
88 /* Checked size_t computations. */
91 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
96 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
101 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
103 # include "isnanl-nolibm.h"
107 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
110 # include "printf-frexp.h"
113 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
115 # include "isnanl-nolibm.h"
116 # include "printf-frexpl.h"
120 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
122 # define EOVERFLOW E2BIG
127 # define local_wcslen wcslen
129 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
130 a dependency towards this library, here is a local substitute.
131 Define this substitute only once, even if this file is included
132 twice in the same compilation unit. */
133 # ifndef local_wcslen_defined
134 # define local_wcslen_defined 1
136 local_wcslen (const wchar_t *s)
140 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
148 /* Default parameters. */
150 # if WIDE_CHAR_VERSION
151 # define VASNPRINTF vasnwprintf
152 # define FCHAR_T wchar_t
153 # define DCHAR_T wchar_t
154 # define TCHAR_T wchar_t
155 # define DCHAR_IS_TCHAR 1
156 # define DIRECTIVE wchar_t_directive
157 # define DIRECTIVES wchar_t_directives
158 # define PRINTF_PARSE wprintf_parse
159 # define DCHAR_CPY wmemcpy
161 # define VASNPRINTF vasnprintf
162 # define FCHAR_T char
163 # define DCHAR_T char
164 # define TCHAR_T char
165 # define DCHAR_IS_TCHAR 1
166 # define DIRECTIVE char_directive
167 # define DIRECTIVES char_directives
168 # define PRINTF_PARSE printf_parse
169 # define DCHAR_CPY memcpy
172 #if WIDE_CHAR_VERSION
173 /* TCHAR_T is wchar_t. */
174 # define USE_SNPRINTF 1
175 # if HAVE_DECL__SNWPRINTF
176 /* On Windows, the function swprintf() has a different signature than
177 on Unix; we use the _snwprintf() function instead. */
178 # define SNPRINTF _snwprintf
181 # define SNPRINTF swprintf
184 /* TCHAR_T is char. */
185 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
186 But don't use it on BeOS, since BeOS snprintf produces no output if the
187 size argument is >= 0x3000000. */
188 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
189 # define USE_SNPRINTF 1
191 # define USE_SNPRINTF 0
193 # if HAVE_DECL__SNPRINTF
195 # define SNPRINTF _snprintf
198 # define SNPRINTF snprintf
199 /* Here we need to call the native snprintf, not rpl_snprintf. */
203 /* Here we need to call the native sprintf, not rpl_sprintf. */
206 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
207 /* Determine the decimal-point character according to the current locale. */
208 # ifndef decimal_point_char_defined
209 # define decimal_point_char_defined 1
211 decimal_point_char ()
214 /* Determine it in a multithread-safe way. We know nl_langinfo is
215 multithread-safe on glibc systems, but is not required to be multithread-
216 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
217 is rarely multithread-safe. */
218 # if HAVE_NL_LANGINFO && __GLIBC__
219 point = nl_langinfo (RADIXCHAR);
222 sprintf (pointbuf, "%#.0f", 1.0);
223 point = &pointbuf[1];
225 point = localeconv () -> decimal_point;
227 /* The decimal point is always a single byte: either '.' or ','. */
228 return (point[0] != '\0' ? point[0] : '.');
233 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
235 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
237 is_infinite_or_zero (double x)
239 return isnan (x) || x + x == x;
244 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
246 /* Equivalent to !isfinite(x), but does not require libm. */
248 is_infinitel (long double x)
250 return isnanl (x) || (x + x == x && x != 0.0L);
255 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
257 /* Converting 'long double' to decimal without rare rounding bugs requires
258 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
259 (and slower) algorithms. */
261 typedef unsigned int mp_limb_t;
262 # define GMP_LIMB_BITS 32
263 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
265 typedef unsigned long long mp_twolimb_t;
266 # define GMP_TWOLIMB_BITS 64
267 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
269 /* Representation of a bignum >= 0. */
273 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
276 /* Compute the product of two bignums >= 0.
277 Return the allocated memory in case of success, NULL in case of memory
278 allocation failure. */
280 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
287 if (src1.nlimbs <= src2.nlimbs)
301 /* Now 0 <= len1 <= len2. */
304 /* src1 or src2 is zero. */
306 dest->limbs = (mp_limb_t *) malloc (1);
310 /* Here 1 <= len1 <= len2. */
316 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
319 for (k = len2; k > 0; )
321 for (i = 0; i < len1; i++)
323 mp_limb_t digit1 = p1[i];
324 mp_twolimb_t carry = 0;
325 for (j = 0; j < len2; j++)
327 mp_limb_t digit2 = p2[j];
328 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
330 dp[i + j] = (mp_limb_t) carry;
331 carry = carry >> GMP_LIMB_BITS;
333 dp[i + len2] = (mp_limb_t) carry;
336 while (dlen > 0 && dp[dlen - 1] == 0)
344 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
345 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
347 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
349 Return the allocated memory in case of success, NULL in case of memory
350 allocation failure. */
352 divide (mpn_t a, mpn_t b, mpn_t *q)
355 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
356 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
357 If m<n, then q:=0 and r:=a.
358 If m>=n=1, perform a single-precision division:
361 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
362 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
363 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
364 Normalise [q[m-1],...,q[0]], yields q.
365 If m>=n>1, perform a multiple-precision division:
366 We have a/b < beta^(m-n+1).
367 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
368 Shift a and b left by s bits, copying them. r:=a.
369 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
370 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
372 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
373 In case of overflow (q* >= beta) set q* := beta-1.
374 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
375 and c3 := b[n-2] * q*.
376 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
377 occurred. Furthermore 0 <= c3 < beta^2.
378 If there was overflow and
379 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
380 the next test can be skipped.}
381 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
382 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
384 Put r := r - b * q* * beta^j. In detail:
385 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
386 hence: u:=0, for i:=0 to n-1 do
388 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
389 u:=u div beta (+ 1, if carry in subtraction)
391 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
393 the carry u does not overflow.}
394 If a negative carry occurs, put q* := q* - 1
395 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
397 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
398 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
400 The room for q[j] can be allocated at the memory location of r[n+j].
401 Finally, round-to-even:
402 Shift r left by 1 bit.
403 If r > b or if r = b and q[0] is odd, q := q+1.
405 const mp_limb_t *a_ptr = a.limbs;
406 size_t a_len = a.nlimbs;
407 const mp_limb_t *b_ptr = b.limbs;
408 size_t b_len = b.nlimbs;
410 mp_limb_t *tmp_roomptr = NULL;
416 /* Allocate room for a_len+2 digits.
417 (Need a_len+1 digits for the real division and 1 more digit for the
418 final rounding of q.) */
419 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
424 while (a_len > 0 && a_ptr[a_len - 1] == 0)
431 /* Division by zero. */
433 if (b_ptr[b_len - 1] == 0)
439 /* Here m = a_len >= 0 and n = b_len > 0. */
443 /* m<n: trivial case. q=0, r := copy of a. */
446 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
447 q_ptr = roomptr + a_len;
452 /* n=1: single precision division.
453 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
457 mp_limb_t den = b_ptr[0];
458 mp_limb_t remainder = 0;
459 const mp_limb_t *sourceptr = a_ptr + a_len;
460 mp_limb_t *destptr = q_ptr + a_len;
462 for (count = a_len; count > 0; count--)
465 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
466 *--destptr = num / den;
467 remainder = num % den;
469 /* Normalise and store r. */
472 r_ptr[0] = remainder;
479 if (q_ptr[q_len - 1] == 0)
485 /* n>1: multiple precision division.
486 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
487 beta^(m-n-1) <= a/b < beta^(m-n+1). */
491 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
519 /* 0 <= s < GMP_LIMB_BITS.
520 Copy b, shifting it left by s bits. */
523 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
524 if (tmp_roomptr == NULL)
530 const mp_limb_t *sourceptr = b_ptr;
531 mp_limb_t *destptr = tmp_roomptr;
532 mp_twolimb_t accu = 0;
534 for (count = b_len; count > 0; count--)
536 accu += (mp_twolimb_t) *sourceptr++ << s;
537 *destptr++ = (mp_limb_t) accu;
538 accu = accu >> GMP_LIMB_BITS;
540 /* accu must be zero, since that was how s was determined. */
546 /* Copy a, shifting it left by s bits, yields r.
548 At the beginning: r = roomptr[0..a_len],
549 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
553 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
558 const mp_limb_t *sourceptr = a_ptr;
559 mp_limb_t *destptr = r_ptr;
560 mp_twolimb_t accu = 0;
562 for (count = a_len; count > 0; count--)
564 accu += (mp_twolimb_t) *sourceptr++ << s;
565 *destptr++ = (mp_limb_t) accu;
566 accu = accu >> GMP_LIMB_BITS;
568 *destptr++ = (mp_limb_t) accu;
570 q_ptr = roomptr + b_len;
571 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
573 size_t j = a_len - b_len; /* m-n */
574 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
575 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
576 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
577 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
578 /* Division loop, traversed m-n+1 times.
579 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
584 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
586 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
588 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
589 | r_ptr[j + b_len - 1];
590 q_star = num / b_msd;
595 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
596 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
597 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
598 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
599 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
601 If yes, jump directly to the subtraction loop.
602 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
603 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
604 if (r_ptr[j + b_len] > b_msd
605 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
606 /* r[j+n] >= b[n-1]+1 or
607 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
612 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
614 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
615 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
616 mp_twolimb_t c3 = /* b[n-2] * q* */
617 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
618 /* While c2 < c3, increase c2 and decrease c3.
619 Consider c3-c2. While it is > 0, decrease it by
620 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
621 this can happen only twice. */
624 q_star = q_star - 1; /* q* := q* - 1 */
625 if (c3 - c2 > b_msdd)
626 q_star = q_star - 1; /* q* := q* - 1 */
632 /* Subtract r := r - b * q* * beta^j. */
635 const mp_limb_t *sourceptr = b_ptr;
636 mp_limb_t *destptr = r_ptr + j;
637 mp_twolimb_t carry = 0;
639 for (count = b_len; count > 0; count--)
641 /* Here 0 <= carry <= q*. */
644 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
645 + (mp_limb_t) ~(*destptr);
646 /* Here 0 <= carry <= beta*q* + beta-1. */
647 *destptr++ = ~(mp_limb_t) carry;
648 carry = carry >> GMP_LIMB_BITS; /* <= q* */
650 cr = (mp_limb_t) carry;
652 /* Subtract cr from r_ptr[j + b_len], then forget about
654 if (cr > r_ptr[j + b_len])
656 /* Subtraction gave a carry. */
657 q_star = q_star - 1; /* q* := q* - 1 */
660 const mp_limb_t *sourceptr = b_ptr;
661 mp_limb_t *destptr = r_ptr + j;
664 for (count = b_len; count > 0; count--)
666 mp_limb_t source1 = *sourceptr++;
667 mp_limb_t source2 = *destptr;
668 *destptr++ = source1 + source2 + carry;
671 ? source1 >= (mp_limb_t) ~source2
672 : source1 > (mp_limb_t) ~source2);
675 /* Forget about the carry and about r[j+n]. */
678 /* q* is determined. Store it as q[j]. */
687 if (q_ptr[q_len - 1] == 0)
689 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
690 b is shifted left by s bits. */
691 /* Shift r right by s bits. */
694 mp_limb_t ptr = r_ptr + r_len;
695 mp_twolimb_t accu = 0;
697 for (count = r_len; count > 0; count--)
699 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
700 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
701 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
706 while (r_len > 0 && r_ptr[r_len - 1] == 0)
709 /* Compare r << 1 with b. */
717 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
718 | (i < r_len ? r_ptr[i] << 1 : 0);
719 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
729 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
734 for (i = 0; i < q_len; i++)
735 if (++(q_ptr[i]) != 0)
740 if (tmp_roomptr != NULL)
747 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
749 Destroys the contents of a.
750 Return the allocated memory - containing the decimal digits in low-to-high
751 order, terminated with a NUL character - in case of success, NULL in case
752 of memory allocation failure. */
754 convert_to_decimal (mpn_t a, size_t extra_zeroes)
756 mp_limb_t *a_ptr = a.limbs;
757 size_t a_len = a.nlimbs;
758 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
759 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
760 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
764 for (; extra_zeroes > 0; extra_zeroes--)
768 /* Divide a by 10^9, in-place. */
769 mp_limb_t remainder = 0;
770 mp_limb_t *ptr = a_ptr + a_len;
772 for (count = a_len; count > 0; count--)
775 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
776 *ptr = num / 1000000000;
777 remainder = num % 1000000000;
779 /* Store the remainder as 9 decimal digits. */
780 for (count = 9; count > 0; count--)
782 *d_ptr++ = '0' + (remainder % 10);
783 remainder = remainder / 10;
786 if (a_ptr[a_len - 1] == 0)
789 /* Remove leading zeroes. */
790 while (d_ptr > c_ptr && d_ptr[-1] == '0')
792 /* But keep at least one zero. */
795 /* Terminate the string. */
801 # if NEED_PRINTF_LONG_DOUBLE
803 /* Assuming x is finite and >= 0:
804 write x as x = 2^e * m, where m is a bignum.
805 Return the allocated memory in case of success, NULL in case of memory
806 allocation failure. */
808 decode_long_double (long double x, int *ep, mpn_t *mp)
815 /* Allocate memory for result. */
816 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
817 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
820 /* Split into exponential part and mantissa. */
821 y = frexpl (x, &exp);
822 if (!(y >= 0.0L && y < 1.0L))
824 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
825 latter is an integer. */
826 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
827 I'm not sure whether it's safe to cast a 'long double' value between
828 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
829 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
831 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
832 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
835 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
838 if (!(y >= 0.0L && y < 1.0L))
840 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
843 if (!(y >= 0.0L && y < 1.0L))
845 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
850 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
853 if (!(y >= 0.0L && y < 1.0L))
855 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
859 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
862 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
865 if (!(y >= 0.0L && y < 1.0L))
867 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
870 if (!(y >= 0.0L && y < 1.0L))
872 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
877 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
880 *ep = exp - LDBL_MANT_BIT;
886 # if NEED_PRINTF_DOUBLE
888 /* Assuming x is finite and >= 0:
889 write x as x = 2^e * m, where m is a bignum.
890 Return the allocated memory in case of success, NULL in case of memory
891 allocation failure. */
893 decode_double (double x, int *ep, mpn_t *mp)
900 /* Allocate memory for result. */
901 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
902 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
905 /* Split into exponential part and mantissa. */
907 if (!(y >= 0.0 && y < 1.0))
909 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
910 latter is an integer. */
911 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
912 I'm not sure whether it's safe to cast a 'double' value between
913 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
914 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
916 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
917 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
920 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
923 if (!(y >= 0.0 && y < 1.0))
925 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
928 if (!(y >= 0.0 && y < 1.0))
930 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
935 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
938 if (!(y >= 0.0 && y < 1.0))
940 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
944 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
947 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
950 if (!(y >= 0.0 && y < 1.0))
952 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
955 if (!(y >= 0.0 && y < 1.0))
957 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
962 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
965 *ep = exp - DBL_MANT_BIT;
971 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
972 Returns the decimal representation of round (x * 10^n).
973 Return the allocated memory - containing the decimal digits in low-to-high
974 order, terminated with a NUL character - in case of success, NULL in case
975 of memory allocation failure. */
977 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
985 unsigned int s_limbs;
994 /* x = 2^e * m, hence
995 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
996 = round (2^s * 5^n * m). */
999 /* Factor out a common power of 10 if possible. */
1002 extra_zeroes = (s < n ? s : n);
1006 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1007 Before converting to decimal, we need to compute
1008 z = round (2^s * 5^n * m). */
1009 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1010 sign. 2.322 is slightly larger than log(5)/log(2). */
1011 abs_n = (n >= 0 ? n : -n);
1012 abs_s = (s >= 0 ? s : -s);
1013 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1014 + abs_s / GMP_LIMB_BITS + 1)
1015 * sizeof (mp_limb_t));
1016 if (pow5_ptr == NULL)
1021 /* Initialize with 1. */
1024 /* Multiply with 5^|n|. */
1027 static mp_limb_t const small_pow5[13 + 1] =
1029 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1030 48828125, 244140625, 1220703125
1033 for (n13 = 0; n13 <= abs_n; n13 += 13)
1035 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1037 mp_twolimb_t carry = 0;
1038 for (j = 0; j < pow5_len; j++)
1040 mp_limb_t digit2 = pow5_ptr[j];
1041 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1042 pow5_ptr[j] = (mp_limb_t) carry;
1043 carry = carry >> GMP_LIMB_BITS;
1046 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1049 s_limbs = abs_s / GMP_LIMB_BITS;
1050 s_bits = abs_s % GMP_LIMB_BITS;
1051 if (n >= 0 ? s >= 0 : s <= 0)
1053 /* Multiply with 2^|s|. */
1056 mp_limb_t *ptr = pow5_ptr;
1057 mp_twolimb_t accu = 0;
1059 for (count = pow5_len; count > 0; count--)
1061 accu += (mp_twolimb_t) *ptr << s_bits;
1062 *ptr++ = (mp_limb_t) accu;
1063 accu = accu >> GMP_LIMB_BITS;
1067 *ptr = (mp_limb_t) accu;
1074 for (count = pow5_len; count > 0;)
1077 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1079 for (count = s_limbs; count > 0;)
1082 pow5_ptr[count] = 0;
1084 pow5_len += s_limbs;
1086 pow5.limbs = pow5_ptr;
1087 pow5.nlimbs = pow5_len;
1090 /* Multiply m with pow5. No division needed. */
1091 z_memory = multiply (m, pow5, &z);
1095 /* Divide m by pow5 and round. */
1096 z_memory = divide (m, pow5, &z);
1101 pow5.limbs = pow5_ptr;
1102 pow5.nlimbs = pow5_len;
1106 Multiply m with pow5, then divide by 2^|s|. */
1110 tmp_memory = multiply (m, pow5, &numerator);
1111 if (tmp_memory == NULL)
1117 /* Construct 2^|s|. */
1119 mp_limb_t *ptr = pow5_ptr + pow5_len;
1121 for (i = 0; i < s_limbs; i++)
1123 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1124 denominator.limbs = ptr;
1125 denominator.nlimbs = s_limbs + 1;
1127 z_memory = divide (numerator, denominator, &z);
1133 Multiply m with 2^s, then divide by pow5. */
1136 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1137 * sizeof (mp_limb_t));
1138 if (num_ptr == NULL)
1145 mp_limb_t *destptr = num_ptr;
1148 for (i = 0; i < s_limbs; i++)
1153 const mp_limb_t *sourceptr = m.limbs;
1154 mp_twolimb_t accu = 0;
1156 for (count = m.nlimbs; count > 0; count--)
1158 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1159 *destptr++ = (mp_limb_t) accu;
1160 accu = accu >> GMP_LIMB_BITS;
1163 *destptr++ = (mp_limb_t) accu;
1167 const mp_limb_t *sourceptr = m.limbs;
1169 for (count = m.nlimbs; count > 0; count--)
1170 *destptr++ = *sourceptr++;
1172 numerator.limbs = num_ptr;
1173 numerator.nlimbs = destptr - num_ptr;
1175 z_memory = divide (numerator, pow5, &z);
1182 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1184 if (z_memory == NULL)
1186 digits = convert_to_decimal (z, extra_zeroes);
1191 # if NEED_PRINTF_LONG_DOUBLE
1193 /* Assuming x is finite and >= 0, and n is an integer:
1194 Returns the decimal representation of round (x * 10^n).
1195 Return the allocated memory - containing the decimal digits in low-to-high
1196 order, terminated with a NUL character - in case of success, NULL in case
1197 of memory allocation failure. */
1199 scale10_round_decimal_long_double (long double x, int n)
1203 void *memory = decode_long_double (x, &e, &m);
1204 return scale10_round_decimal_decoded (e, m, memory, n);
1209 # if NEED_PRINTF_DOUBLE
1211 /* Assuming x is finite and >= 0, and n is an integer:
1212 Returns the decimal representation of round (x * 10^n).
1213 Return the allocated memory - containing the decimal digits in low-to-high
1214 order, terminated with a NUL character - in case of success, NULL in case
1215 of memory allocation failure. */
1217 scale10_round_decimal_double (double x, int n)
1221 void *memory = decode_double (x, &e, &m);
1222 return scale10_round_decimal_decoded (e, m, memory, n);
1227 # if NEED_PRINTF_LONG_DOUBLE
1229 /* Assuming x is finite and > 0:
1230 Return an approximation for n with 10^n <= x < 10^(n+1).
1231 The approximation is usually the right n, but may be off by 1 sometimes. */
1233 floorlog10l (long double x)
1240 /* Split into exponential part and mantissa. */
1241 y = frexpl (x, &exp);
1242 if (!(y >= 0.0L && y < 1.0L))
1248 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1250 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1251 exp -= GMP_LIMB_BITS;
1253 if (y < (1.0L / (1 << 16)))
1255 y *= 1.0L * (1 << 16);
1258 if (y < (1.0L / (1 << 8)))
1260 y *= 1.0L * (1 << 8);
1263 if (y < (1.0L / (1 << 4)))
1265 y *= 1.0L * (1 << 4);
1268 if (y < (1.0L / (1 << 2)))
1270 y *= 1.0L * (1 << 2);
1273 if (y < (1.0L / (1 << 1)))
1275 y *= 1.0L * (1 << 1);
1279 if (!(y >= 0.5L && y < 1.0L))
1281 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1284 if (z < 0.70710678118654752444)
1286 z *= 1.4142135623730950488;
1289 if (z < 0.8408964152537145431)
1291 z *= 1.1892071150027210667;
1294 if (z < 0.91700404320467123175)
1296 z *= 1.0905077326652576592;
1299 if (z < 0.9576032806985736469)
1301 z *= 1.0442737824274138403;
1304 /* Now 0.95 <= z <= 1.01. */
1306 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1307 Four terms are enough to get an approximation with error < 10^-7. */
1308 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1309 /* Finally multiply with log(2)/log(10), yields an approximation for
1311 l *= 0.30102999566398119523;
1312 /* Round down to the next integer. */
1313 return (int) l + (l < 0 ? -1 : 0);
1318 # if NEED_PRINTF_DOUBLE
1320 /* Assuming x is finite and > 0:
1321 Return an approximation for n with 10^n <= x < 10^(n+1).
1322 The approximation is usually the right n, but may be off by 1 sometimes. */
1324 floorlog10 (double x)
1331 /* Split into exponential part and mantissa. */
1332 y = frexp (x, &exp);
1333 if (!(y >= 0.0 && y < 1.0))
1339 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1341 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1342 exp -= GMP_LIMB_BITS;
1344 if (y < (1.0 / (1 << 16)))
1346 y *= 1.0 * (1 << 16);
1349 if (y < (1.0 / (1 << 8)))
1351 y *= 1.0 * (1 << 8);
1354 if (y < (1.0 / (1 << 4)))
1356 y *= 1.0 * (1 << 4);
1359 if (y < (1.0 / (1 << 2)))
1361 y *= 1.0 * (1 << 2);
1364 if (y < (1.0 / (1 << 1)))
1366 y *= 1.0 * (1 << 1);
1370 if (!(y >= 0.5 && y < 1.0))
1372 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1375 if (z < 0.70710678118654752444)
1377 z *= 1.4142135623730950488;
1380 if (z < 0.8408964152537145431)
1382 z *= 1.1892071150027210667;
1385 if (z < 0.91700404320467123175)
1387 z *= 1.0905077326652576592;
1390 if (z < 0.9576032806985736469)
1392 z *= 1.0442737824274138403;
1395 /* Now 0.95 <= z <= 1.01. */
1397 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1398 Four terms are enough to get an approximation with error < 10^-7. */
1399 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1400 /* Finally multiply with log(2)/log(10), yields an approximation for
1402 l *= 0.30102999566398119523;
1403 /* Round down to the next integer. */
1404 return (int) l + (l < 0 ? -1 : 0);
1412 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1413 const FCHAR_T *format, va_list args)
1418 if (PRINTF_PARSE (format, &d, &a) < 0)
1419 /* errno is already set. */
1427 if (PRINTF_FETCHARGS (args, &a) < 0)
1435 size_t buf_neededlength;
1437 TCHAR_T *buf_malloced;
1441 /* Output string accumulator. */
1446 /* Allocate a small buffer that will hold a directive passed to
1447 sprintf or snprintf. */
1449 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1451 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1453 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1454 buf_malloced = NULL;
1459 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1460 if (size_overflow_p (buf_memsize))
1461 goto out_of_memory_1;
1462 buf = (TCHAR_T *) malloc (buf_memsize);
1464 goto out_of_memory_1;
1468 if (resultbuf != NULL)
1471 allocated = *lengthp;
1480 result is either == resultbuf or == NULL or malloc-allocated.
1481 If length > 0, then result != NULL. */
1483 /* Ensures that allocated >= needed. Aborts through a jump to
1484 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1485 #define ENSURE_ALLOCATION(needed) \
1486 if ((needed) > allocated) \
1488 size_t memory_size; \
1491 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1492 if ((needed) > allocated) \
1493 allocated = (needed); \
1494 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1495 if (size_overflow_p (memory_size)) \
1496 goto out_of_memory; \
1497 if (result == resultbuf || result == NULL) \
1498 memory = (DCHAR_T *) malloc (memory_size); \
1500 memory = (DCHAR_T *) realloc (result, memory_size); \
1501 if (memory == NULL) \
1502 goto out_of_memory; \
1503 if (result == resultbuf && length > 0) \
1504 DCHAR_CPY (memory, result, length); \
1508 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1510 if (cp != dp->dir_start)
1512 size_t n = dp->dir_start - cp;
1513 size_t augmented_length = xsum (length, n);
1515 ENSURE_ALLOCATION (augmented_length);
1516 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1517 need that the format string contains only ASCII characters
1518 if FCHAR_T and DCHAR_T are not the same type. */
1519 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1521 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1522 length = augmented_length;
1527 result[length++] = (unsigned char) *cp++;
1534 /* Execute a single directive. */
1535 if (dp->conversion == '%')
1537 size_t augmented_length;
1539 if (!(dp->arg_index == ARG_NONE))
1541 augmented_length = xsum (length, 1);
1542 ENSURE_ALLOCATION (augmented_length);
1543 result[length] = '%';
1544 length = augmented_length;
1548 if (!(dp->arg_index != ARG_NONE))
1551 if (dp->conversion == 'n')
1553 switch (a.arg[dp->arg_index].type)
1555 case TYPE_COUNT_SCHAR_POINTER:
1556 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1558 case TYPE_COUNT_SHORT_POINTER:
1559 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1561 case TYPE_COUNT_INT_POINTER:
1562 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1564 case TYPE_COUNT_LONGINT_POINTER:
1565 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1567 #if HAVE_LONG_LONG_INT
1568 case TYPE_COUNT_LONGLONGINT_POINTER:
1569 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1577 /* The unistdio extensions. */
1578 else if (dp->conversion == 'U')
1580 arg_type type = a.arg[dp->arg_index].type;
1581 int flags = dp->flags;
1589 if (dp->width_start != dp->width_end)
1591 if (dp->width_arg_index != ARG_NONE)
1595 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1597 arg = a.arg[dp->width_arg_index].a.a_int;
1600 /* "A negative field width is taken as a '-' flag
1601 followed by a positive field width." */
1603 width = (unsigned int) (-arg);
1610 const FCHAR_T *digitp = dp->width_start;
1613 width = xsum (xtimes (width, 10), *digitp++ - '0');
1614 while (digitp != dp->width_end);
1621 if (dp->precision_start != dp->precision_end)
1623 if (dp->precision_arg_index != ARG_NONE)
1627 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1629 arg = a.arg[dp->precision_arg_index].a.a_int;
1630 /* "A negative precision is taken as if the precision
1640 const FCHAR_T *digitp = dp->precision_start + 1;
1643 while (digitp != dp->precision_end)
1644 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1651 case TYPE_U8_STRING:
1653 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1654 const uint8_t *arg_end;
1659 /* Use only PRECISION characters, from the left. */
1662 for (; precision > 0; precision--)
1664 int count = u8_strmblen (arg_end);
1669 if (!(result == resultbuf || result == NULL))
1671 if (buf_malloced != NULL)
1672 free (buf_malloced);
1683 /* Use the entire string, and count the number of
1689 int count = u8_strmblen (arg_end);
1694 if (!(result == resultbuf || result == NULL))
1696 if (buf_malloced != NULL)
1697 free (buf_malloced);
1708 /* Use the entire string. */
1709 arg_end = arg + u8_strlen (arg);
1710 /* The number of characters doesn't matter. */
1714 if (has_width && width > characters
1715 && !(dp->flags & FLAG_LEFT))
1717 size_t n = width - characters;
1718 ENSURE_ALLOCATION (xsum (length, n));
1719 DCHAR_SET (result + length, ' ', n);
1723 # if DCHAR_IS_UINT8_T
1725 size_t n = arg_end - arg;
1726 ENSURE_ALLOCATION (xsum (length, n));
1727 DCHAR_CPY (result + length, arg, n);
1732 DCHAR_T *converted = result + length;
1733 size_t converted_len = allocated - length;
1735 /* Convert from UTF-8 to locale encoding. */
1736 if (u8_conv_to_encoding (locale_charset (),
1737 iconveh_question_mark,
1738 arg, arg_end - arg, NULL,
1739 &converted, &converted_len)
1742 /* Convert from UTF-8 to UTF-16/UTF-32. */
1744 U8_TO_DCHAR (arg, arg_end - arg,
1745 converted, &converted_len);
1746 if (converted == NULL)
1749 int saved_errno = errno;
1750 if (!(result == resultbuf || result == NULL))
1752 if (buf_malloced != NULL)
1753 free (buf_malloced);
1755 errno = saved_errno;
1758 if (converted != result + length)
1760 ENSURE_ALLOCATION (xsum (length, converted_len));
1761 DCHAR_CPY (result + length, converted, converted_len);
1764 length += converted_len;
1768 if (has_width && width > characters
1769 && (dp->flags & FLAG_LEFT))
1771 size_t n = width - characters;
1772 ENSURE_ALLOCATION (xsum (length, n));
1773 DCHAR_SET (result + length, ' ', n);
1779 case TYPE_U16_STRING:
1781 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1782 const uint16_t *arg_end;
1787 /* Use only PRECISION characters, from the left. */
1790 for (; precision > 0; precision--)
1792 int count = u16_strmblen (arg_end);
1797 if (!(result == resultbuf || result == NULL))
1799 if (buf_malloced != NULL)
1800 free (buf_malloced);
1811 /* Use the entire string, and count the number of
1817 int count = u16_strmblen (arg_end);
1822 if (!(result == resultbuf || result == NULL))
1824 if (buf_malloced != NULL)
1825 free (buf_malloced);
1836 /* Use the entire string. */
1837 arg_end = arg + u16_strlen (arg);
1838 /* The number of characters doesn't matter. */
1842 if (has_width && width > characters
1843 && !(dp->flags & FLAG_LEFT))
1845 size_t n = width - characters;
1846 ENSURE_ALLOCATION (xsum (length, n));
1847 DCHAR_SET (result + length, ' ', n);
1851 # if DCHAR_IS_UINT16_T
1853 size_t n = arg_end - arg;
1854 ENSURE_ALLOCATION (xsum (length, n));
1855 DCHAR_CPY (result + length, arg, n);
1860 DCHAR_T *converted = result + length;
1861 size_t converted_len = allocated - length;
1863 /* Convert from UTF-16 to locale encoding. */
1864 if (u16_conv_to_encoding (locale_charset (),
1865 iconveh_question_mark,
1866 arg, arg_end - arg, NULL,
1867 &converted, &converted_len)
1870 /* Convert from UTF-16 to UTF-8/UTF-32. */
1872 U16_TO_DCHAR (arg, arg_end - arg,
1873 converted, &converted_len);
1874 if (converted == NULL)
1877 int saved_errno = errno;
1878 if (!(result == resultbuf || result == NULL))
1880 if (buf_malloced != NULL)
1881 free (buf_malloced);
1883 errno = saved_errno;
1886 if (converted != result + length)
1888 ENSURE_ALLOCATION (xsum (length, converted_len));
1889 DCHAR_CPY (result + length, converted, converted_len);
1892 length += converted_len;
1896 if (has_width && width > characters
1897 && (dp->flags & FLAG_LEFT))
1899 size_t n = width - characters;
1900 ENSURE_ALLOCATION (xsum (length, n));
1901 DCHAR_SET (result + length, ' ', n);
1907 case TYPE_U32_STRING:
1909 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1910 const uint32_t *arg_end;
1915 /* Use only PRECISION characters, from the left. */
1918 for (; precision > 0; precision--)
1920 int count = u32_strmblen (arg_end);
1925 if (!(result == resultbuf || result == NULL))
1927 if (buf_malloced != NULL)
1928 free (buf_malloced);
1939 /* Use the entire string, and count the number of
1945 int count = u32_strmblen (arg_end);
1950 if (!(result == resultbuf || result == NULL))
1952 if (buf_malloced != NULL)
1953 free (buf_malloced);
1964 /* Use the entire string. */
1965 arg_end = arg + u32_strlen (arg);
1966 /* The number of characters doesn't matter. */
1970 if (has_width && width > characters
1971 && !(dp->flags & FLAG_LEFT))
1973 size_t n = width - characters;
1974 ENSURE_ALLOCATION (xsum (length, n));
1975 DCHAR_SET (result + length, ' ', n);
1979 # if DCHAR_IS_UINT32_T
1981 size_t n = arg_end - arg;
1982 ENSURE_ALLOCATION (xsum (length, n));
1983 DCHAR_CPY (result + length, arg, n);
1988 DCHAR_T *converted = result + length;
1989 size_t converted_len = allocated - length;
1991 /* Convert from UTF-32 to locale encoding. */
1992 if (u32_conv_to_encoding (locale_charset (),
1993 iconveh_question_mark,
1994 arg, arg_end - arg, NULL,
1995 &converted, &converted_len)
1998 /* Convert from UTF-32 to UTF-8/UTF-16. */
2000 U32_TO_DCHAR (arg, arg_end - arg,
2001 converted, &converted_len);
2002 if (converted == NULL)
2005 int saved_errno = errno;
2006 if (!(result == resultbuf || result == NULL))
2008 if (buf_malloced != NULL)
2009 free (buf_malloced);
2011 errno = saved_errno;
2014 if (converted != result + length)
2016 ENSURE_ALLOCATION (xsum (length, converted_len));
2017 DCHAR_CPY (result + length, converted, converted_len);
2020 length += converted_len;
2024 if (has_width && width > characters
2025 && (dp->flags & FLAG_LEFT))
2027 size_t n = width - characters;
2028 ENSURE_ALLOCATION (xsum (length, n));
2029 DCHAR_SET (result + length, ' ', n);
2040 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2041 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2042 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2044 # if NEED_PRINTF_DOUBLE
2045 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2047 # if NEED_PRINTF_LONG_DOUBLE
2048 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2054 arg_type type = a.arg[dp->arg_index].type;
2055 int flags = dp->flags;
2061 DCHAR_T tmpbuf[700];
2068 if (dp->width_start != dp->width_end)
2070 if (dp->width_arg_index != ARG_NONE)
2074 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2076 arg = a.arg[dp->width_arg_index].a.a_int;
2079 /* "A negative field width is taken as a '-' flag
2080 followed by a positive field width." */
2082 width = (unsigned int) (-arg);
2089 const FCHAR_T *digitp = dp->width_start;
2092 width = xsum (xtimes (width, 10), *digitp++ - '0');
2093 while (digitp != dp->width_end);
2100 if (dp->precision_start != dp->precision_end)
2102 if (dp->precision_arg_index != ARG_NONE)
2106 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2108 arg = a.arg[dp->precision_arg_index].a.a_int;
2109 /* "A negative precision is taken as if the precision
2119 const FCHAR_T *digitp = dp->precision_start + 1;
2122 while (digitp != dp->precision_end)
2123 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2128 /* Allocate a temporary buffer of sufficient size. */
2129 if (type == TYPE_LONGDOUBLE)
2131 (unsigned int) ((LDBL_DIG + 1)
2132 * 0.831 /* decimal -> hexadecimal */
2134 + 1; /* turn floor into ceil */
2137 (unsigned int) ((DBL_DIG + 1)
2138 * 0.831 /* decimal -> hexadecimal */
2140 + 1; /* turn floor into ceil */
2141 if (tmp_length < precision)
2142 tmp_length = precision;
2143 /* Account for sign, decimal point etc. */
2144 tmp_length = xsum (tmp_length, 12);
2146 if (tmp_length < width)
2149 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2151 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2155 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2157 if (size_overflow_p (tmp_memsize))
2158 /* Overflow, would lead to out of memory. */
2160 tmp = (DCHAR_T *) malloc (tmp_memsize);
2162 /* Out of memory. */
2168 if (type == TYPE_LONGDOUBLE)
2170 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2171 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2175 if (dp->conversion == 'A')
2177 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2181 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2187 DECL_LONG_DOUBLE_ROUNDING
2189 BEGIN_LONG_DOUBLE_ROUNDING ();
2191 if (signbit (arg)) /* arg < 0.0L or negative zero */
2199 else if (flags & FLAG_SHOWSIGN)
2201 else if (flags & FLAG_SPACE)
2204 if (arg > 0.0L && arg + arg == arg)
2206 if (dp->conversion == 'A')
2208 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2212 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2218 long double mantissa;
2221 mantissa = printf_frexpl (arg, &exponent);
2229 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2231 /* Round the mantissa. */
2232 long double tail = mantissa;
2235 for (q = precision; ; q--)
2237 int digit = (int) tail;
2241 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2250 for (q = precision; q > 0; q--)
2256 *p++ = dp->conversion - 'A' + 'X';
2261 digit = (int) mantissa;
2264 if ((flags & FLAG_ALT)
2265 || mantissa > 0.0L || precision > 0)
2267 *p++ = decimal_point_char ();
2268 /* This loop terminates because we assume
2269 that FLT_RADIX is a power of 2. */
2270 while (mantissa > 0.0L)
2273 digit = (int) mantissa;
2278 : dp->conversion - 10);
2282 while (precision > 0)
2289 *p++ = dp->conversion - 'A' + 'P';
2290 # if WIDE_CHAR_VERSION
2292 static const wchar_t decimal_format[] =
2293 { '%', '+', 'd', '\0' };
2294 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2299 if (sizeof (DCHAR_T) == 1)
2301 sprintf ((char *) p, "%+d", exponent);
2309 sprintf (expbuf, "%+d", exponent);
2310 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2316 END_LONG_DOUBLE_ROUNDING ();
2324 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2325 double arg = a.arg[dp->arg_index].a.a_double;
2329 if (dp->conversion == 'A')
2331 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2335 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2342 if (signbit (arg)) /* arg < 0.0 or negative zero */
2350 else if (flags & FLAG_SHOWSIGN)
2352 else if (flags & FLAG_SPACE)
2355 if (arg > 0.0 && arg + arg == arg)
2357 if (dp->conversion == 'A')
2359 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2363 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2372 mantissa = printf_frexp (arg, &exponent);
2380 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2382 /* Round the mantissa. */
2383 double tail = mantissa;
2386 for (q = precision; ; q--)
2388 int digit = (int) tail;
2392 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2401 for (q = precision; q > 0; q--)
2407 *p++ = dp->conversion - 'A' + 'X';
2412 digit = (int) mantissa;
2415 if ((flags & FLAG_ALT)
2416 || mantissa > 0.0 || precision > 0)
2418 *p++ = decimal_point_char ();
2419 /* This loop terminates because we assume
2420 that FLT_RADIX is a power of 2. */
2421 while (mantissa > 0.0)
2424 digit = (int) mantissa;
2429 : dp->conversion - 10);
2433 while (precision > 0)
2440 *p++ = dp->conversion - 'A' + 'P';
2441 # if WIDE_CHAR_VERSION
2443 static const wchar_t decimal_format[] =
2444 { '%', '+', 'd', '\0' };
2445 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2450 if (sizeof (DCHAR_T) == 1)
2452 sprintf ((char *) p, "%+d", exponent);
2460 sprintf (expbuf, "%+d", exponent);
2461 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2471 /* The generated string now extends from tmp to p, with the
2472 zero padding insertion point being at pad_ptr. */
2473 if (has_width && p - tmp < width)
2475 size_t pad = width - (p - tmp);
2476 DCHAR_T *end = p + pad;
2478 if (flags & FLAG_LEFT)
2480 /* Pad with spaces on the right. */
2481 for (; pad > 0; pad--)
2484 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2486 /* Pad with zeroes. */
2491 for (; pad > 0; pad--)
2496 /* Pad with spaces on the left. */
2501 for (; pad > 0; pad--)
2509 size_t count = p - tmp;
2511 if (count >= tmp_length)
2512 /* tmp_length was incorrectly calculated - fix the
2516 /* Make room for the result. */
2517 if (count >= allocated - length)
2519 size_t n = xsum (length, count);
2521 ENSURE_ALLOCATION (n);
2524 /* Append the result. */
2525 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2532 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2533 else if ((dp->conversion == 'f' || dp->conversion == 'F'
2534 || dp->conversion == 'e' || dp->conversion == 'E'
2535 || dp->conversion == 'g' || dp->conversion == 'G'
2536 || dp->conversion == 'a' || dp->conversion == 'A')
2538 # if NEED_PRINTF_DOUBLE
2539 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2540 # elif NEED_PRINTF_INFINITE_DOUBLE
2541 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2542 /* The systems (mingw) which produce wrong output
2543 for Inf, -Inf, and NaN also do so for -0.0.
2544 Therefore we treat this case here as well. */
2545 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2547 # if NEED_PRINTF_LONG_DOUBLE
2548 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2549 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2550 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2551 /* Some systems produce wrong output for Inf,
2553 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
2557 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2558 arg_type type = a.arg[dp->arg_index].type;
2560 int flags = dp->flags;
2566 DCHAR_T tmpbuf[700];
2573 if (dp->width_start != dp->width_end)
2575 if (dp->width_arg_index != ARG_NONE)
2579 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2581 arg = a.arg[dp->width_arg_index].a.a_int;
2584 /* "A negative field width is taken as a '-' flag
2585 followed by a positive field width." */
2587 width = (unsigned int) (-arg);
2594 const FCHAR_T *digitp = dp->width_start;
2597 width = xsum (xtimes (width, 10), *digitp++ - '0');
2598 while (digitp != dp->width_end);
2605 if (dp->precision_start != dp->precision_end)
2607 if (dp->precision_arg_index != ARG_NONE)
2611 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2613 arg = a.arg[dp->precision_arg_index].a.a_int;
2614 /* "A negative precision is taken as if the precision
2624 const FCHAR_T *digitp = dp->precision_start + 1;
2627 while (digitp != dp->precision_end)
2628 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2633 /* POSIX specifies the default precision to be 6 for %f, %F,
2634 %e, %E, but not for %g, %G. Implementations appear to use
2635 the same default precision also for %g, %G. */
2639 /* Allocate a temporary buffer of sufficient size. */
2640 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2641 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
2642 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2643 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2644 # elif NEED_PRINTF_LONG_DOUBLE
2645 tmp_length = LDBL_DIG + 1;
2646 # elif NEED_PRINTF_DOUBLE
2647 tmp_length = DBL_DIG + 1;
2651 if (tmp_length < precision)
2652 tmp_length = precision;
2653 # if NEED_PRINTF_LONG_DOUBLE
2654 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2655 if (type == TYPE_LONGDOUBLE)
2657 if (dp->conversion == 'f' || dp->conversion == 'F')
2659 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2660 if (!(isnanl (arg) || arg + arg == arg))
2662 /* arg is finite and nonzero. */
2663 int exponent = floorlog10l (arg < 0 ? -arg : arg);
2664 if (exponent >= 0 && tmp_length < exponent + precision)
2665 tmp_length = exponent + precision;
2669 # if NEED_PRINTF_DOUBLE
2670 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2671 if (type == TYPE_DOUBLE)
2673 if (dp->conversion == 'f' || dp->conversion == 'F')
2675 double arg = a.arg[dp->arg_index].a.a_double;
2676 if (!(isnan (arg) || arg + arg == arg))
2678 /* arg is finite and nonzero. */
2679 int exponent = floorlog10 (arg < 0 ? -arg : arg);
2680 if (exponent >= 0 && tmp_length < exponent + precision)
2681 tmp_length = exponent + precision;
2685 /* Account for sign, decimal point etc. */
2686 tmp_length = xsum (tmp_length, 12);
2688 if (tmp_length < width)
2691 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2693 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2697 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2699 if (size_overflow_p (tmp_memsize))
2700 /* Overflow, would lead to out of memory. */
2702 tmp = (DCHAR_T *) malloc (tmp_memsize);
2704 /* Out of memory. */
2711 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2712 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2713 if (type == TYPE_LONGDOUBLE)
2716 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2720 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2722 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2726 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2732 DECL_LONG_DOUBLE_ROUNDING
2734 BEGIN_LONG_DOUBLE_ROUNDING ();
2736 if (signbit (arg)) /* arg < 0.0L or negative zero */
2744 else if (flags & FLAG_SHOWSIGN)
2746 else if (flags & FLAG_SPACE)
2749 if (arg > 0.0L && arg + arg == arg)
2751 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2753 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2757 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2762 # if NEED_PRINTF_LONG_DOUBLE
2765 if (dp->conversion == 'f' || dp->conversion == 'F')
2771 scale10_round_decimal_long_double (arg, precision);
2774 END_LONG_DOUBLE_ROUNDING ();
2777 ndigits = strlen (digits);
2779 if (ndigits > precision)
2783 *p++ = digits[ndigits];
2785 while (ndigits > precision);
2788 /* Here ndigits <= precision. */
2789 if ((flags & FLAG_ALT) || precision > 0)
2791 *p++ = decimal_point_char ();
2792 for (; precision > ndigits; precision--)
2797 *p++ = digits[ndigits];
2803 else if (dp->conversion == 'e' || dp->conversion == 'E')
2811 if ((flags & FLAG_ALT) || precision > 0)
2813 *p++ = decimal_point_char ();
2814 for (; precision > 0; precision--)
2825 exponent = floorlog10l (arg);
2830 scale10_round_decimal_long_double (arg,
2831 (int)precision - exponent);
2834 END_LONG_DOUBLE_ROUNDING ();
2837 ndigits = strlen (digits);
2839 if (ndigits == precision + 1)
2841 if (ndigits < precision
2842 || ndigits > precision + 2)
2843 /* The exponent was not guessed
2844 precisely enough. */
2847 /* None of two values of exponent is
2848 the right one. Prevent an endless
2852 if (ndigits == precision)
2859 /* Here ndigits = precision+1. */
2860 *p++ = digits[--ndigits];
2861 if ((flags & FLAG_ALT) || precision > 0)
2863 *p++ = decimal_point_char ();
2867 *p++ = digits[ndigits];
2874 *p++ = dp->conversion; /* 'e' or 'E' */
2875 # if WIDE_CHAR_VERSION
2877 static const wchar_t decimal_format[] =
2878 { '%', '+', '.', '2', 'd', '\0' };
2879 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2884 if (sizeof (DCHAR_T) == 1)
2886 sprintf ((char *) p, "%+.2d", exponent);
2894 sprintf (expbuf, "%+.2d", exponent);
2895 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2900 else if (dp->conversion == 'g' || dp->conversion == 'G')
2904 /* precision >= 1. */
2907 /* The exponent is 0, >= -4, < precision.
2908 Use fixed-point notation. */
2910 size_t ndigits = precision;
2911 /* Number of trailing zeroes that have to be
2914 (flags & FLAG_ALT ? 0 : precision - 1);
2918 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2920 *p++ = decimal_point_char ();
2921 while (ndigits > nzeroes)
2937 exponent = floorlog10l (arg);
2942 scale10_round_decimal_long_double (arg,
2943 (int)(precision - 1) - exponent);
2946 END_LONG_DOUBLE_ROUNDING ();
2949 ndigits = strlen (digits);
2951 if (ndigits == precision)
2953 if (ndigits < precision - 1
2954 || ndigits > precision + 1)
2955 /* The exponent was not guessed
2956 precisely enough. */
2959 /* None of two values of exponent is
2960 the right one. Prevent an endless
2964 if (ndigits < precision)
2970 /* Here ndigits = precision. */
2972 /* Determine the number of trailing zeroes
2973 that have to be dropped. */
2975 if ((flags & FLAG_ALT) == 0)
2976 while (nzeroes < ndigits
2977 && digits[nzeroes] == '0')
2980 /* The exponent is now determined. */
2982 && exponent < (long)precision)
2984 /* Fixed-point notation:
2985 max(exponent,0)+1 digits, then the
2986 decimal point, then the remaining
2987 digits without trailing zeroes. */
2990 size_t count = exponent + 1;
2991 /* Note: count <= precision = ndigits. */
2992 for (; count > 0; count--)
2993 *p++ = digits[--ndigits];
2994 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2996 *p++ = decimal_point_char ();
2997 while (ndigits > nzeroes)
3000 *p++ = digits[ndigits];
3006 size_t count = -exponent - 1;
3008 *p++ = decimal_point_char ();
3009 for (; count > 0; count--)
3011 while (ndigits > nzeroes)
3014 *p++ = digits[ndigits];
3020 /* Exponential notation. */
3021 *p++ = digits[--ndigits];
3022 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3024 *p++ = decimal_point_char ();
3025 while (ndigits > nzeroes)
3028 *p++ = digits[ndigits];
3031 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3032 # if WIDE_CHAR_VERSION
3034 static const wchar_t decimal_format[] =
3035 { '%', '+', '.', '2', 'd', '\0' };
3036 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3041 if (sizeof (DCHAR_T) == 1)
3043 sprintf ((char *) p, "%+.2d", exponent);
3051 sprintf (expbuf, "%+.2d", exponent);
3052 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3064 /* arg is finite. */
3069 END_LONG_DOUBLE_ROUNDING ();
3072 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3076 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3078 double arg = a.arg[dp->arg_index].a.a_double;
3082 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3084 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3088 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3095 if (signbit (arg)) /* arg < 0.0 or negative zero */
3103 else if (flags & FLAG_SHOWSIGN)
3105 else if (flags & FLAG_SPACE)
3108 if (arg > 0.0 && arg + arg == arg)
3110 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3112 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3116 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3121 # if NEED_PRINTF_DOUBLE
3124 if (dp->conversion == 'f' || dp->conversion == 'F')
3130 scale10_round_decimal_double (arg, precision);
3133 ndigits = strlen (digits);
3135 if (ndigits > precision)
3139 *p++ = digits[ndigits];
3141 while (ndigits > precision);
3144 /* Here ndigits <= precision. */
3145 if ((flags & FLAG_ALT) || precision > 0)
3147 *p++ = decimal_point_char ();
3148 for (; precision > ndigits; precision--)
3153 *p++ = digits[ndigits];
3159 else if (dp->conversion == 'e' || dp->conversion == 'E')
3167 if ((flags & FLAG_ALT) || precision > 0)
3169 *p++ = decimal_point_char ();
3170 for (; precision > 0; precision--)
3181 exponent = floorlog10 (arg);
3186 scale10_round_decimal_double (arg,
3187 (int)precision - exponent);
3190 ndigits = strlen (digits);
3192 if (ndigits == precision + 1)
3194 if (ndigits < precision
3195 || ndigits > precision + 2)
3196 /* The exponent was not guessed
3197 precisely enough. */
3200 /* None of two values of exponent is
3201 the right one. Prevent an endless
3205 if (ndigits == precision)
3212 /* Here ndigits = precision+1. */
3213 *p++ = digits[--ndigits];
3214 if ((flags & FLAG_ALT) || precision > 0)
3216 *p++ = decimal_point_char ();
3220 *p++ = digits[ndigits];
3227 *p++ = dp->conversion; /* 'e' or 'E' */
3228 # if WIDE_CHAR_VERSION
3230 static const wchar_t decimal_format[] =
3231 /* Produce the same number of exponent digits
3232 as the native printf implementation. */
3233 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3234 { '%', '+', '.', '3', 'd', '\0' };
3236 { '%', '+', '.', '2', 'd', '\0' };
3238 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3244 static const char decimal_format[] =
3245 /* Produce the same number of exponent digits
3246 as the native printf implementation. */
3247 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3252 if (sizeof (DCHAR_T) == 1)
3254 sprintf ((char *) p, decimal_format, exponent);
3262 sprintf (expbuf, decimal_format, exponent);
3263 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3269 else if (dp->conversion == 'g' || dp->conversion == 'G')
3273 /* precision >= 1. */
3276 /* The exponent is 0, >= -4, < precision.
3277 Use fixed-point notation. */
3279 size_t ndigits = precision;
3280 /* Number of trailing zeroes that have to be
3283 (flags & FLAG_ALT ? 0 : precision - 1);
3287 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3289 *p++ = decimal_point_char ();
3290 while (ndigits > nzeroes)
3306 exponent = floorlog10 (arg);
3311 scale10_round_decimal_double (arg,
3312 (int)(precision - 1) - exponent);
3315 ndigits = strlen (digits);
3317 if (ndigits == precision)
3319 if (ndigits < precision - 1
3320 || ndigits > precision + 1)
3321 /* The exponent was not guessed
3322 precisely enough. */
3325 /* None of two values of exponent is
3326 the right one. Prevent an endless
3330 if (ndigits < precision)
3336 /* Here ndigits = precision. */
3338 /* Determine the number of trailing zeroes
3339 that have to be dropped. */
3341 if ((flags & FLAG_ALT) == 0)
3342 while (nzeroes < ndigits
3343 && digits[nzeroes] == '0')
3346 /* The exponent is now determined. */
3348 && exponent < (long)precision)
3350 /* Fixed-point notation:
3351 max(exponent,0)+1 digits, then the
3352 decimal point, then the remaining
3353 digits without trailing zeroes. */
3356 size_t count = exponent + 1;
3357 /* Note: count <= precision = ndigits. */
3358 for (; count > 0; count--)
3359 *p++ = digits[--ndigits];
3360 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3362 *p++ = decimal_point_char ();
3363 while (ndigits > nzeroes)
3366 *p++ = digits[ndigits];
3372 size_t count = -exponent - 1;
3374 *p++ = decimal_point_char ();
3375 for (; count > 0; count--)
3377 while (ndigits > nzeroes)
3380 *p++ = digits[ndigits];
3386 /* Exponential notation. */
3387 *p++ = digits[--ndigits];
3388 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3390 *p++ = decimal_point_char ();
3391 while (ndigits > nzeroes)
3394 *p++ = digits[ndigits];
3397 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3398 # if WIDE_CHAR_VERSION
3400 static const wchar_t decimal_format[] =
3401 /* Produce the same number of exponent digits
3402 as the native printf implementation. */
3403 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3404 { '%', '+', '.', '3', 'd', '\0' };
3406 { '%', '+', '.', '2', 'd', '\0' };
3408 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3414 static const char decimal_format[] =
3415 /* Produce the same number of exponent digits
3416 as the native printf implementation. */
3417 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3422 if (sizeof (DCHAR_T) == 1)
3424 sprintf ((char *) p, decimal_format, exponent);
3432 sprintf (expbuf, decimal_format, exponent);
3433 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3446 /* arg is finite. */
3452 if (dp->conversion == 'f' || dp->conversion == 'F')
3455 if ((flags & FLAG_ALT) || precision > 0)
3457 *p++ = decimal_point_char ();
3458 for (; precision > 0; precision--)
3462 else if (dp->conversion == 'e' || dp->conversion == 'E')
3465 if ((flags & FLAG_ALT) || precision > 0)
3467 *p++ = decimal_point_char ();
3468 for (; precision > 0; precision--)
3471 *p++ = dp->conversion; /* 'e' or 'E' */
3473 /* Produce the same number of exponent digits as
3474 the native printf implementation. */
3475 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3481 else if (dp->conversion == 'g' || dp->conversion == 'G')
3484 if (flags & FLAG_ALT)
3487 (precision > 0 ? precision - 1 : 0);
3488 *p++ = decimal_point_char ();
3489 for (; ndigits > 0; --ndigits)
3501 /* The generated string now extends from tmp to p, with the
3502 zero padding insertion point being at pad_ptr. */
3503 if (has_width && p - tmp < width)
3505 size_t pad = width - (p - tmp);
3506 DCHAR_T *end = p + pad;
3508 if (flags & FLAG_LEFT)
3510 /* Pad with spaces on the right. */
3511 for (; pad > 0; pad--)
3514 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3516 /* Pad with zeroes. */
3521 for (; pad > 0; pad--)
3526 /* Pad with spaces on the left. */
3531 for (; pad > 0; pad--)
3539 size_t count = p - tmp;
3541 if (count >= tmp_length)
3542 /* tmp_length was incorrectly calculated - fix the
3546 /* Make room for the result. */
3547 if (count >= allocated - length)
3549 size_t n = xsum (length, count);
3551 ENSURE_ALLOCATION (n);
3554 /* Append the result. */
3555 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3564 arg_type type = a.arg[dp->arg_index].type;
3565 int flags = dp->flags;
3566 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3570 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3574 #if NEED_PRINTF_UNBOUNDED_PRECISION
3577 # define prec_ourselves 0
3579 #if !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_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 !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))
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. */
4027 /* Construct the arguments for calling snprintf or sprintf. */
4029 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4031 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4033 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4035 if (dp->precision_arg_index != ARG_NONE)
4037 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4039 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4043 /* The SNPRINTF result is appended after result[0..length].
4044 The latter is an array of DCHAR_T; SNPRINTF appends an
4045 array of TCHAR_T to it. This is possible because
4046 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4047 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4048 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4049 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4050 where an snprintf() with maxlen==1 acts like sprintf(). */
4051 ENSURE_ALLOCATION (xsum (length,
4052 (2 + TCHARS_PER_DCHAR - 1)
4053 / TCHARS_PER_DCHAR));
4054 /* Prepare checking whether snprintf returns the count
4056 *(TCHAR_T *) (result + length) = '\0';
4065 size_t maxlen = allocated - length;
4066 /* SNPRINTF can fail if its second argument is
4068 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4069 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4070 maxlen = maxlen * TCHARS_PER_DCHAR;
4071 # define SNPRINTF_BUF(arg) \
4072 switch (prefix_count) \
4075 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4080 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4082 prefixes[0], arg, &count); \
4085 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4087 prefixes[0], prefixes[1], arg, \
4094 # define SNPRINTF_BUF(arg) \
4095 switch (prefix_count) \
4098 count = sprintf (tmp, buf, arg); \
4101 count = sprintf (tmp, buf, prefixes[0], arg); \
4104 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4116 int arg = a.arg[dp->arg_index].a.a_schar;
4122 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4128 int arg = a.arg[dp->arg_index].a.a_short;
4134 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4140 int arg = a.arg[dp->arg_index].a.a_int;
4146 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4152 long int arg = a.arg[dp->arg_index].a.a_longint;
4158 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4162 #if HAVE_LONG_LONG_INT
4163 case TYPE_LONGLONGINT:
4165 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4169 case TYPE_ULONGLONGINT:
4171 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4178 double arg = a.arg[dp->arg_index].a.a_double;
4182 case TYPE_LONGDOUBLE:
4184 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4190 int arg = a.arg[dp->arg_index].a.a_char;
4195 case TYPE_WIDE_CHAR:
4197 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
4204 const char *arg = a.arg[dp->arg_index].a.a_string;
4209 case TYPE_WIDE_STRING:
4211 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
4218 void *arg = a.arg[dp->arg_index].a.a_pointer;
4227 /* Portability: Not all implementations of snprintf()
4228 are ISO C 99 compliant. Determine the number of
4229 bytes that snprintf() has produced or would have
4233 /* Verify that snprintf() has NUL-terminated its
4236 && ((TCHAR_T *) (result + length)) [count] != '\0')
4238 /* Portability hack. */
4239 if (retcount > count)
4244 /* snprintf() doesn't understand the '%n'
4248 /* Don't use the '%n' directive; instead, look
4249 at the snprintf() return value. */
4255 /* Look at the snprintf() return value. */
4258 /* HP-UX 10.20 snprintf() is doubly deficient:
4259 It doesn't understand the '%n' directive,
4260 *and* it returns -1 (rather than the length
4261 that would have been required) when the
4262 buffer is too small. */
4263 size_t bigger_need =
4264 xsum (xtimes (allocated, 2), 12);
4265 ENSURE_ALLOCATION (bigger_need);
4274 /* Attempt to handle failure. */
4277 if (!(result == resultbuf || result == NULL))
4279 if (buf_malloced != NULL)
4280 free (buf_malloced);
4287 /* Handle overflow of the allocated buffer.
4288 If such an overflow occurs, a C99 compliant snprintf()
4289 returns a count >= maxlen. However, a non-compliant
4290 snprintf() function returns only count = maxlen - 1. To
4291 cover both cases, test whether count >= maxlen - 1. */
4292 if ((unsigned int) count + 1 >= maxlen)
4294 /* If maxlen already has attained its allowed maximum,
4295 allocating more memory will not increase maxlen.
4296 Instead of looping, bail out. */
4297 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
4301 /* Need at least (count + 1) * sizeof (TCHAR_T)
4302 bytes. (The +1 is for the trailing NUL.)
4303 But ask for (count + 2) * sizeof (TCHAR_T)
4304 bytes, so that in the next round, we likely get
4305 maxlen > (unsigned int) count + 1
4306 and so we don't get here again.
4307 And allocate proportionally, to avoid looping
4308 eternally if snprintf() reports a too small
4312 ((unsigned int) count + 2
4313 + TCHARS_PER_DCHAR - 1)
4314 / TCHARS_PER_DCHAR),
4315 xtimes (allocated, 2));
4317 ENSURE_ALLOCATION (n);
4323 #if NEED_PRINTF_UNBOUNDED_PRECISION
4326 /* Handle the precision. */
4329 (TCHAR_T *) (result + length);
4333 size_t prefix_count;
4337 /* Put the additional zeroes after the sign. */
4339 && (*prec_ptr == '-' || *prec_ptr == '+'
4340 || *prec_ptr == ' '))
4342 /* Put the additional zeroes after the 0x prefix if
4343 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
4345 && prec_ptr[0] == '0'
4346 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
4349 move = count - prefix_count;
4350 if (precision > move)
4352 /* Insert zeroes. */
4353 size_t insert = precision - move;
4359 (count + insert + TCHARS_PER_DCHAR - 1)
4360 / TCHARS_PER_DCHAR);
4361 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4362 ENSURE_ALLOCATION (n);
4363 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4364 prec_ptr = (TCHAR_T *) (result + length);
4367 prec_end = prec_ptr + count;
4368 prec_ptr += prefix_count;
4370 while (prec_end > prec_ptr)
4373 prec_end[insert] = prec_end[0];
4379 while (prec_end > prec_ptr);
4388 if (count >= tmp_length)
4389 /* tmp_length was incorrectly calculated - fix the
4394 /* Convert from TCHAR_T[] to DCHAR_T[]. */
4395 if (dp->conversion == 'c' || dp->conversion == 's')
4397 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
4399 The result string is not certainly ASCII. */
4400 const TCHAR_T *tmpsrc;
4403 /* This code assumes that TCHAR_T is 'char'. */
4404 typedef int TCHAR_T_verify
4405 [2 * (sizeof (TCHAR_T) == 1) - 1];
4407 tmpsrc = (TCHAR_T *) (result + length);
4413 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
4414 iconveh_question_mark,
4417 &tmpdst, &tmpdst_len)
4420 int saved_errno = errno;
4421 if (!(result == resultbuf || result == NULL))
4423 if (buf_malloced != NULL)
4424 free (buf_malloced);
4426 errno = saved_errno;
4429 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
4430 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
4436 /* The result string is ASCII.
4437 Simple 1:1 conversion. */
4439 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
4440 no-op conversion, in-place on the array starting
4441 at (result + length). */
4442 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
4445 const TCHAR_T *tmpsrc;
4450 if (result == resultbuf)
4452 tmpsrc = (TCHAR_T *) (result + length);
4453 /* ENSURE_ALLOCATION will not move tmpsrc
4454 (because it's part of resultbuf). */
4455 ENSURE_ALLOCATION (xsum (length, count));
4459 /* ENSURE_ALLOCATION will move the array
4460 (because it uses realloc(). */
4461 ENSURE_ALLOCATION (xsum (length, count));
4462 tmpsrc = (TCHAR_T *) (result + length);
4466 ENSURE_ALLOCATION (xsum (length, count));
4468 tmpdst = result + length;
4469 /* Copy backwards, because of overlapping. */
4472 for (n = count; n > 0; n--)
4473 *--tmpdst = (unsigned char) *--tmpsrc;
4478 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4479 /* Make room for the result. */
4480 if (count > allocated - length)
4482 /* Need at least count elements. But allocate
4485 xmax (xsum (length, count), xtimes (allocated, 2));
4487 ENSURE_ALLOCATION (n);
4491 /* Here count <= allocated - length. */
4493 /* Perform padding. */
4494 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4495 if (pad_ourselves && has_width)
4498 # if ENABLE_UNISTDIO
4499 /* Outside POSIX, it's preferrable to compare the width
4500 against the number of _characters_ of the converted
4502 w = DCHAR_MBSNLEN (result + length, count);
4504 /* The width is compared against the number of _bytes_
4505 of the converted value, says POSIX. */
4510 size_t pad = width - w;
4512 /* Make room for the result. */
4513 if (xsum (count, pad) > allocated - length)
4515 /* Need at least count + pad elements. But
4516 allocate proportionally. */
4518 xmax (xsum3 (length, count, pad),
4519 xtimes (allocated, 2));
4522 ENSURE_ALLOCATION (n);
4525 /* Here count + pad <= allocated - length. */
4528 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
4529 DCHAR_T * const rp = result + length;
4531 DCHAR_T * const rp = tmp;
4533 DCHAR_T *p = rp + count;
4534 DCHAR_T *end = p + pad;
4535 # if NEED_PRINTF_FLAG_ZERO
4537 # if !DCHAR_IS_TCHAR
4538 if (dp->conversion == 'c'
4539 || dp->conversion == 's')
4540 /* No zero-padding for string directives. */
4545 pad_ptr = (*rp == '-' ? rp + 1 : rp);
4546 /* No zero-padding of "inf" and "nan". */
4547 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
4548 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
4552 /* The generated string now extends from rp to p,
4553 with the zero padding insertion point being at
4556 count = count + pad; /* = end - rp */
4558 if (flags & FLAG_LEFT)
4560 /* Pad with spaces on the right. */
4561 for (; pad > 0; pad--)
4564 # if NEED_PRINTF_FLAG_ZERO
4565 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4567 /* Pad with zeroes. */
4572 for (; pad > 0; pad--)
4578 /* Pad with spaces on the left. */
4583 for (; pad > 0; pad--)
4591 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4592 if (count >= tmp_length)
4593 /* tmp_length was incorrectly calculated - fix the
4598 /* Here still count <= allocated - length. */
4600 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
4601 /* The snprintf() result did fit. */
4603 /* Append the sprintf() result. */
4604 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4611 #if NEED_PRINTF_DIRECTIVE_F
4612 if (dp->conversion == 'F')
4614 /* Convert the %f result to upper case for %F. */
4615 DCHAR_T *rp = result + length;
4617 for (rc = count; rc > 0; rc--, rp++)
4618 if (*rp >= 'a' && *rp <= 'z')
4619 *rp = *rp - 'a' + 'A';
4630 /* Add the final NUL. */
4631 ENSURE_ALLOCATION (xsum (length, 1));
4632 result[length] = '\0';
4634 if (result != resultbuf && length + 1 < allocated)
4636 /* Shrink the allocated memory if possible. */
4639 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
4644 if (buf_malloced != NULL)
4645 free (buf_malloced);
4648 /* Note that we can produce a big string of a length > INT_MAX. POSIX
4649 says that snprintf() fails with errno = EOVERFLOW in this case, but
4650 that's only because snprintf() returns an 'int'. This function does
4651 not have this limitation. */
4655 if (!(result == resultbuf || result == NULL))
4657 if (buf_malloced != NULL)
4658 free (buf_malloced);
4664 if (!(result == resultbuf || result == NULL))
4666 if (buf_malloced != NULL)
4667 free (buf_malloced);
4675 #undef TCHARS_PER_DCHAR
4682 #undef DCHAR_IS_TCHAR