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 && !defined IN_LIBINTL
110 # include "printf-frexp.h"
111 # include "isnanl-nolibm.h"
112 # include "printf-frexpl.h"
116 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
118 # define EOVERFLOW E2BIG
123 # define local_wcslen wcslen
125 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
126 a dependency towards this library, here is a local substitute.
127 Define this substitute only once, even if this file is included
128 twice in the same compilation unit. */
129 # ifndef local_wcslen_defined
130 # define local_wcslen_defined 1
132 local_wcslen (const wchar_t *s)
136 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
144 /* Default parameters. */
146 # if WIDE_CHAR_VERSION
147 # define VASNPRINTF vasnwprintf
148 # define FCHAR_T wchar_t
149 # define DCHAR_T wchar_t
150 # define TCHAR_T wchar_t
151 # define DCHAR_IS_TCHAR 1
152 # define DIRECTIVE wchar_t_directive
153 # define DIRECTIVES wchar_t_directives
154 # define PRINTF_PARSE wprintf_parse
155 # define DCHAR_CPY wmemcpy
157 # define VASNPRINTF vasnprintf
158 # define FCHAR_T char
159 # define DCHAR_T char
160 # define TCHAR_T char
161 # define DCHAR_IS_TCHAR 1
162 # define DIRECTIVE char_directive
163 # define DIRECTIVES char_directives
164 # define PRINTF_PARSE printf_parse
165 # define DCHAR_CPY memcpy
168 #if WIDE_CHAR_VERSION
169 /* TCHAR_T is wchar_t. */
170 # define USE_SNPRINTF 1
171 # if HAVE_DECL__SNWPRINTF
172 /* On Windows, the function swprintf() has a different signature than
173 on Unix; we use the _snwprintf() function instead. */
174 # define SNPRINTF _snwprintf
177 # define SNPRINTF swprintf
180 /* TCHAR_T is char. */
181 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
182 But don't use it on BeOS, since BeOS snprintf produces no output if the
183 size argument is >= 0x3000000. */
184 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
185 # define USE_SNPRINTF 1
187 # define USE_SNPRINTF 0
189 # if HAVE_DECL__SNPRINTF
191 # define SNPRINTF _snprintf
194 # define SNPRINTF snprintf
195 /* Here we need to call the native snprintf, not rpl_snprintf. */
199 /* Here we need to call the native sprintf, not rpl_sprintf. */
202 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
203 /* Determine the decimal-point character according to the current locale. */
204 # ifndef decimal_point_char_defined
205 # define decimal_point_char_defined 1
207 decimal_point_char ()
210 /* Determine it in a multithread-safe way. We know nl_langinfo is
211 multithread-safe on glibc systems, but is not required to be multithread-
212 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
213 is rarely multithread-safe. */
214 # if HAVE_NL_LANGINFO && __GLIBC__
215 point = nl_langinfo (RADIXCHAR);
218 sprintf (pointbuf, "%#.0f", 1.0);
219 point = &pointbuf[1];
221 point = localeconv () -> decimal_point;
223 /* The decimal point is always a single byte: either '.' or ','. */
224 return (point[0] != '\0' ? point[0] : '.');
229 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
231 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
233 is_infinite_or_zero (double x)
235 return isnan (x) || x + x == x;
240 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
242 /* Equivalent to !isfinite(x), but does not require libm. */
244 is_infinitel (long double x)
246 return isnanl (x) || (x + x == x && x != 0.0L);
251 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
253 /* Converting 'long double' to decimal without rare rounding bugs requires
254 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
255 (and slower) algorithms. */
257 typedef unsigned int mp_limb_t;
258 # define GMP_LIMB_BITS 32
259 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
261 typedef unsigned long long mp_twolimb_t;
262 # define GMP_TWOLIMB_BITS 64
263 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
265 /* Representation of a bignum >= 0. */
269 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
272 /* Compute the product of two bignums >= 0.
273 Return the allocated memory in case of success, NULL in case of memory
274 allocation failure. */
276 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
283 if (src1.nlimbs <= src2.nlimbs)
297 /* Now 0 <= len1 <= len2. */
300 /* src1 or src2 is zero. */
302 dest->limbs = (mp_limb_t *) malloc (1);
306 /* Here 1 <= len1 <= len2. */
312 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
315 for (k = len2; k > 0; )
317 for (i = 0; i < len1; i++)
319 mp_limb_t digit1 = p1[i];
320 mp_twolimb_t carry = 0;
321 for (j = 0; j < len2; j++)
323 mp_limb_t digit2 = p2[j];
324 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
326 dp[i + j] = (mp_limb_t) carry;
327 carry = carry >> GMP_LIMB_BITS;
329 dp[i + len2] = (mp_limb_t) carry;
332 while (dlen > 0 && dp[dlen - 1] == 0)
340 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
341 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
343 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
345 Return the allocated memory in case of success, NULL in case of memory
346 allocation failure. */
348 divide (mpn_t a, mpn_t b, mpn_t *q)
351 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
352 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
353 If m<n, then q:=0 and r:=a.
354 If m>=n=1, perform a single-precision division:
357 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
358 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
359 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
360 Normalise [q[m-1],...,q[0]], yields q.
361 If m>=n>1, perform a multiple-precision division:
362 We have a/b < beta^(m-n+1).
363 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
364 Shift a and b left by s bits, copying them. r:=a.
365 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
366 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
368 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
369 In case of overflow (q* >= beta) set q* := beta-1.
370 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
371 and c3 := b[n-2] * q*.
372 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
373 occurred. Furthermore 0 <= c3 < beta^2.
374 If there was overflow and
375 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
376 the next test can be skipped.}
377 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
378 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
380 Put r := r - b * q* * beta^j. In detail:
381 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
382 hence: u:=0, for i:=0 to n-1 do
384 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
385 u:=u div beta (+ 1, if carry in subtraction)
387 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
389 the carry u does not overflow.}
390 If a negative carry occurs, put q* := q* - 1
391 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
393 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
394 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
396 The room for q[j] can be allocated at the memory location of r[n+j].
397 Finally, round-to-even:
398 Shift r left by 1 bit.
399 If r > b or if r = b and q[0] is odd, q := q+1.
401 const mp_limb_t *a_ptr = a.limbs;
402 size_t a_len = a.nlimbs;
403 const mp_limb_t *b_ptr = b.limbs;
404 size_t b_len = b.nlimbs;
406 mp_limb_t *tmp_roomptr = NULL;
412 /* Allocate room for a_len+2 digits.
413 (Need a_len+1 digits for the real division and 1 more digit for the
414 final rounding of q.) */
415 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
420 while (a_len > 0 && a_ptr[a_len - 1] == 0)
427 /* Division by zero. */
429 if (b_ptr[b_len - 1] == 0)
435 /* Here m = a_len >= 0 and n = b_len > 0. */
439 /* m<n: trivial case. q=0, r := copy of a. */
442 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
443 q_ptr = roomptr + a_len;
448 /* n=1: single precision division.
449 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
453 mp_limb_t den = b_ptr[0];
454 mp_limb_t remainder = 0;
455 const mp_limb_t *sourceptr = a_ptr + a_len;
456 mp_limb_t *destptr = q_ptr + a_len;
458 for (count = a_len; count > 0; count--)
461 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
462 *--destptr = num / den;
463 remainder = num % den;
465 /* Normalise and store r. */
468 r_ptr[0] = remainder;
475 if (q_ptr[q_len - 1] == 0)
481 /* n>1: multiple precision division.
482 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
483 beta^(m-n-1) <= a/b < beta^(m-n+1). */
487 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
515 /* 0 <= s < GMP_LIMB_BITS.
516 Copy b, shifting it left by s bits. */
519 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
520 if (tmp_roomptr == NULL)
526 const mp_limb_t *sourceptr = b_ptr;
527 mp_limb_t *destptr = tmp_roomptr;
528 mp_twolimb_t accu = 0;
530 for (count = b_len; count > 0; count--)
532 accu += (mp_twolimb_t) *sourceptr++ << s;
533 *destptr++ = (mp_limb_t) accu;
534 accu = accu >> GMP_LIMB_BITS;
536 /* accu must be zero, since that was how s was determined. */
542 /* Copy a, shifting it left by s bits, yields r.
544 At the beginning: r = roomptr[0..a_len],
545 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
549 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
554 const mp_limb_t *sourceptr = a_ptr;
555 mp_limb_t *destptr = r_ptr;
556 mp_twolimb_t accu = 0;
558 for (count = a_len; count > 0; count--)
560 accu += (mp_twolimb_t) *sourceptr++ << s;
561 *destptr++ = (mp_limb_t) accu;
562 accu = accu >> GMP_LIMB_BITS;
564 *destptr++ = (mp_limb_t) accu;
566 q_ptr = roomptr + b_len;
567 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
569 size_t j = a_len - b_len; /* m-n */
570 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
571 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
572 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
573 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
574 /* Division loop, traversed m-n+1 times.
575 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
580 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
582 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
584 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
585 | r_ptr[j + b_len - 1];
586 q_star = num / b_msd;
591 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
592 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
593 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
594 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
595 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
597 If yes, jump directly to the subtraction loop.
598 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
599 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
600 if (r_ptr[j + b_len] > b_msd
601 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
602 /* r[j+n] >= b[n-1]+1 or
603 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
608 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
610 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
611 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
612 mp_twolimb_t c3 = /* b[n-2] * q* */
613 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
614 /* While c2 < c3, increase c2 and decrease c3.
615 Consider c3-c2. While it is > 0, decrease it by
616 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
617 this can happen only twice. */
620 q_star = q_star - 1; /* q* := q* - 1 */
621 if (c3 - c2 > b_msdd)
622 q_star = q_star - 1; /* q* := q* - 1 */
628 /* Subtract r := r - b * q* * beta^j. */
631 const mp_limb_t *sourceptr = b_ptr;
632 mp_limb_t *destptr = r_ptr + j;
633 mp_twolimb_t carry = 0;
635 for (count = b_len; count > 0; count--)
637 /* Here 0 <= carry <= q*. */
640 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
641 + (mp_limb_t) ~(*destptr);
642 /* Here 0 <= carry <= beta*q* + beta-1. */
643 *destptr++ = ~(mp_limb_t) carry;
644 carry = carry >> GMP_LIMB_BITS; /* <= q* */
646 cr = (mp_limb_t) carry;
648 /* Subtract cr from r_ptr[j + b_len], then forget about
650 if (cr > r_ptr[j + b_len])
652 /* Subtraction gave a carry. */
653 q_star = q_star - 1; /* q* := q* - 1 */
656 const mp_limb_t *sourceptr = b_ptr;
657 mp_limb_t *destptr = r_ptr + j;
660 for (count = b_len; count > 0; count--)
662 mp_limb_t source1 = *sourceptr++;
663 mp_limb_t source2 = *destptr;
664 *destptr++ = source1 + source2 + carry;
667 ? source1 >= (mp_limb_t) ~source2
668 : source1 > (mp_limb_t) ~source2);
671 /* Forget about the carry and about r[j+n]. */
674 /* q* is determined. Store it as q[j]. */
683 if (q_ptr[q_len - 1] == 0)
685 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
686 b is shifted left by s bits. */
687 /* Shift r right by s bits. */
690 mp_limb_t ptr = r_ptr + r_len;
691 mp_twolimb_t accu = 0;
693 for (count = r_len; count > 0; count--)
695 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
696 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
697 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
702 while (r_len > 0 && r_ptr[r_len - 1] == 0)
705 /* Compare r << 1 with b. */
713 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
714 | (i < r_len ? r_ptr[i] << 1 : 0);
715 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
725 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
730 for (i = 0; i < q_len; i++)
731 if (++(q_ptr[i]) != 0)
736 if (tmp_roomptr != NULL)
743 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
745 Destroys the contents of a.
746 Return the allocated memory - containing the decimal digits in low-to-high
747 order, terminated with a NUL character - in case of success, NULL in case
748 of memory allocation failure. */
750 convert_to_decimal (mpn_t a, size_t extra_zeroes)
752 mp_limb_t *a_ptr = a.limbs;
753 size_t a_len = a.nlimbs;
754 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
755 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
756 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
760 for (; extra_zeroes > 0; extra_zeroes--)
764 /* Divide a by 10^9, in-place. */
765 mp_limb_t remainder = 0;
766 mp_limb_t *ptr = a_ptr + a_len;
768 for (count = a_len; count > 0; count--)
771 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
772 *ptr = num / 1000000000;
773 remainder = num % 1000000000;
775 /* Store the remainder as 9 decimal digits. */
776 for (count = 9; count > 0; count--)
778 *d_ptr++ = '0' + (remainder % 10);
779 remainder = remainder / 10;
782 if (a_ptr[a_len - 1] == 0)
785 /* Remove leading zeroes. */
786 while (d_ptr > c_ptr && d_ptr[-1] == '0')
788 /* But keep at least one zero. */
791 /* Terminate the string. */
797 # if NEED_PRINTF_LONG_DOUBLE
799 /* Assuming x is finite and >= 0:
800 write x as x = 2^e * m, where m is a bignum.
801 Return the allocated memory in case of success, NULL in case of memory
802 allocation failure. */
804 decode_long_double (long double x, int *ep, mpn_t *mp)
811 /* Allocate memory for result. */
812 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
813 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
816 /* Split into exponential part and mantissa. */
817 y = frexpl (x, &exp);
818 if (!(y >= 0.0L && y < 1.0L))
820 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
821 latter is an integer. */
822 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
823 I'm not sure whether it's safe to cast a 'long double' value between
824 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
825 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
827 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
828 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
831 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
834 if (!(y >= 0.0L && y < 1.0L))
836 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
839 if (!(y >= 0.0L && y < 1.0L))
841 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
846 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
849 if (!(y >= 0.0L && y < 1.0L))
851 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
855 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
858 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
861 if (!(y >= 0.0L && y < 1.0L))
863 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
866 if (!(y >= 0.0L && y < 1.0L))
868 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
873 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
876 *ep = exp - LDBL_MANT_BIT;
882 # if NEED_PRINTF_DOUBLE
884 /* Assuming x is finite and >= 0:
885 write x as x = 2^e * m, where m is a bignum.
886 Return the allocated memory in case of success, NULL in case of memory
887 allocation failure. */
889 decode_double (double x, int *ep, mpn_t *mp)
896 /* Allocate memory for result. */
897 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
898 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
901 /* Split into exponential part and mantissa. */
903 if (!(y >= 0.0 && y < 1.0))
905 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
906 latter is an integer. */
907 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
908 I'm not sure whether it's safe to cast a 'double' value between
909 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
910 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
912 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
913 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
916 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
919 if (!(y >= 0.0 && y < 1.0))
921 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
924 if (!(y >= 0.0 && y < 1.0))
926 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
931 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
934 if (!(y >= 0.0 && y < 1.0))
936 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
940 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
943 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
946 if (!(y >= 0.0 && y < 1.0))
948 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
951 if (!(y >= 0.0 && y < 1.0))
953 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
958 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
961 *ep = exp - DBL_MANT_BIT;
967 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
968 Returns the decimal representation of round (x * 10^n).
969 Return the allocated memory - containing the decimal digits in low-to-high
970 order, terminated with a NUL character - in case of success, NULL in case
971 of memory allocation failure. */
973 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
981 unsigned int s_limbs;
990 /* x = 2^e * m, hence
991 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
992 = round (2^s * 5^n * m). */
995 /* Factor out a common power of 10 if possible. */
998 extra_zeroes = (s < n ? s : n);
1002 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1003 Before converting to decimal, we need to compute
1004 z = round (2^s * 5^n * m). */
1005 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1006 sign. 2.322 is slightly larger than log(5)/log(2). */
1007 abs_n = (n >= 0 ? n : -n);
1008 abs_s = (s >= 0 ? s : -s);
1009 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1010 + abs_s / GMP_LIMB_BITS + 1)
1011 * sizeof (mp_limb_t));
1012 if (pow5_ptr == NULL)
1017 /* Initialize with 1. */
1020 /* Multiply with 5^|n|. */
1023 static mp_limb_t const small_pow5[13 + 1] =
1025 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1026 48828125, 244140625, 1220703125
1029 for (n13 = 0; n13 <= abs_n; n13 += 13)
1031 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1033 mp_twolimb_t carry = 0;
1034 for (j = 0; j < pow5_len; j++)
1036 mp_limb_t digit2 = pow5_ptr[j];
1037 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1038 pow5_ptr[j] = (mp_limb_t) carry;
1039 carry = carry >> GMP_LIMB_BITS;
1042 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1045 s_limbs = abs_s / GMP_LIMB_BITS;
1046 s_bits = abs_s % GMP_LIMB_BITS;
1047 if (n >= 0 ? s >= 0 : s <= 0)
1049 /* Multiply with 2^|s|. */
1052 mp_limb_t *ptr = pow5_ptr;
1053 mp_twolimb_t accu = 0;
1055 for (count = pow5_len; count > 0; count--)
1057 accu += (mp_twolimb_t) *ptr << s_bits;
1058 *ptr++ = (mp_limb_t) accu;
1059 accu = accu >> GMP_LIMB_BITS;
1063 *ptr = (mp_limb_t) accu;
1070 for (count = pow5_len; count > 0;)
1073 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1075 for (count = s_limbs; count > 0;)
1078 pow5_ptr[count] = 0;
1080 pow5_len += s_limbs;
1082 pow5.limbs = pow5_ptr;
1083 pow5.nlimbs = pow5_len;
1086 /* Multiply m with pow5. No division needed. */
1087 z_memory = multiply (m, pow5, &z);
1091 /* Divide m by pow5 and round. */
1092 z_memory = divide (m, pow5, &z);
1097 pow5.limbs = pow5_ptr;
1098 pow5.nlimbs = pow5_len;
1102 Multiply m with pow5, then divide by 2^|s|. */
1106 tmp_memory = multiply (m, pow5, &numerator);
1107 if (tmp_memory == NULL)
1113 /* Construct 2^|s|. */
1115 mp_limb_t *ptr = pow5_ptr + pow5_len;
1117 for (i = 0; i < s_limbs; i++)
1119 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1120 denominator.limbs = ptr;
1121 denominator.nlimbs = s_limbs + 1;
1123 z_memory = divide (numerator, denominator, &z);
1129 Multiply m with 2^s, then divide by pow5. */
1132 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1133 * sizeof (mp_limb_t));
1134 if (num_ptr == NULL)
1141 mp_limb_t *destptr = num_ptr;
1144 for (i = 0; i < s_limbs; i++)
1149 const mp_limb_t *sourceptr = m.limbs;
1150 mp_twolimb_t accu = 0;
1152 for (count = m.nlimbs; count > 0; count--)
1154 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1155 *destptr++ = (mp_limb_t) accu;
1156 accu = accu >> GMP_LIMB_BITS;
1159 *destptr++ = (mp_limb_t) accu;
1163 const mp_limb_t *sourceptr = m.limbs;
1165 for (count = m.nlimbs; count > 0; count--)
1166 *destptr++ = *sourceptr++;
1168 numerator.limbs = num_ptr;
1169 numerator.nlimbs = destptr - num_ptr;
1171 z_memory = divide (numerator, pow5, &z);
1178 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1180 if (z_memory == NULL)
1182 digits = convert_to_decimal (z, extra_zeroes);
1187 # if NEED_PRINTF_LONG_DOUBLE
1189 /* Assuming x is finite and >= 0, and n is an integer:
1190 Returns the decimal representation of round (x * 10^n).
1191 Return the allocated memory - containing the decimal digits in low-to-high
1192 order, terminated with a NUL character - in case of success, NULL in case
1193 of memory allocation failure. */
1195 scale10_round_decimal_long_double (long double x, int n)
1199 void *memory = decode_long_double (x, &e, &m);
1200 return scale10_round_decimal_decoded (e, m, memory, n);
1205 # if NEED_PRINTF_DOUBLE
1207 /* Assuming x is finite and >= 0, and n is an integer:
1208 Returns the decimal representation of round (x * 10^n).
1209 Return the allocated memory - containing the decimal digits in low-to-high
1210 order, terminated with a NUL character - in case of success, NULL in case
1211 of memory allocation failure. */
1213 scale10_round_decimal_double (double x, int n)
1217 void *memory = decode_double (x, &e, &m);
1218 return scale10_round_decimal_decoded (e, m, memory, n);
1223 # if NEED_PRINTF_LONG_DOUBLE
1225 /* Assuming x is finite and > 0:
1226 Return an approximation for n with 10^n <= x < 10^(n+1).
1227 The approximation is usually the right n, but may be off by 1 sometimes. */
1229 floorlog10l (long double x)
1236 /* Split into exponential part and mantissa. */
1237 y = frexpl (x, &exp);
1238 if (!(y >= 0.0L && y < 1.0L))
1244 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1246 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1247 exp -= GMP_LIMB_BITS;
1249 if (y < (1.0L / (1 << 16)))
1251 y *= 1.0L * (1 << 16);
1254 if (y < (1.0L / (1 << 8)))
1256 y *= 1.0L * (1 << 8);
1259 if (y < (1.0L / (1 << 4)))
1261 y *= 1.0L * (1 << 4);
1264 if (y < (1.0L / (1 << 2)))
1266 y *= 1.0L * (1 << 2);
1269 if (y < (1.0L / (1 << 1)))
1271 y *= 1.0L * (1 << 1);
1275 if (!(y >= 0.5L && y < 1.0L))
1277 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1280 if (z < 0.70710678118654752444)
1282 z *= 1.4142135623730950488;
1285 if (z < 0.8408964152537145431)
1287 z *= 1.1892071150027210667;
1290 if (z < 0.91700404320467123175)
1292 z *= 1.0905077326652576592;
1295 if (z < 0.9576032806985736469)
1297 z *= 1.0442737824274138403;
1300 /* Now 0.95 <= z <= 1.01. */
1302 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1303 Four terms are enough to get an approximation with error < 10^-7. */
1304 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1305 /* Finally multiply with log(2)/log(10), yields an approximation for
1307 l *= 0.30102999566398119523;
1308 /* Round down to the next integer. */
1309 return (int) l + (l < 0 ? -1 : 0);
1314 # if NEED_PRINTF_DOUBLE
1316 /* Assuming x is finite and > 0:
1317 Return an approximation for n with 10^n <= x < 10^(n+1).
1318 The approximation is usually the right n, but may be off by 1 sometimes. */
1320 floorlog10 (double x)
1327 /* Split into exponential part and mantissa. */
1328 y = frexp (x, &exp);
1329 if (!(y >= 0.0 && y < 1.0))
1335 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1337 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1338 exp -= GMP_LIMB_BITS;
1340 if (y < (1.0 / (1 << 16)))
1342 y *= 1.0 * (1 << 16);
1345 if (y < (1.0 / (1 << 8)))
1347 y *= 1.0 * (1 << 8);
1350 if (y < (1.0 / (1 << 4)))
1352 y *= 1.0 * (1 << 4);
1355 if (y < (1.0 / (1 << 2)))
1357 y *= 1.0 * (1 << 2);
1360 if (y < (1.0 / (1 << 1)))
1362 y *= 1.0 * (1 << 1);
1366 if (!(y >= 0.5 && y < 1.0))
1368 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1371 if (z < 0.70710678118654752444)
1373 z *= 1.4142135623730950488;
1376 if (z < 0.8408964152537145431)
1378 z *= 1.1892071150027210667;
1381 if (z < 0.91700404320467123175)
1383 z *= 1.0905077326652576592;
1386 if (z < 0.9576032806985736469)
1388 z *= 1.0442737824274138403;
1391 /* Now 0.95 <= z <= 1.01. */
1393 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1394 Four terms are enough to get an approximation with error < 10^-7. */
1395 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1396 /* Finally multiply with log(2)/log(10), yields an approximation for
1398 l *= 0.30102999566398119523;
1399 /* Round down to the next integer. */
1400 return (int) l + (l < 0 ? -1 : 0);
1408 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1409 const FCHAR_T *format, va_list args)
1414 if (PRINTF_PARSE (format, &d, &a) < 0)
1415 /* errno is already set. */
1423 if (PRINTF_FETCHARGS (args, &a) < 0)
1431 size_t buf_neededlength;
1433 TCHAR_T *buf_malloced;
1437 /* Output string accumulator. */
1442 /* Allocate a small buffer that will hold a directive passed to
1443 sprintf or snprintf. */
1445 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1447 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1449 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1450 buf_malloced = NULL;
1455 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1456 if (size_overflow_p (buf_memsize))
1457 goto out_of_memory_1;
1458 buf = (TCHAR_T *) malloc (buf_memsize);
1460 goto out_of_memory_1;
1464 if (resultbuf != NULL)
1467 allocated = *lengthp;
1476 result is either == resultbuf or == NULL or malloc-allocated.
1477 If length > 0, then result != NULL. */
1479 /* Ensures that allocated >= needed. Aborts through a jump to
1480 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1481 #define ENSURE_ALLOCATION(needed) \
1482 if ((needed) > allocated) \
1484 size_t memory_size; \
1487 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1488 if ((needed) > allocated) \
1489 allocated = (needed); \
1490 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1491 if (size_overflow_p (memory_size)) \
1492 goto out_of_memory; \
1493 if (result == resultbuf || result == NULL) \
1494 memory = (DCHAR_T *) malloc (memory_size); \
1496 memory = (DCHAR_T *) realloc (result, memory_size); \
1497 if (memory == NULL) \
1498 goto out_of_memory; \
1499 if (result == resultbuf && length > 0) \
1500 DCHAR_CPY (memory, result, length); \
1504 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1506 if (cp != dp->dir_start)
1508 size_t n = dp->dir_start - cp;
1509 size_t augmented_length = xsum (length, n);
1511 ENSURE_ALLOCATION (augmented_length);
1512 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1513 need that the format string contains only ASCII characters
1514 if FCHAR_T and DCHAR_T are not the same type. */
1515 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1517 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1518 length = augmented_length;
1523 result[length++] = (unsigned char) *cp++;
1530 /* Execute a single directive. */
1531 if (dp->conversion == '%')
1533 size_t augmented_length;
1535 if (!(dp->arg_index == ARG_NONE))
1537 augmented_length = xsum (length, 1);
1538 ENSURE_ALLOCATION (augmented_length);
1539 result[length] = '%';
1540 length = augmented_length;
1544 if (!(dp->arg_index != ARG_NONE))
1547 if (dp->conversion == 'n')
1549 switch (a.arg[dp->arg_index].type)
1551 case TYPE_COUNT_SCHAR_POINTER:
1552 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1554 case TYPE_COUNT_SHORT_POINTER:
1555 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1557 case TYPE_COUNT_INT_POINTER:
1558 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1560 case TYPE_COUNT_LONGINT_POINTER:
1561 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1563 #if HAVE_LONG_LONG_INT
1564 case TYPE_COUNT_LONGLONGINT_POINTER:
1565 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1573 /* The unistdio extensions. */
1574 else if (dp->conversion == 'U')
1576 arg_type type = a.arg[dp->arg_index].type;
1577 int flags = dp->flags;
1585 if (dp->width_start != dp->width_end)
1587 if (dp->width_arg_index != ARG_NONE)
1591 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1593 arg = a.arg[dp->width_arg_index].a.a_int;
1596 /* "A negative field width is taken as a '-' flag
1597 followed by a positive field width." */
1599 width = (unsigned int) (-arg);
1606 const FCHAR_T *digitp = dp->width_start;
1609 width = xsum (xtimes (width, 10), *digitp++ - '0');
1610 while (digitp != dp->width_end);
1617 if (dp->precision_start != dp->precision_end)
1619 if (dp->precision_arg_index != ARG_NONE)
1623 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1625 arg = a.arg[dp->precision_arg_index].a.a_int;
1626 /* "A negative precision is taken as if the precision
1636 const FCHAR_T *digitp = dp->precision_start + 1;
1639 while (digitp != dp->precision_end)
1640 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1647 case TYPE_U8_STRING:
1649 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1650 const uint8_t *arg_end;
1655 /* Use only PRECISION characters, from the left. */
1658 for (; precision > 0; precision--)
1660 int count = u8_strmblen (arg_end);
1665 if (!(result == resultbuf || result == NULL))
1667 if (buf_malloced != NULL)
1668 free (buf_malloced);
1679 /* Use the entire string, and count the number of
1685 int count = u8_strmblen (arg_end);
1690 if (!(result == resultbuf || result == NULL))
1692 if (buf_malloced != NULL)
1693 free (buf_malloced);
1704 /* Use the entire string. */
1705 arg_end = arg + u8_strlen (arg);
1706 /* The number of characters doesn't matter. */
1710 if (has_width && width > characters
1711 && !(dp->flags & FLAG_LEFT))
1713 size_t n = width - characters;
1714 ENSURE_ALLOCATION (xsum (length, n));
1715 DCHAR_SET (result + length, ' ', n);
1719 # if DCHAR_IS_UINT8_T
1721 size_t n = arg_end - arg;
1722 ENSURE_ALLOCATION (xsum (length, n));
1723 DCHAR_CPY (result + length, arg, n);
1728 DCHAR_T *converted = result + length;
1729 size_t converted_len = allocated - length;
1731 /* Convert from UTF-8 to locale encoding. */
1732 if (u8_conv_to_encoding (locale_charset (),
1733 iconveh_question_mark,
1734 arg, arg_end - arg, NULL,
1735 &converted, &converted_len)
1738 /* Convert from UTF-8 to UTF-16/UTF-32. */
1740 U8_TO_DCHAR (arg, arg_end - arg,
1741 converted, &converted_len);
1742 if (converted == NULL)
1745 int saved_errno = errno;
1746 if (!(result == resultbuf || result == NULL))
1748 if (buf_malloced != NULL)
1749 free (buf_malloced);
1751 errno = saved_errno;
1754 if (converted != result + length)
1756 ENSURE_ALLOCATION (xsum (length, converted_len));
1757 DCHAR_CPY (result + length, converted, converted_len);
1760 length += converted_len;
1764 if (has_width && width > characters
1765 && (dp->flags & FLAG_LEFT))
1767 size_t n = width - characters;
1768 ENSURE_ALLOCATION (xsum (length, n));
1769 DCHAR_SET (result + length, ' ', n);
1775 case TYPE_U16_STRING:
1777 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1778 const uint16_t *arg_end;
1783 /* Use only PRECISION characters, from the left. */
1786 for (; precision > 0; precision--)
1788 int count = u16_strmblen (arg_end);
1793 if (!(result == resultbuf || result == NULL))
1795 if (buf_malloced != NULL)
1796 free (buf_malloced);
1807 /* Use the entire string, and count the number of
1813 int count = u16_strmblen (arg_end);
1818 if (!(result == resultbuf || result == NULL))
1820 if (buf_malloced != NULL)
1821 free (buf_malloced);
1832 /* Use the entire string. */
1833 arg_end = arg + u16_strlen (arg);
1834 /* The number of characters doesn't matter. */
1838 if (has_width && width > characters
1839 && !(dp->flags & FLAG_LEFT))
1841 size_t n = width - characters;
1842 ENSURE_ALLOCATION (xsum (length, n));
1843 DCHAR_SET (result + length, ' ', n);
1847 # if DCHAR_IS_UINT16_T
1849 size_t n = arg_end - arg;
1850 ENSURE_ALLOCATION (xsum (length, n));
1851 DCHAR_CPY (result + length, arg, n);
1856 DCHAR_T *converted = result + length;
1857 size_t converted_len = allocated - length;
1859 /* Convert from UTF-16 to locale encoding. */
1860 if (u16_conv_to_encoding (locale_charset (),
1861 iconveh_question_mark,
1862 arg, arg_end - arg, NULL,
1863 &converted, &converted_len)
1866 /* Convert from UTF-16 to UTF-8/UTF-32. */
1868 U16_TO_DCHAR (arg, arg_end - arg,
1869 converted, &converted_len);
1870 if (converted == NULL)
1873 int saved_errno = errno;
1874 if (!(result == resultbuf || result == NULL))
1876 if (buf_malloced != NULL)
1877 free (buf_malloced);
1879 errno = saved_errno;
1882 if (converted != result + length)
1884 ENSURE_ALLOCATION (xsum (length, converted_len));
1885 DCHAR_CPY (result + length, converted, converted_len);
1888 length += converted_len;
1892 if (has_width && width > characters
1893 && (dp->flags & FLAG_LEFT))
1895 size_t n = width - characters;
1896 ENSURE_ALLOCATION (xsum (length, n));
1897 DCHAR_SET (result + length, ' ', n);
1903 case TYPE_U32_STRING:
1905 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1906 const uint32_t *arg_end;
1911 /* Use only PRECISION characters, from the left. */
1914 for (; precision > 0; precision--)
1916 int count = u32_strmblen (arg_end);
1921 if (!(result == resultbuf || result == NULL))
1923 if (buf_malloced != NULL)
1924 free (buf_malloced);
1935 /* Use the entire string, and count the number of
1941 int count = u32_strmblen (arg_end);
1946 if (!(result == resultbuf || result == NULL))
1948 if (buf_malloced != NULL)
1949 free (buf_malloced);
1960 /* Use the entire string. */
1961 arg_end = arg + u32_strlen (arg);
1962 /* The number of characters doesn't matter. */
1966 if (has_width && width > characters
1967 && !(dp->flags & FLAG_LEFT))
1969 size_t n = width - characters;
1970 ENSURE_ALLOCATION (xsum (length, n));
1971 DCHAR_SET (result + length, ' ', n);
1975 # if DCHAR_IS_UINT32_T
1977 size_t n = arg_end - arg;
1978 ENSURE_ALLOCATION (xsum (length, n));
1979 DCHAR_CPY (result + length, arg, n);
1984 DCHAR_T *converted = result + length;
1985 size_t converted_len = allocated - length;
1987 /* Convert from UTF-32 to locale encoding. */
1988 if (u32_conv_to_encoding (locale_charset (),
1989 iconveh_question_mark,
1990 arg, arg_end - arg, NULL,
1991 &converted, &converted_len)
1994 /* Convert from UTF-32 to UTF-8/UTF-16. */
1996 U32_TO_DCHAR (arg, arg_end - arg,
1997 converted, &converted_len);
1998 if (converted == NULL)
2001 int saved_errno = errno;
2002 if (!(result == resultbuf || result == NULL))
2004 if (buf_malloced != NULL)
2005 free (buf_malloced);
2007 errno = saved_errno;
2010 if (converted != result + length)
2012 ENSURE_ALLOCATION (xsum (length, converted_len));
2013 DCHAR_CPY (result + length, converted, converted_len);
2016 length += converted_len;
2020 if (has_width && width > characters
2021 && (dp->flags & FLAG_LEFT))
2023 size_t n = width - characters;
2024 ENSURE_ALLOCATION (xsum (length, n));
2025 DCHAR_SET (result + length, ' ', n);
2036 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
2037 else if (dp->conversion == 'a' || dp->conversion == 'A')
2039 arg_type type = a.arg[dp->arg_index].type;
2040 int flags = dp->flags;
2046 DCHAR_T tmpbuf[700];
2053 if (dp->width_start != dp->width_end)
2055 if (dp->width_arg_index != ARG_NONE)
2059 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2061 arg = a.arg[dp->width_arg_index].a.a_int;
2064 /* "A negative field width is taken as a '-' flag
2065 followed by a positive field width." */
2067 width = (unsigned int) (-arg);
2074 const FCHAR_T *digitp = dp->width_start;
2077 width = xsum (xtimes (width, 10), *digitp++ - '0');
2078 while (digitp != dp->width_end);
2085 if (dp->precision_start != dp->precision_end)
2087 if (dp->precision_arg_index != ARG_NONE)
2091 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2093 arg = a.arg[dp->precision_arg_index].a.a_int;
2094 /* "A negative precision is taken as if the precision
2104 const FCHAR_T *digitp = dp->precision_start + 1;
2107 while (digitp != dp->precision_end)
2108 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2113 /* Allocate a temporary buffer of sufficient size. */
2114 if (type == TYPE_LONGDOUBLE)
2116 (unsigned int) ((LDBL_DIG + 1)
2117 * 0.831 /* decimal -> hexadecimal */
2119 + 1; /* turn floor into ceil */
2122 (unsigned int) ((DBL_DIG + 1)
2123 * 0.831 /* decimal -> hexadecimal */
2125 + 1; /* turn floor into ceil */
2126 if (tmp_length < precision)
2127 tmp_length = precision;
2128 /* Account for sign, decimal point etc. */
2129 tmp_length = xsum (tmp_length, 12);
2131 if (tmp_length < width)
2134 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2136 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2140 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2142 if (size_overflow_p (tmp_memsize))
2143 /* Overflow, would lead to out of memory. */
2145 tmp = (DCHAR_T *) malloc (tmp_memsize);
2147 /* Out of memory. */
2153 if (type == TYPE_LONGDOUBLE)
2155 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2159 if (dp->conversion == 'A')
2161 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2165 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2171 DECL_LONG_DOUBLE_ROUNDING
2173 BEGIN_LONG_DOUBLE_ROUNDING ();
2175 if (signbit (arg)) /* arg < 0.0L or negative zero */
2183 else if (flags & FLAG_SHOWSIGN)
2185 else if (flags & FLAG_SPACE)
2188 if (arg > 0.0L && arg + arg == arg)
2190 if (dp->conversion == 'A')
2192 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2196 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2202 long double mantissa;
2205 mantissa = printf_frexpl (arg, &exponent);
2213 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2215 /* Round the mantissa. */
2216 long double tail = mantissa;
2219 for (q = precision; ; q--)
2221 int digit = (int) tail;
2225 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2234 for (q = precision; q > 0; q--)
2240 *p++ = dp->conversion - 'A' + 'X';
2245 digit = (int) mantissa;
2248 if ((flags & FLAG_ALT)
2249 || mantissa > 0.0L || precision > 0)
2251 *p++ = decimal_point_char ();
2252 /* This loop terminates because we assume
2253 that FLT_RADIX is a power of 2. */
2254 while (mantissa > 0.0L)
2257 digit = (int) mantissa;
2262 : dp->conversion - 10);
2266 while (precision > 0)
2273 *p++ = dp->conversion - 'A' + 'P';
2274 # if WIDE_CHAR_VERSION
2276 static const wchar_t decimal_format[] =
2277 { '%', '+', 'd', '\0' };
2278 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2283 if (sizeof (DCHAR_T) == 1)
2285 sprintf ((char *) p, "%+d", exponent);
2293 sprintf (expbuf, "%+d", exponent);
2294 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2300 END_LONG_DOUBLE_ROUNDING ();
2305 double arg = a.arg[dp->arg_index].a.a_double;
2309 if (dp->conversion == 'A')
2311 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2315 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2322 if (signbit (arg)) /* arg < 0.0 or negative zero */
2330 else if (flags & FLAG_SHOWSIGN)
2332 else if (flags & FLAG_SPACE)
2335 if (arg > 0.0 && arg + arg == arg)
2337 if (dp->conversion == 'A')
2339 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2343 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2352 mantissa = printf_frexp (arg, &exponent);
2360 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2362 /* Round the mantissa. */
2363 double tail = mantissa;
2366 for (q = precision; ; q--)
2368 int digit = (int) tail;
2372 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2381 for (q = precision; q > 0; q--)
2387 *p++ = dp->conversion - 'A' + 'X';
2392 digit = (int) mantissa;
2395 if ((flags & FLAG_ALT)
2396 || mantissa > 0.0 || precision > 0)
2398 *p++ = decimal_point_char ();
2399 /* This loop terminates because we assume
2400 that FLT_RADIX is a power of 2. */
2401 while (mantissa > 0.0)
2404 digit = (int) mantissa;
2409 : dp->conversion - 10);
2413 while (precision > 0)
2420 *p++ = dp->conversion - 'A' + 'P';
2421 # if WIDE_CHAR_VERSION
2423 static const wchar_t decimal_format[] =
2424 { '%', '+', 'd', '\0' };
2425 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2430 if (sizeof (DCHAR_T) == 1)
2432 sprintf ((char *) p, "%+d", exponent);
2440 sprintf (expbuf, "%+d", exponent);
2441 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2448 /* The generated string now extends from tmp to p, with the
2449 zero padding insertion point being at pad_ptr. */
2450 if (has_width && p - tmp < width)
2452 size_t pad = width - (p - tmp);
2453 DCHAR_T *end = p + pad;
2455 if (flags & FLAG_LEFT)
2457 /* Pad with spaces on the right. */
2458 for (; pad > 0; pad--)
2461 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2463 /* Pad with zeroes. */
2468 for (; pad > 0; pad--)
2473 /* Pad with spaces on the left. */
2478 for (; pad > 0; pad--)
2486 size_t count = p - tmp;
2488 if (count >= tmp_length)
2489 /* tmp_length was incorrectly calculated - fix the
2493 /* Make room for the result. */
2494 if (count >= allocated - length)
2496 size_t n = xsum (length, count);
2498 ENSURE_ALLOCATION (n);
2501 /* Append the result. */
2502 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2509 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2510 else if ((dp->conversion == 'f' || dp->conversion == 'F'
2511 || dp->conversion == 'e' || dp->conversion == 'E'
2512 || dp->conversion == 'g' || dp->conversion == 'G'
2513 || dp->conversion == 'a' || dp->conversion == 'A')
2515 # if NEED_PRINTF_DOUBLE
2516 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2517 # elif NEED_PRINTF_INFINITE_DOUBLE
2518 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2519 /* The systems (mingw) which produce wrong output
2520 for Inf, -Inf, and NaN also do so for -0.0.
2521 Therefore we treat this case here as well. */
2522 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2524 # if NEED_PRINTF_LONG_DOUBLE
2525 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2526 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2527 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2528 /* Some systems produce wrong output for Inf,
2530 && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
2534 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2535 arg_type type = a.arg[dp->arg_index].type;
2537 int flags = dp->flags;
2543 DCHAR_T tmpbuf[700];
2550 if (dp->width_start != dp->width_end)
2552 if (dp->width_arg_index != ARG_NONE)
2556 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2558 arg = a.arg[dp->width_arg_index].a.a_int;
2561 /* "A negative field width is taken as a '-' flag
2562 followed by a positive field width." */
2564 width = (unsigned int) (-arg);
2571 const FCHAR_T *digitp = dp->width_start;
2574 width = xsum (xtimes (width, 10), *digitp++ - '0');
2575 while (digitp != dp->width_end);
2582 if (dp->precision_start != dp->precision_end)
2584 if (dp->precision_arg_index != ARG_NONE)
2588 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2590 arg = a.arg[dp->precision_arg_index].a.a_int;
2591 /* "A negative precision is taken as if the precision
2601 const FCHAR_T *digitp = dp->precision_start + 1;
2604 while (digitp != dp->precision_end)
2605 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2610 /* POSIX specifies the default precision to be 6 for %f, %F,
2611 %e, %E, but not for %g, %G. Implementations appear to use
2612 the same default precision also for %g, %G. */
2616 /* Allocate a temporary buffer of sufficient size. */
2617 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2618 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
2619 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2620 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2621 # elif NEED_PRINTF_LONG_DOUBLE
2622 tmp_length = LDBL_DIG + 1;
2623 # elif NEED_PRINTF_DOUBLE
2624 tmp_length = DBL_DIG + 1;
2628 if (tmp_length < precision)
2629 tmp_length = precision;
2630 # if NEED_PRINTF_LONG_DOUBLE
2631 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2632 if (type == TYPE_LONGDOUBLE)
2634 if (dp->conversion == 'f' || dp->conversion == 'F')
2636 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2637 if (!(isnanl (arg) || arg + arg == arg))
2639 /* arg is finite and nonzero. */
2640 int exponent = floorlog10l (arg < 0 ? -arg : arg);
2641 if (exponent >= 0 && tmp_length < exponent + precision)
2642 tmp_length = exponent + precision;
2646 # if NEED_PRINTF_DOUBLE
2647 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2648 if (type == TYPE_DOUBLE)
2650 if (dp->conversion == 'f' || dp->conversion == 'F')
2652 double arg = a.arg[dp->arg_index].a.a_double;
2653 if (!(isnan (arg) || arg + arg == arg))
2655 /* arg is finite and nonzero. */
2656 int exponent = floorlog10 (arg < 0 ? -arg : arg);
2657 if (exponent >= 0 && tmp_length < exponent + precision)
2658 tmp_length = exponent + precision;
2662 /* Account for sign, decimal point etc. */
2663 tmp_length = xsum (tmp_length, 12);
2665 if (tmp_length < width)
2668 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2670 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2674 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2676 if (size_overflow_p (tmp_memsize))
2677 /* Overflow, would lead to out of memory. */
2679 tmp = (DCHAR_T *) malloc (tmp_memsize);
2681 /* Out of memory. */
2688 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2689 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2690 if (type == TYPE_LONGDOUBLE)
2693 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2697 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2699 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2703 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2709 DECL_LONG_DOUBLE_ROUNDING
2711 BEGIN_LONG_DOUBLE_ROUNDING ();
2713 if (signbit (arg)) /* arg < 0.0L or negative zero */
2721 else if (flags & FLAG_SHOWSIGN)
2723 else if (flags & FLAG_SPACE)
2726 if (arg > 0.0L && arg + arg == arg)
2728 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2730 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2734 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2739 # if NEED_PRINTF_LONG_DOUBLE
2742 if (dp->conversion == 'f' || dp->conversion == 'F')
2748 scale10_round_decimal_long_double (arg, precision);
2751 END_LONG_DOUBLE_ROUNDING ();
2754 ndigits = strlen (digits);
2756 if (ndigits > precision)
2760 *p++ = digits[ndigits];
2762 while (ndigits > precision);
2765 /* Here ndigits <= precision. */
2766 if ((flags & FLAG_ALT) || precision > 0)
2768 *p++ = decimal_point_char ();
2769 for (; precision > ndigits; precision--)
2774 *p++ = digits[ndigits];
2780 else if (dp->conversion == 'e' || dp->conversion == 'E')
2788 if ((flags & FLAG_ALT) || precision > 0)
2790 *p++ = decimal_point_char ();
2791 for (; precision > 0; precision--)
2802 exponent = floorlog10l (arg);
2807 scale10_round_decimal_long_double (arg,
2808 (int)precision - exponent);
2811 END_LONG_DOUBLE_ROUNDING ();
2814 ndigits = strlen (digits);
2816 if (ndigits == precision + 1)
2818 if (ndigits < precision
2819 || ndigits > precision + 2)
2820 /* The exponent was not guessed
2821 precisely enough. */
2824 /* None of two values of exponent is
2825 the right one. Prevent an endless
2829 if (ndigits == precision)
2836 /* Here ndigits = precision+1. */
2837 *p++ = digits[--ndigits];
2838 if ((flags & FLAG_ALT) || precision > 0)
2840 *p++ = decimal_point_char ();
2844 *p++ = digits[ndigits];
2851 *p++ = dp->conversion; /* 'e' or 'E' */
2852 # if WIDE_CHAR_VERSION
2854 static const wchar_t decimal_format[] =
2855 { '%', '+', '.', '2', 'd', '\0' };
2856 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2861 if (sizeof (DCHAR_T) == 1)
2863 sprintf ((char *) p, "%+.2d", exponent);
2871 sprintf (expbuf, "%+.2d", exponent);
2872 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2877 else if (dp->conversion == 'g' || dp->conversion == 'G')
2881 /* precision >= 1. */
2884 /* The exponent is 0, >= -4, < precision.
2885 Use fixed-point notation. */
2887 size_t ndigits = precision;
2888 /* Number of trailing zeroes that have to be
2891 (flags & FLAG_ALT ? 0 : precision - 1);
2895 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2897 *p++ = decimal_point_char ();
2898 while (ndigits > nzeroes)
2914 exponent = floorlog10l (arg);
2919 scale10_round_decimal_long_double (arg,
2920 (int)(precision - 1) - exponent);
2923 END_LONG_DOUBLE_ROUNDING ();
2926 ndigits = strlen (digits);
2928 if (ndigits == precision)
2930 if (ndigits < precision - 1
2931 || ndigits > precision + 1)
2932 /* The exponent was not guessed
2933 precisely enough. */
2936 /* None of two values of exponent is
2937 the right one. Prevent an endless
2941 if (ndigits < precision)
2947 /* Here ndigits = precision. */
2949 /* Determine the number of trailing zeroes
2950 that have to be dropped. */
2952 if ((flags & FLAG_ALT) == 0)
2953 while (nzeroes < ndigits
2954 && digits[nzeroes] == '0')
2957 /* The exponent is now determined. */
2959 && exponent < (long)precision)
2961 /* Fixed-point notation:
2962 max(exponent,0)+1 digits, then the
2963 decimal point, then the remaining
2964 digits without trailing zeroes. */
2967 size_t count = exponent + 1;
2968 /* Note: count <= precision = ndigits. */
2969 for (; count > 0; count--)
2970 *p++ = digits[--ndigits];
2971 if ((flags & FLAG_ALT) || ndigits > nzeroes)
2973 *p++ = decimal_point_char ();
2974 while (ndigits > nzeroes)
2977 *p++ = digits[ndigits];
2983 size_t count = -exponent - 1;
2985 *p++ = decimal_point_char ();
2986 for (; count > 0; count--)
2988 while (ndigits > nzeroes)
2991 *p++ = digits[ndigits];
2997 /* Exponential notation. */
2998 *p++ = digits[--ndigits];
2999 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3001 *p++ = decimal_point_char ();
3002 while (ndigits > nzeroes)
3005 *p++ = digits[ndigits];
3008 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3009 # if WIDE_CHAR_VERSION
3011 static const wchar_t decimal_format[] =
3012 { '%', '+', '.', '2', 'd', '\0' };
3013 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3018 if (sizeof (DCHAR_T) == 1)
3020 sprintf ((char *) p, "%+.2d", exponent);
3028 sprintf (expbuf, "%+.2d", exponent);
3029 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3041 /* arg is finite. */
3046 END_LONG_DOUBLE_ROUNDING ();
3049 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3053 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3055 double arg = a.arg[dp->arg_index].a.a_double;
3059 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3061 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3065 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3072 if (signbit (arg)) /* arg < 0.0 or negative zero */
3080 else if (flags & FLAG_SHOWSIGN)
3082 else if (flags & FLAG_SPACE)
3085 if (arg > 0.0 && arg + arg == arg)
3087 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3089 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3093 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3098 # if NEED_PRINTF_DOUBLE
3101 if (dp->conversion == 'f' || dp->conversion == 'F')
3107 scale10_round_decimal_double (arg, precision);
3110 ndigits = strlen (digits);
3112 if (ndigits > precision)
3116 *p++ = digits[ndigits];
3118 while (ndigits > precision);
3121 /* Here ndigits <= precision. */
3122 if ((flags & FLAG_ALT) || precision > 0)
3124 *p++ = decimal_point_char ();
3125 for (; precision > ndigits; precision--)
3130 *p++ = digits[ndigits];
3136 else if (dp->conversion == 'e' || dp->conversion == 'E')
3144 if ((flags & FLAG_ALT) || precision > 0)
3146 *p++ = decimal_point_char ();
3147 for (; precision > 0; precision--)
3158 exponent = floorlog10 (arg);
3163 scale10_round_decimal_double (arg,
3164 (int)precision - exponent);
3167 ndigits = strlen (digits);
3169 if (ndigits == precision + 1)
3171 if (ndigits < precision
3172 || ndigits > precision + 2)
3173 /* The exponent was not guessed
3174 precisely enough. */
3177 /* None of two values of exponent is
3178 the right one. Prevent an endless
3182 if (ndigits == precision)
3189 /* Here ndigits = precision+1. */
3190 *p++ = digits[--ndigits];
3191 if ((flags & FLAG_ALT) || precision > 0)
3193 *p++ = decimal_point_char ();
3197 *p++ = digits[ndigits];
3204 *p++ = dp->conversion; /* 'e' or 'E' */
3205 # if WIDE_CHAR_VERSION
3207 static const wchar_t decimal_format[] =
3208 /* Produce the same number of exponent digits
3209 as the native printf implementation. */
3210 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3211 { '%', '+', '.', '3', 'd', '\0' };
3213 { '%', '+', '.', '2', 'd', '\0' };
3215 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3221 static const char decimal_format[] =
3222 /* Produce the same number of exponent digits
3223 as the native printf implementation. */
3224 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3229 if (sizeof (DCHAR_T) == 1)
3231 sprintf ((char *) p, decimal_format, exponent);
3239 sprintf (expbuf, decimal_format, exponent);
3240 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3246 else if (dp->conversion == 'g' || dp->conversion == 'G')
3250 /* precision >= 1. */
3253 /* The exponent is 0, >= -4, < precision.
3254 Use fixed-point notation. */
3256 size_t ndigits = precision;
3257 /* Number of trailing zeroes that have to be
3260 (flags & FLAG_ALT ? 0 : precision - 1);
3264 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3266 *p++ = decimal_point_char ();
3267 while (ndigits > nzeroes)
3283 exponent = floorlog10 (arg);
3288 scale10_round_decimal_double (arg,
3289 (int)(precision - 1) - exponent);
3292 ndigits = strlen (digits);
3294 if (ndigits == precision)
3296 if (ndigits < precision - 1
3297 || ndigits > precision + 1)
3298 /* The exponent was not guessed
3299 precisely enough. */
3302 /* None of two values of exponent is
3303 the right one. Prevent an endless
3307 if (ndigits < precision)
3313 /* Here ndigits = precision. */
3315 /* Determine the number of trailing zeroes
3316 that have to be dropped. */
3318 if ((flags & FLAG_ALT) == 0)
3319 while (nzeroes < ndigits
3320 && digits[nzeroes] == '0')
3323 /* The exponent is now determined. */
3325 && exponent < (long)precision)
3327 /* Fixed-point notation:
3328 max(exponent,0)+1 digits, then the
3329 decimal point, then the remaining
3330 digits without trailing zeroes. */
3333 size_t count = exponent + 1;
3334 /* Note: count <= precision = ndigits. */
3335 for (; count > 0; count--)
3336 *p++ = digits[--ndigits];
3337 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3339 *p++ = decimal_point_char ();
3340 while (ndigits > nzeroes)
3343 *p++ = digits[ndigits];
3349 size_t count = -exponent - 1;
3351 *p++ = decimal_point_char ();
3352 for (; count > 0; count--)
3354 while (ndigits > nzeroes)
3357 *p++ = digits[ndigits];
3363 /* Exponential notation. */
3364 *p++ = digits[--ndigits];
3365 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3367 *p++ = decimal_point_char ();
3368 while (ndigits > nzeroes)
3371 *p++ = digits[ndigits];
3374 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3375 # if WIDE_CHAR_VERSION
3377 static const wchar_t decimal_format[] =
3378 /* Produce the same number of exponent digits
3379 as the native printf implementation. */
3380 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3381 { '%', '+', '.', '3', 'd', '\0' };
3383 { '%', '+', '.', '2', 'd', '\0' };
3385 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3391 static const char decimal_format[] =
3392 /* Produce the same number of exponent digits
3393 as the native printf implementation. */
3394 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3399 if (sizeof (DCHAR_T) == 1)
3401 sprintf ((char *) p, decimal_format, exponent);
3409 sprintf (expbuf, decimal_format, exponent);
3410 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3423 /* arg is finite. */
3429 if (dp->conversion == 'f' || dp->conversion == 'F')
3432 if ((flags & FLAG_ALT) || precision > 0)
3434 *p++ = decimal_point_char ();
3435 for (; precision > 0; precision--)
3439 else if (dp->conversion == 'e' || dp->conversion == 'E')
3442 if ((flags & FLAG_ALT) || precision > 0)
3444 *p++ = decimal_point_char ();
3445 for (; precision > 0; precision--)
3448 *p++ = dp->conversion; /* 'e' or 'E' */
3450 /* Produce the same number of exponent digits as
3451 the native printf implementation. */
3452 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3458 else if (dp->conversion == 'g' || dp->conversion == 'G')
3461 if (flags & FLAG_ALT)
3464 (precision > 0 ? precision - 1 : 0);
3465 *p++ = decimal_point_char ();
3466 for (; ndigits > 0; --ndigits)
3478 /* The generated string now extends from tmp to p, with the
3479 zero padding insertion point being at pad_ptr. */
3480 if (has_width && p - tmp < width)
3482 size_t pad = width - (p - tmp);
3483 DCHAR_T *end = p + pad;
3485 if (flags & FLAG_LEFT)
3487 /* Pad with spaces on the right. */
3488 for (; pad > 0; pad--)
3491 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3493 /* Pad with zeroes. */
3498 for (; pad > 0; pad--)
3503 /* Pad with spaces on the left. */
3508 for (; pad > 0; pad--)
3516 size_t count = p - tmp;
3518 if (count >= tmp_length)
3519 /* tmp_length was incorrectly calculated - fix the
3523 /* Make room for the result. */
3524 if (count >= allocated - length)
3526 size_t n = xsum (length, count);
3528 ENSURE_ALLOCATION (n);
3531 /* Append the result. */
3532 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3541 arg_type type = a.arg[dp->arg_index].type;
3542 int flags = dp->flags;
3543 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3547 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3551 #if NEED_PRINTF_UNBOUNDED_PRECISION
3554 # define prec_ourselves 0
3556 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3559 # define pad_ourselves 0
3562 unsigned int prefix_count;
3566 TCHAR_T tmpbuf[700];
3570 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3573 if (dp->width_start != dp->width_end)
3575 if (dp->width_arg_index != ARG_NONE)
3579 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3581 arg = a.arg[dp->width_arg_index].a.a_int;
3584 /* "A negative field width is taken as a '-' flag
3585 followed by a positive field width." */
3587 width = (unsigned int) (-arg);
3594 const FCHAR_T *digitp = dp->width_start;
3597 width = xsum (xtimes (width, 10), *digitp++ - '0');
3598 while (digitp != dp->width_end);
3604 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3607 if (dp->precision_start != dp->precision_end)
3609 if (dp->precision_arg_index != ARG_NONE)
3613 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3615 arg = a.arg[dp->precision_arg_index].a.a_int;
3616 /* "A negative precision is taken as if the precision
3626 const FCHAR_T *digitp = dp->precision_start + 1;
3629 while (digitp != dp->precision_end)
3630 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3637 /* Allocate a temporary buffer of sufficient size for calling
3640 switch (dp->conversion)
3643 case 'd': case 'i': case 'u':
3644 # if HAVE_LONG_LONG_INT
3645 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3647 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3648 * 0.30103 /* binary -> decimal */
3650 + 1; /* turn floor into ceil */
3653 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3655 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3656 * 0.30103 /* binary -> decimal */
3658 + 1; /* turn floor into ceil */
3661 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3662 * 0.30103 /* binary -> decimal */
3664 + 1; /* turn floor into ceil */
3665 if (tmp_length < precision)
3666 tmp_length = precision;
3667 /* Multiply by 2, as an estimate for FLAG_GROUP. */
3668 tmp_length = xsum (tmp_length, tmp_length);
3669 /* Add 1, to account for a leading sign. */
3670 tmp_length = xsum (tmp_length, 1);
3674 # if HAVE_LONG_LONG_INT
3675 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3677 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3678 * 0.333334 /* binary -> octal */
3680 + 1; /* turn floor into ceil */
3683 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3685 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3686 * 0.333334 /* binary -> octal */
3688 + 1; /* turn floor into ceil */
3691 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3692 * 0.333334 /* binary -> octal */
3694 + 1; /* turn floor into ceil */
3695 if (tmp_length < precision)
3696 tmp_length = precision;
3697 /* Add 1, to account for a leading sign. */
3698 tmp_length = xsum (tmp_length, 1);
3702 # if HAVE_LONG_LONG_INT
3703 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3705 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3706 * 0.25 /* binary -> hexadecimal */
3708 + 1; /* turn floor into ceil */
3711 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3713 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3714 * 0.25 /* binary -> hexadecimal */
3716 + 1; /* turn floor into ceil */
3719 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3720 * 0.25 /* binary -> hexadecimal */
3722 + 1; /* turn floor into ceil */
3723 if (tmp_length < precision)
3724 tmp_length = precision;
3725 /* Add 2, to account for a leading sign or alternate form. */
3726 tmp_length = xsum (tmp_length, 2);
3730 if (type == TYPE_LONGDOUBLE)
3732 (unsigned int) (LDBL_MAX_EXP
3733 * 0.30103 /* binary -> decimal */
3734 * 2 /* estimate for FLAG_GROUP */
3736 + 1 /* turn floor into ceil */
3737 + 10; /* sign, decimal point etc. */
3740 (unsigned int) (DBL_MAX_EXP
3741 * 0.30103 /* binary -> decimal */
3742 * 2 /* estimate for FLAG_GROUP */
3744 + 1 /* turn floor into ceil */
3745 + 10; /* sign, decimal point etc. */
3746 tmp_length = xsum (tmp_length, precision);
3749 case 'e': case 'E': case 'g': case 'G':
3751 12; /* sign, decimal point, exponent etc. */
3752 tmp_length = xsum (tmp_length, precision);
3756 if (type == TYPE_LONGDOUBLE)
3758 (unsigned int) (LDBL_DIG
3759 * 0.831 /* decimal -> hexadecimal */
3761 + 1; /* turn floor into ceil */
3764 (unsigned int) (DBL_DIG
3765 * 0.831 /* decimal -> hexadecimal */
3767 + 1; /* turn floor into ceil */
3768 if (tmp_length < precision)
3769 tmp_length = precision;
3770 /* Account for sign, decimal point etc. */
3771 tmp_length = xsum (tmp_length, 12);
3775 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
3776 if (type == TYPE_WIDE_CHAR)
3777 tmp_length = MB_CUR_MAX;
3785 if (type == TYPE_WIDE_STRING)
3788 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
3790 # if !WIDE_CHAR_VERSION
3791 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
3796 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
3801 (unsigned int) (sizeof (void *) * CHAR_BIT
3802 * 0.25 /* binary -> hexadecimal */
3804 + 1 /* turn floor into ceil */
3805 + 2; /* account for leading 0x */
3812 # if ENABLE_UNISTDIO
3813 /* Padding considers the number of characters, therefore the
3814 number of elements after padding may be
3815 > max (tmp_length, width)
3817 <= tmp_length + width. */
3818 tmp_length = xsum (tmp_length, width);
3820 /* Padding considers the number of elements, says POSIX. */
3821 if (tmp_length < width)
3825 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3828 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
3832 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
3834 if (size_overflow_p (tmp_memsize))
3835 /* Overflow, would lead to out of memory. */
3837 tmp = (TCHAR_T *) malloc (tmp_memsize);
3839 /* Out of memory. */
3844 /* Decide whether to handle the precision ourselves. */
3845 #if NEED_PRINTF_UNBOUNDED_PRECISION
3846 switch (dp->conversion)
3848 case 'd': case 'i': case 'u':
3850 case 'x': case 'X': case 'p':
3851 prec_ourselves = has_precision && (precision > 0);
3859 /* Decide whether to perform the padding ourselves. */
3860 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3861 switch (dp->conversion)
3863 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
3864 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
3865 to perform the padding after this conversion. Functions
3866 with unistdio extensions perform the padding based on
3867 character count rather than element count. */
3870 # if NEED_PRINTF_FLAG_ZERO
3871 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
3877 pad_ourselves = prec_ourselves;
3882 /* Construct the format string for calling snprintf or
3886 #if NEED_PRINTF_FLAG_GROUPING
3887 /* The underlying implementation doesn't support the ' flag.
3888 Produce no grouping characters in this case; this is
3889 acceptable because the grouping is locale dependent. */
3891 if (flags & FLAG_GROUP)
3894 if (flags & FLAG_LEFT)
3896 if (flags & FLAG_SHOWSIGN)
3898 if (flags & FLAG_SPACE)
3900 if (flags & FLAG_ALT)
3904 if (flags & FLAG_ZERO)
3906 if (dp->width_start != dp->width_end)
3908 size_t n = dp->width_end - dp->width_start;
3909 /* The width specification is known to consist only
3910 of standard ASCII characters. */
3911 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
3913 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
3918 const FCHAR_T *mp = dp->width_start;
3920 *fbp++ = (unsigned char) *mp++;
3925 if (!prec_ourselves)
3927 if (dp->precision_start != dp->precision_end)
3929 size_t n = dp->precision_end - dp->precision_start;
3930 /* The precision specification is known to consist only
3931 of standard ASCII characters. */
3932 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
3934 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
3939 const FCHAR_T *mp = dp->precision_start;
3941 *fbp++ = (unsigned char) *mp++;
3949 #if HAVE_LONG_LONG_INT
3950 case TYPE_LONGLONGINT:
3951 case TYPE_ULONGLONGINT:
3952 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3965 case TYPE_WIDE_CHAR:
3968 case TYPE_WIDE_STRING:
3972 case TYPE_LONGDOUBLE:
3978 #if NEED_PRINTF_DIRECTIVE_F
3979 if (dp->conversion == 'F')
3983 *fbp = dp->conversion;
3985 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3))
3990 /* On glibc2 systems from glibc >= 2.3 - probably also older
3991 ones - we know that snprintf's returns value conforms to
3992 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
3993 Therefore we can avoid using %n in this situation.
3994 On glibc2 systems from 2004-10-18 or newer, the use of %n
3995 in format strings in writable memory may crash the program
3996 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
3997 in this situation. */
4004 /* Construct the arguments for calling snprintf or sprintf. */
4006 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4008 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4010 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4012 if (dp->precision_arg_index != ARG_NONE)
4014 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4016 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4020 /* The SNPRINTF result is appended after result[0..length].
4021 The latter is an array of DCHAR_T; SNPRINTF appends an
4022 array of TCHAR_T to it. This is possible because
4023 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4024 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4025 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4026 /* Prepare checking whether snprintf returns the count
4028 ENSURE_ALLOCATION (xsum (length, 1));
4029 *(TCHAR_T *) (result + length) = '\0';
4038 size_t maxlen = allocated - length;
4039 /* SNPRINTF can fail if its second argument is
4041 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4042 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4043 maxlen = maxlen * TCHARS_PER_DCHAR;
4044 # define SNPRINTF_BUF(arg) \
4045 switch (prefix_count) \
4048 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4053 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4055 prefixes[0], arg, &count); \
4058 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4060 prefixes[0], prefixes[1], arg, \
4067 # define SNPRINTF_BUF(arg) \
4068 switch (prefix_count) \
4071 count = sprintf (tmp, buf, arg); \
4074 count = sprintf (tmp, buf, prefixes[0], arg); \
4077 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4089 int arg = a.arg[dp->arg_index].a.a_schar;
4095 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4101 int arg = a.arg[dp->arg_index].a.a_short;
4107 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4113 int arg = a.arg[dp->arg_index].a.a_int;
4119 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4125 long int arg = a.arg[dp->arg_index].a.a_longint;
4131 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4135 #if HAVE_LONG_LONG_INT
4136 case TYPE_LONGLONGINT:
4138 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4142 case TYPE_ULONGLONGINT:
4144 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4151 double arg = a.arg[dp->arg_index].a.a_double;
4155 case TYPE_LONGDOUBLE:
4157 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4163 int arg = a.arg[dp->arg_index].a.a_char;
4168 case TYPE_WIDE_CHAR:
4170 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
4177 const char *arg = a.arg[dp->arg_index].a.a_string;
4182 case TYPE_WIDE_STRING:
4184 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
4191 void *arg = a.arg[dp->arg_index].a.a_pointer;
4200 /* Portability: Not all implementations of snprintf()
4201 are ISO C 99 compliant. Determine the number of
4202 bytes that snprintf() has produced or would have
4206 /* Verify that snprintf() has NUL-terminated its
4209 && ((TCHAR_T *) (result + length)) [count] != '\0')
4211 /* Portability hack. */
4212 if (retcount > count)
4217 /* snprintf() doesn't understand the '%n'
4221 /* Don't use the '%n' directive; instead, look
4222 at the snprintf() return value. */
4228 /* Look at the snprintf() return value. */
4231 /* HP-UX 10.20 snprintf() is doubly deficient:
4232 It doesn't understand the '%n' directive,
4233 *and* it returns -1 (rather than the length
4234 that would have been required) when the
4235 buffer is too small. */
4236 size_t bigger_need =
4237 xsum (xtimes (allocated, 2), 12);
4238 ENSURE_ALLOCATION (bigger_need);
4247 /* Attempt to handle failure. */
4250 if (!(result == resultbuf || result == NULL))
4252 if (buf_malloced != NULL)
4253 free (buf_malloced);
4260 /* Handle overflow of the allocated buffer.
4261 If such an overflow occurs, a C99 compliant snprintf()
4262 returns a count >= maxlen. However, a non-compliant
4263 snprintf() function returns only count = maxlen - 1. To
4264 cover both cases, test whether count >= maxlen - 1. */
4265 if ((unsigned int) count + 1 >= maxlen)
4267 /* If maxlen already has attained its allowed maximum,
4268 allocating more memory will not increase maxlen.
4269 Instead of looping, bail out. */
4270 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
4274 /* Need at least count * sizeof (TCHAR_T) bytes.
4275 But allocate proportionally, to avoid looping
4276 eternally if snprintf() reports a too small
4280 (count + TCHARS_PER_DCHAR - 1)
4281 / TCHARS_PER_DCHAR),
4282 xtimes (allocated, 2));
4284 ENSURE_ALLOCATION (n);
4290 #if NEED_PRINTF_UNBOUNDED_PRECISION
4293 /* Handle the precision. */
4296 (TCHAR_T *) (result + length);
4300 size_t prefix_count;
4304 /* Put the additional zeroes after the sign. */
4306 && (*prec_ptr == '-' || *prec_ptr == '+'
4307 || *prec_ptr == ' '))
4309 /* Put the additional zeroes after the 0x prefix if
4310 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
4312 && prec_ptr[0] == '0'
4313 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
4316 move = count - prefix_count;
4317 if (precision > move)
4319 /* Insert zeroes. */
4320 size_t insert = precision - move;
4326 (count + insert + TCHARS_PER_DCHAR - 1)
4327 / TCHARS_PER_DCHAR);
4328 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4329 ENSURE_ALLOCATION (n);
4330 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4331 prec_ptr = (TCHAR_T *) (result + length);
4334 prec_end = prec_ptr + count;
4335 prec_ptr += prefix_count;
4337 while (prec_end > prec_ptr)
4340 prec_end[insert] = prec_end[0];
4346 while (prec_end > prec_ptr);
4355 if (count >= tmp_length)
4356 /* tmp_length was incorrectly calculated - fix the
4361 /* Convert from TCHAR_T[] to DCHAR_T[]. */
4362 if (dp->conversion == 'c' || dp->conversion == 's')
4364 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
4366 The result string is not certainly ASCII. */
4367 const TCHAR_T *tmpsrc;
4370 /* This code assumes that TCHAR_T is 'char'. */
4371 typedef int TCHAR_T_verify
4372 [2 * (sizeof (TCHAR_T) == 1) - 1];
4374 tmpsrc = (TCHAR_T *) (result + length);
4380 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
4381 iconveh_question_mark,
4384 &tmpdst, &tmpdst_len)
4387 int saved_errno = errno;
4388 if (!(result == resultbuf || result == NULL))
4390 if (buf_malloced != NULL)
4391 free (buf_malloced);
4393 errno = saved_errno;
4396 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
4397 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
4403 /* The result string is ASCII.
4404 Simple 1:1 conversion. */
4406 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
4407 no-op conversion, in-place on the array starting
4408 at (result + length). */
4409 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
4412 const TCHAR_T *tmpsrc;
4417 if (result == resultbuf)
4419 tmpsrc = (TCHAR_T *) (result + length);
4420 /* ENSURE_ALLOCATION will not move tmpsrc
4421 (because it's part of resultbuf). */
4422 ENSURE_ALLOCATION (xsum (length, count));
4426 /* ENSURE_ALLOCATION will move the array
4427 (because it uses realloc(). */
4428 ENSURE_ALLOCATION (xsum (length, count));
4429 tmpsrc = (TCHAR_T *) (result + length);
4433 ENSURE_ALLOCATION (xsum (length, count));
4435 tmpdst = result + length;
4436 /* Copy backwards, because of overlapping. */
4439 for (n = count; n > 0; n--)
4440 *--tmpdst = (unsigned char) *--tmpsrc;
4445 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4446 /* Make room for the result. */
4447 if (count > allocated - length)
4449 /* Need at least count elements. But allocate
4452 xmax (xsum (length, count), xtimes (allocated, 2));
4454 ENSURE_ALLOCATION (n);
4458 /* Here count <= allocated - length. */
4460 /* Perform padding. */
4461 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4462 if (pad_ourselves && has_width)
4465 # if ENABLE_UNISTDIO
4466 /* Outside POSIX, it's preferrable to compare the width
4467 against the number of _characters_ of the converted
4469 w = DCHAR_MBSNLEN (result + length, count);
4471 /* The width is compared against the number of _bytes_
4472 of the converted value, says POSIX. */
4477 size_t pad = width - w;
4479 /* Make room for the result. */
4480 if (xsum (count, pad) > allocated - length)
4482 /* Need at least count + pad elements. But
4483 allocate proportionally. */
4485 xmax (xsum3 (length, count, pad),
4486 xtimes (allocated, 2));
4489 ENSURE_ALLOCATION (n);
4492 /* Here count + pad <= allocated - length. */
4495 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
4496 DCHAR_T * const rp = result + length;
4498 DCHAR_T * const rp = tmp;
4500 DCHAR_T *p = rp + count;
4501 DCHAR_T *end = p + pad;
4502 # if NEED_PRINTF_FLAG_ZERO
4504 # if !DCHAR_IS_TCHAR
4505 if (dp->conversion == 'c'
4506 || dp->conversion == 's')
4507 /* No zero-padding for string directives. */
4512 pad_ptr = (*rp == '-' ? rp + 1 : rp);
4513 /* No zero-padding of "inf" and "nan". */
4514 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
4515 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
4519 /* The generated string now extends from rp to p,
4520 with the zero padding insertion point being at
4523 count = count + pad; /* = end - rp */
4525 if (flags & FLAG_LEFT)
4527 /* Pad with spaces on the right. */
4528 for (; pad > 0; pad--)
4531 # if NEED_PRINTF_FLAG_ZERO
4532 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4534 /* Pad with zeroes. */
4539 for (; pad > 0; pad--)
4545 /* Pad with spaces on the left. */
4550 for (; pad > 0; pad--)
4558 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4559 if (count >= tmp_length)
4560 /* tmp_length was incorrectly calculated - fix the
4565 /* Here still count <= allocated - length. */
4567 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
4568 /* The snprintf() result did fit. */
4570 /* Append the sprintf() result. */
4571 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4578 #if NEED_PRINTF_DIRECTIVE_F
4579 if (dp->conversion == 'F')
4581 /* Convert the %f result to upper case for %F. */
4582 DCHAR_T *rp = result + length;
4584 for (rc = count; rc > 0; rc--, rp++)
4585 if (*rp >= 'a' && *rp <= 'z')
4586 *rp = *rp - 'a' + 'A';
4597 /* Add the final NUL. */
4598 ENSURE_ALLOCATION (xsum (length, 1));
4599 result[length] = '\0';
4601 if (result != resultbuf && length + 1 < allocated)
4603 /* Shrink the allocated memory if possible. */
4606 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
4611 if (buf_malloced != NULL)
4612 free (buf_malloced);
4615 /* Note that we can produce a big string of a length > INT_MAX. POSIX
4616 says that snprintf() fails with errno = EOVERFLOW in this case, but
4617 that's only because snprintf() returns an 'int'. This function does
4618 not have this limitation. */
4622 if (!(result == resultbuf || result == NULL))
4624 if (buf_malloced != NULL)
4625 free (buf_malloced);
4631 if (!(result == resultbuf || result == NULL))
4633 if (buf_malloced != NULL)
4634 free (buf_malloced);
4642 #undef TCHARS_PER_DCHAR
4649 #undef DCHAR_IS_TCHAR