1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2009 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
98 # include "isnand-nolibm.h"
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
109 # include "isnand-nolibm.h"
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 /* Default parameters. */
122 # if WIDE_CHAR_VERSION
123 # define VASNPRINTF vasnwprintf
124 # define FCHAR_T wchar_t
125 # define DCHAR_T wchar_t
126 # define TCHAR_T wchar_t
127 # define DCHAR_IS_TCHAR 1
128 # define DIRECTIVE wchar_t_directive
129 # define DIRECTIVES wchar_t_directives
130 # define PRINTF_PARSE wprintf_parse
131 # define DCHAR_CPY wmemcpy
132 # define DCHAR_SET wmemset
134 # define VASNPRINTF vasnprintf
135 # define FCHAR_T char
136 # define DCHAR_T char
137 # define TCHAR_T char
138 # define DCHAR_IS_TCHAR 1
139 # define DIRECTIVE char_directive
140 # define DIRECTIVES char_directives
141 # define PRINTF_PARSE printf_parse
142 # define DCHAR_CPY memcpy
143 # define DCHAR_SET memset
146 #if WIDE_CHAR_VERSION
147 /* TCHAR_T is wchar_t. */
148 # define USE_SNPRINTF 1
149 # if HAVE_DECL__SNWPRINTF
150 /* On Windows, the function swprintf() has a different signature than
151 on Unix; we use the _snwprintf() function instead. */
152 # define SNPRINTF _snwprintf
155 # define SNPRINTF swprintf
158 /* TCHAR_T is char. */
159 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
160 But don't use it on BeOS, since BeOS snprintf produces no output if the
161 size argument is >= 0x3000000.
162 Also don't use it on Linux libc5, since there snprintf with size = 1
163 writes any output without bounds, like sprintf. */
164 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
165 # define USE_SNPRINTF 1
167 # define USE_SNPRINTF 0
169 # if HAVE_DECL__SNPRINTF
171 # define SNPRINTF _snprintf
174 # define SNPRINTF snprintf
175 /* Here we need to call the native snprintf, not rpl_snprintf. */
179 /* Here we need to call the native sprintf, not rpl_sprintf. */
182 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
183 warnings in this file. Use -Dlint to suppress them. */
185 # define IF_LINT(Code) Code
187 # define IF_LINT(Code) /* empty */
190 /* Avoid some warnings from "gcc -Wshadow".
191 This file doesn't use the exp() and remainder() functions. */
195 #define remainder rem
197 #if !USE_SNPRINTF && !WIDE_CHAR_VERSION
198 # if (HAVE_STRNLEN && !defined _AIX)
199 # define local_strnlen strnlen
201 # ifndef local_strnlen_defined
202 # define local_strnlen_defined 1
204 local_strnlen (const char *string, size_t maxlen)
206 const char *end = memchr (string, '\0', maxlen);
207 return end ? (size_t) (end - string) : maxlen;
213 #if (!USE_SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T && (WIDE_CHAR_VERSION || DCHAR_IS_TCHAR)
215 # define local_wcslen wcslen
217 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
218 a dependency towards this library, here is a local substitute.
219 Define this substitute only once, even if this file is included
220 twice in the same compilation unit. */
221 # ifndef local_wcslen_defined
222 # define local_wcslen_defined 1
224 local_wcslen (const wchar_t *s)
228 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
236 #if !USE_SNPRINTF && HAVE_WCHAR_T && WIDE_CHAR_VERSION
238 # define local_wcsnlen wcsnlen
240 # ifndef local_wcsnlen_defined
241 # define local_wcsnlen_defined 1
243 local_wcsnlen (const wchar_t *s, size_t maxlen)
247 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
255 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
256 /* Determine the decimal-point character according to the current locale. */
257 # ifndef decimal_point_char_defined
258 # define decimal_point_char_defined 1
260 decimal_point_char ()
263 /* Determine it in a multithread-safe way. We know nl_langinfo is
264 multithread-safe on glibc systems, but is not required to be multithread-
265 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
266 is rarely multithread-safe. */
267 # if HAVE_NL_LANGINFO && __GLIBC__
268 point = nl_langinfo (RADIXCHAR);
271 sprintf (pointbuf, "%#.0f", 1.0);
272 point = &pointbuf[1];
274 point = localeconv () -> decimal_point;
276 /* The decimal point is always a single byte: either '.' or ','. */
277 return (point[0] != '\0' ? point[0] : '.');
282 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
284 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
286 is_infinite_or_zero (double x)
288 return isnand (x) || x + x == x;
293 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
295 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
297 is_infinite_or_zerol (long double x)
299 return isnanl (x) || x + x == x;
304 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
306 /* Converting 'long double' to decimal without rare rounding bugs requires
307 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
308 (and slower) algorithms. */
310 typedef unsigned int mp_limb_t;
311 # define GMP_LIMB_BITS 32
312 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
314 typedef unsigned long long mp_twolimb_t;
315 # define GMP_TWOLIMB_BITS 64
316 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
318 /* Representation of a bignum >= 0. */
322 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
325 /* Compute the product of two bignums >= 0.
326 Return the allocated memory in case of success, NULL in case of memory
327 allocation failure. */
329 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
336 if (src1.nlimbs <= src2.nlimbs)
350 /* Now 0 <= len1 <= len2. */
353 /* src1 or src2 is zero. */
355 dest->limbs = (mp_limb_t *) malloc (1);
359 /* Here 1 <= len1 <= len2. */
365 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
368 for (k = len2; k > 0; )
370 for (i = 0; i < len1; i++)
372 mp_limb_t digit1 = p1[i];
373 mp_twolimb_t carry = 0;
374 for (j = 0; j < len2; j++)
376 mp_limb_t digit2 = p2[j];
377 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
379 dp[i + j] = (mp_limb_t) carry;
380 carry = carry >> GMP_LIMB_BITS;
382 dp[i + len2] = (mp_limb_t) carry;
385 while (dlen > 0 && dp[dlen - 1] == 0)
393 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
394 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
396 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
398 Return the allocated memory in case of success, NULL in case of memory
399 allocation failure. */
401 divide (mpn_t a, mpn_t b, mpn_t *q)
404 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
405 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
406 If m<n, then q:=0 and r:=a.
407 If m>=n=1, perform a single-precision division:
410 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
411 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
412 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
413 Normalise [q[m-1],...,q[0]], yields q.
414 If m>=n>1, perform a multiple-precision division:
415 We have a/b < beta^(m-n+1).
416 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
417 Shift a and b left by s bits, copying them. r:=a.
418 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
419 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
421 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
422 In case of overflow (q* >= beta) set q* := beta-1.
423 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
424 and c3 := b[n-2] * q*.
425 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
426 occurred. Furthermore 0 <= c3 < beta^2.
427 If there was overflow and
428 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
429 the next test can be skipped.}
430 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
431 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
433 Put r := r - b * q* * beta^j. In detail:
434 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
435 hence: u:=0, for i:=0 to n-1 do
437 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
438 u:=u div beta (+ 1, if carry in subtraction)
440 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
442 the carry u does not overflow.}
443 If a negative carry occurs, put q* := q* - 1
444 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
446 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
447 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
449 The room for q[j] can be allocated at the memory location of r[n+j].
450 Finally, round-to-even:
451 Shift r left by 1 bit.
452 If r > b or if r = b and q[0] is odd, q := q+1.
454 const mp_limb_t *a_ptr = a.limbs;
455 size_t a_len = a.nlimbs;
456 const mp_limb_t *b_ptr = b.limbs;
457 size_t b_len = b.nlimbs;
459 mp_limb_t *tmp_roomptr = NULL;
465 /* Allocate room for a_len+2 digits.
466 (Need a_len+1 digits for the real division and 1 more digit for the
467 final rounding of q.) */
468 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
473 while (a_len > 0 && a_ptr[a_len - 1] == 0)
480 /* Division by zero. */
482 if (b_ptr[b_len - 1] == 0)
488 /* Here m = a_len >= 0 and n = b_len > 0. */
492 /* m<n: trivial case. q=0, r := copy of a. */
495 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
496 q_ptr = roomptr + a_len;
501 /* n=1: single precision division.
502 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
506 mp_limb_t den = b_ptr[0];
507 mp_limb_t remainder = 0;
508 const mp_limb_t *sourceptr = a_ptr + a_len;
509 mp_limb_t *destptr = q_ptr + a_len;
511 for (count = a_len; count > 0; count--)
514 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
515 *--destptr = num / den;
516 remainder = num % den;
518 /* Normalise and store r. */
521 r_ptr[0] = remainder;
528 if (q_ptr[q_len - 1] == 0)
534 /* n>1: multiple precision division.
535 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
536 beta^(m-n-1) <= a/b < beta^(m-n+1). */
540 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
568 /* 0 <= s < GMP_LIMB_BITS.
569 Copy b, shifting it left by s bits. */
572 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
573 if (tmp_roomptr == NULL)
579 const mp_limb_t *sourceptr = b_ptr;
580 mp_limb_t *destptr = tmp_roomptr;
581 mp_twolimb_t accu = 0;
583 for (count = b_len; count > 0; count--)
585 accu += (mp_twolimb_t) *sourceptr++ << s;
586 *destptr++ = (mp_limb_t) accu;
587 accu = accu >> GMP_LIMB_BITS;
589 /* accu must be zero, since that was how s was determined. */
595 /* Copy a, shifting it left by s bits, yields r.
597 At the beginning: r = roomptr[0..a_len],
598 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
602 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
607 const mp_limb_t *sourceptr = a_ptr;
608 mp_limb_t *destptr = r_ptr;
609 mp_twolimb_t accu = 0;
611 for (count = a_len; count > 0; count--)
613 accu += (mp_twolimb_t) *sourceptr++ << s;
614 *destptr++ = (mp_limb_t) accu;
615 accu = accu >> GMP_LIMB_BITS;
617 *destptr++ = (mp_limb_t) accu;
619 q_ptr = roomptr + b_len;
620 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
622 size_t j = a_len - b_len; /* m-n */
623 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
624 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
625 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
626 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
627 /* Division loop, traversed m-n+1 times.
628 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
633 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
635 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
637 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
638 | r_ptr[j + b_len - 1];
639 q_star = num / b_msd;
644 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
645 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
646 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
647 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
648 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
650 If yes, jump directly to the subtraction loop.
651 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
652 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
653 if (r_ptr[j + b_len] > b_msd
654 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
655 /* r[j+n] >= b[n-1]+1 or
656 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
661 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
663 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
664 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
665 mp_twolimb_t c3 = /* b[n-2] * q* */
666 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
667 /* While c2 < c3, increase c2 and decrease c3.
668 Consider c3-c2. While it is > 0, decrease it by
669 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
670 this can happen only twice. */
673 q_star = q_star - 1; /* q* := q* - 1 */
674 if (c3 - c2 > b_msdd)
675 q_star = q_star - 1; /* q* := q* - 1 */
681 /* Subtract r := r - b * q* * beta^j. */
684 const mp_limb_t *sourceptr = b_ptr;
685 mp_limb_t *destptr = r_ptr + j;
686 mp_twolimb_t carry = 0;
688 for (count = b_len; count > 0; count--)
690 /* Here 0 <= carry <= q*. */
693 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
694 + (mp_limb_t) ~(*destptr);
695 /* Here 0 <= carry <= beta*q* + beta-1. */
696 *destptr++ = ~(mp_limb_t) carry;
697 carry = carry >> GMP_LIMB_BITS; /* <= q* */
699 cr = (mp_limb_t) carry;
701 /* Subtract cr from r_ptr[j + b_len], then forget about
703 if (cr > r_ptr[j + b_len])
705 /* Subtraction gave a carry. */
706 q_star = q_star - 1; /* q* := q* - 1 */
709 const mp_limb_t *sourceptr = b_ptr;
710 mp_limb_t *destptr = r_ptr + j;
713 for (count = b_len; count > 0; count--)
715 mp_limb_t source1 = *sourceptr++;
716 mp_limb_t source2 = *destptr;
717 *destptr++ = source1 + source2 + carry;
720 ? source1 >= (mp_limb_t) ~source2
721 : source1 > (mp_limb_t) ~source2);
724 /* Forget about the carry and about r[j+n]. */
727 /* q* is determined. Store it as q[j]. */
736 if (q_ptr[q_len - 1] == 0)
738 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
739 b is shifted left by s bits. */
740 /* Shift r right by s bits. */
743 mp_limb_t ptr = r_ptr + r_len;
744 mp_twolimb_t accu = 0;
746 for (count = r_len; count > 0; count--)
748 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
749 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
750 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
755 while (r_len > 0 && r_ptr[r_len - 1] == 0)
758 /* Compare r << 1 with b. */
766 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
767 | (i < r_len ? r_ptr[i] << 1 : 0);
768 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
778 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
783 for (i = 0; i < q_len; i++)
784 if (++(q_ptr[i]) != 0)
789 if (tmp_roomptr != NULL)
796 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
798 Destroys the contents of a.
799 Return the allocated memory - containing the decimal digits in low-to-high
800 order, terminated with a NUL character - in case of success, NULL in case
801 of memory allocation failure. */
803 convert_to_decimal (mpn_t a, size_t extra_zeroes)
805 mp_limb_t *a_ptr = a.limbs;
806 size_t a_len = a.nlimbs;
807 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
808 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
809 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
813 for (; extra_zeroes > 0; extra_zeroes--)
817 /* Divide a by 10^9, in-place. */
818 mp_limb_t remainder = 0;
819 mp_limb_t *ptr = a_ptr + a_len;
821 for (count = a_len; count > 0; count--)
824 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
825 *ptr = num / 1000000000;
826 remainder = num % 1000000000;
828 /* Store the remainder as 9 decimal digits. */
829 for (count = 9; count > 0; count--)
831 *d_ptr++ = '0' + (remainder % 10);
832 remainder = remainder / 10;
835 if (a_ptr[a_len - 1] == 0)
838 /* Remove leading zeroes. */
839 while (d_ptr > c_ptr && d_ptr[-1] == '0')
841 /* But keep at least one zero. */
844 /* Terminate the string. */
850 # if NEED_PRINTF_LONG_DOUBLE
852 /* Assuming x is finite and >= 0:
853 write x as x = 2^e * m, where m is a bignum.
854 Return the allocated memory in case of success, NULL in case of memory
855 allocation failure. */
857 decode_long_double (long double x, int *ep, mpn_t *mp)
864 /* Allocate memory for result. */
865 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
866 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
869 /* Split into exponential part and mantissa. */
870 y = frexpl (x, &exp);
871 if (!(y >= 0.0L && y < 1.0L))
873 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
874 latter is an integer. */
875 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
876 I'm not sure whether it's safe to cast a 'long double' value between
877 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
878 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
880 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
881 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
884 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
887 if (!(y >= 0.0L && y < 1.0L))
889 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
892 if (!(y >= 0.0L && y < 1.0L))
894 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
899 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
902 if (!(y >= 0.0L && y < 1.0L))
904 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
908 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
911 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
914 if (!(y >= 0.0L && y < 1.0L))
916 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
919 if (!(y >= 0.0L && y < 1.0L))
921 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
923 #if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
929 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
932 *ep = exp - LDBL_MANT_BIT;
938 # if NEED_PRINTF_DOUBLE
940 /* Assuming x is finite and >= 0:
941 write x as x = 2^e * m, where m is a bignum.
942 Return the allocated memory in case of success, NULL in case of memory
943 allocation failure. */
945 decode_double (double x, int *ep, mpn_t *mp)
952 /* Allocate memory for result. */
953 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
954 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
957 /* Split into exponential part and mantissa. */
959 if (!(y >= 0.0 && y < 1.0))
961 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
962 latter is an integer. */
963 /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
964 I'm not sure whether it's safe to cast a 'double' value between
965 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
966 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
968 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
969 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
972 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
975 if (!(y >= 0.0 && y < 1.0))
977 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
980 if (!(y >= 0.0 && y < 1.0))
982 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
987 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
990 if (!(y >= 0.0 && y < 1.0))
992 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
996 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
999 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1002 if (!(y >= 0.0 && y < 1.0))
1004 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1007 if (!(y >= 0.0 && y < 1.0))
1009 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1014 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1017 *ep = exp - DBL_MANT_BIT;
1023 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1024 Returns the decimal representation of round (x * 10^n).
1025 Return the allocated memory - containing the decimal digits in low-to-high
1026 order, terminated with a NUL character - in case of success, NULL in case
1027 of memory allocation failure. */
1029 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1032 size_t extra_zeroes;
1035 mp_limb_t *pow5_ptr;
1037 unsigned int s_limbs;
1038 unsigned int s_bits;
1046 /* x = 2^e * m, hence
1047 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1048 = round (2^s * 5^n * m). */
1051 /* Factor out a common power of 10 if possible. */
1054 extra_zeroes = (s < n ? s : n);
1058 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1059 Before converting to decimal, we need to compute
1060 z = round (2^s * 5^n * m). */
1061 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1062 sign. 2.322 is slightly larger than log(5)/log(2). */
1063 abs_n = (n >= 0 ? n : -n);
1064 abs_s = (s >= 0 ? s : -s);
1065 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1066 + abs_s / GMP_LIMB_BITS + 1)
1067 * sizeof (mp_limb_t));
1068 if (pow5_ptr == NULL)
1073 /* Initialize with 1. */
1076 /* Multiply with 5^|n|. */
1079 static mp_limb_t const small_pow5[13 + 1] =
1081 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1082 48828125, 244140625, 1220703125
1085 for (n13 = 0; n13 <= abs_n; n13 += 13)
1087 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1089 mp_twolimb_t carry = 0;
1090 for (j = 0; j < pow5_len; j++)
1092 mp_limb_t digit2 = pow5_ptr[j];
1093 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1094 pow5_ptr[j] = (mp_limb_t) carry;
1095 carry = carry >> GMP_LIMB_BITS;
1098 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1101 s_limbs = abs_s / GMP_LIMB_BITS;
1102 s_bits = abs_s % GMP_LIMB_BITS;
1103 if (n >= 0 ? s >= 0 : s <= 0)
1105 /* Multiply with 2^|s|. */
1108 mp_limb_t *ptr = pow5_ptr;
1109 mp_twolimb_t accu = 0;
1111 for (count = pow5_len; count > 0; count--)
1113 accu += (mp_twolimb_t) *ptr << s_bits;
1114 *ptr++ = (mp_limb_t) accu;
1115 accu = accu >> GMP_LIMB_BITS;
1119 *ptr = (mp_limb_t) accu;
1126 for (count = pow5_len; count > 0;)
1129 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1131 for (count = s_limbs; count > 0;)
1134 pow5_ptr[count] = 0;
1136 pow5_len += s_limbs;
1138 pow5.limbs = pow5_ptr;
1139 pow5.nlimbs = pow5_len;
1142 /* Multiply m with pow5. No division needed. */
1143 z_memory = multiply (m, pow5, &z);
1147 /* Divide m by pow5 and round. */
1148 z_memory = divide (m, pow5, &z);
1153 pow5.limbs = pow5_ptr;
1154 pow5.nlimbs = pow5_len;
1158 Multiply m with pow5, then divide by 2^|s|. */
1162 tmp_memory = multiply (m, pow5, &numerator);
1163 if (tmp_memory == NULL)
1169 /* Construct 2^|s|. */
1171 mp_limb_t *ptr = pow5_ptr + pow5_len;
1173 for (i = 0; i < s_limbs; i++)
1175 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1176 denominator.limbs = ptr;
1177 denominator.nlimbs = s_limbs + 1;
1179 z_memory = divide (numerator, denominator, &z);
1185 Multiply m with 2^s, then divide by pow5. */
1188 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1189 * sizeof (mp_limb_t));
1190 if (num_ptr == NULL)
1197 mp_limb_t *destptr = num_ptr;
1200 for (i = 0; i < s_limbs; i++)
1205 const mp_limb_t *sourceptr = m.limbs;
1206 mp_twolimb_t accu = 0;
1208 for (count = m.nlimbs; count > 0; count--)
1210 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1211 *destptr++ = (mp_limb_t) accu;
1212 accu = accu >> GMP_LIMB_BITS;
1215 *destptr++ = (mp_limb_t) accu;
1219 const mp_limb_t *sourceptr = m.limbs;
1221 for (count = m.nlimbs; count > 0; count--)
1222 *destptr++ = *sourceptr++;
1224 numerator.limbs = num_ptr;
1225 numerator.nlimbs = destptr - num_ptr;
1227 z_memory = divide (numerator, pow5, &z);
1234 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1236 if (z_memory == NULL)
1238 digits = convert_to_decimal (z, extra_zeroes);
1243 # if NEED_PRINTF_LONG_DOUBLE
1245 /* Assuming x is finite and >= 0, and n is an integer:
1246 Returns the decimal representation of round (x * 10^n).
1247 Return the allocated memory - containing the decimal digits in low-to-high
1248 order, terminated with a NUL character - in case of success, NULL in case
1249 of memory allocation failure. */
1251 scale10_round_decimal_long_double (long double x, int n)
1255 void *memory = decode_long_double (x, &e, &m);
1256 return scale10_round_decimal_decoded (e, m, memory, n);
1261 # if NEED_PRINTF_DOUBLE
1263 /* Assuming x is finite and >= 0, and n is an integer:
1264 Returns the decimal representation of round (x * 10^n).
1265 Return the allocated memory - containing the decimal digits in low-to-high
1266 order, terminated with a NUL character - in case of success, NULL in case
1267 of memory allocation failure. */
1269 scale10_round_decimal_double (double x, int n)
1273 void *memory = decode_double (x, &e, &m);
1274 return scale10_round_decimal_decoded (e, m, memory, n);
1279 # if NEED_PRINTF_LONG_DOUBLE
1281 /* Assuming x is finite and > 0:
1282 Return an approximation for n with 10^n <= x < 10^(n+1).
1283 The approximation is usually the right n, but may be off by 1 sometimes. */
1285 floorlog10l (long double x)
1292 /* Split into exponential part and mantissa. */
1293 y = frexpl (x, &exp);
1294 if (!(y >= 0.0L && y < 1.0L))
1300 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1302 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1303 exp -= GMP_LIMB_BITS;
1305 if (y < (1.0L / (1 << 16)))
1307 y *= 1.0L * (1 << 16);
1310 if (y < (1.0L / (1 << 8)))
1312 y *= 1.0L * (1 << 8);
1315 if (y < (1.0L / (1 << 4)))
1317 y *= 1.0L * (1 << 4);
1320 if (y < (1.0L / (1 << 2)))
1322 y *= 1.0L * (1 << 2);
1325 if (y < (1.0L / (1 << 1)))
1327 y *= 1.0L * (1 << 1);
1331 if (!(y >= 0.5L && y < 1.0L))
1333 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1336 if (z < 0.70710678118654752444)
1338 z *= 1.4142135623730950488;
1341 if (z < 0.8408964152537145431)
1343 z *= 1.1892071150027210667;
1346 if (z < 0.91700404320467123175)
1348 z *= 1.0905077326652576592;
1351 if (z < 0.9576032806985736469)
1353 z *= 1.0442737824274138403;
1356 /* Now 0.95 <= z <= 1.01. */
1358 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1359 Four terms are enough to get an approximation with error < 10^-7. */
1360 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1361 /* Finally multiply with log(2)/log(10), yields an approximation for
1363 l *= 0.30102999566398119523;
1364 /* Round down to the next integer. */
1365 return (int) l + (l < 0 ? -1 : 0);
1370 # if NEED_PRINTF_DOUBLE
1372 /* Assuming x is finite and > 0:
1373 Return an approximation for n with 10^n <= x < 10^(n+1).
1374 The approximation is usually the right n, but may be off by 1 sometimes. */
1376 floorlog10 (double x)
1383 /* Split into exponential part and mantissa. */
1384 y = frexp (x, &exp);
1385 if (!(y >= 0.0 && y < 1.0))
1391 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1393 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1394 exp -= GMP_LIMB_BITS;
1396 if (y < (1.0 / (1 << 16)))
1398 y *= 1.0 * (1 << 16);
1401 if (y < (1.0 / (1 << 8)))
1403 y *= 1.0 * (1 << 8);
1406 if (y < (1.0 / (1 << 4)))
1408 y *= 1.0 * (1 << 4);
1411 if (y < (1.0 / (1 << 2)))
1413 y *= 1.0 * (1 << 2);
1416 if (y < (1.0 / (1 << 1)))
1418 y *= 1.0 * (1 << 1);
1422 if (!(y >= 0.5 && y < 1.0))
1424 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1427 if (z < 0.70710678118654752444)
1429 z *= 1.4142135623730950488;
1432 if (z < 0.8408964152537145431)
1434 z *= 1.1892071150027210667;
1437 if (z < 0.91700404320467123175)
1439 z *= 1.0905077326652576592;
1442 if (z < 0.9576032806985736469)
1444 z *= 1.0442737824274138403;
1447 /* Now 0.95 <= z <= 1.01. */
1449 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1450 Four terms are enough to get an approximation with error < 10^-7. */
1451 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1452 /* Finally multiply with log(2)/log(10), yields an approximation for
1454 l *= 0.30102999566398119523;
1455 /* Round down to the next integer. */
1456 return (int) l + (l < 0 ? -1 : 0);
1461 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1462 a single '1' digit. */
1464 is_borderline (const char *digits, size_t precision)
1466 for (; precision > 0; precision--, digits++)
1472 return *digits == '\0';
1478 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1479 const FCHAR_T *format, va_list args)
1484 if (PRINTF_PARSE (format, &d, &a) < 0)
1485 /* errno is already set. */
1493 if (PRINTF_FETCHARGS (args, &a) < 0)
1501 size_t buf_neededlength;
1503 TCHAR_T *buf_malloced;
1507 /* Output string accumulator. */
1512 /* Allocate a small buffer that will hold a directive passed to
1513 sprintf or snprintf. */
1515 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1517 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1519 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1520 buf_malloced = NULL;
1525 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1526 if (size_overflow_p (buf_memsize))
1527 goto out_of_memory_1;
1528 buf = (TCHAR_T *) malloc (buf_memsize);
1530 goto out_of_memory_1;
1534 if (resultbuf != NULL)
1537 allocated = *lengthp;
1546 result is either == resultbuf or == NULL or malloc-allocated.
1547 If length > 0, then result != NULL. */
1549 /* Ensures that allocated >= needed. Aborts through a jump to
1550 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1551 #define ENSURE_ALLOCATION(needed) \
1552 if ((needed) > allocated) \
1554 size_t memory_size; \
1557 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1558 if ((needed) > allocated) \
1559 allocated = (needed); \
1560 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1561 if (size_overflow_p (memory_size)) \
1562 goto out_of_memory; \
1563 if (result == resultbuf || result == NULL) \
1564 memory = (DCHAR_T *) malloc (memory_size); \
1566 memory = (DCHAR_T *) realloc (result, memory_size); \
1567 if (memory == NULL) \
1568 goto out_of_memory; \
1569 if (result == resultbuf && length > 0) \
1570 DCHAR_CPY (memory, result, length); \
1574 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1576 if (cp != dp->dir_start)
1578 size_t n = dp->dir_start - cp;
1579 size_t augmented_length = xsum (length, n);
1581 ENSURE_ALLOCATION (augmented_length);
1582 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1583 need that the format string contains only ASCII characters
1584 if FCHAR_T and DCHAR_T are not the same type. */
1585 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1587 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1588 length = augmented_length;
1593 result[length++] = (unsigned char) *cp++;
1600 /* Execute a single directive. */
1601 if (dp->conversion == '%')
1603 size_t augmented_length;
1605 if (!(dp->arg_index == ARG_NONE))
1607 augmented_length = xsum (length, 1);
1608 ENSURE_ALLOCATION (augmented_length);
1609 result[length] = '%';
1610 length = augmented_length;
1614 if (!(dp->arg_index != ARG_NONE))
1617 if (dp->conversion == 'n')
1619 switch (a.arg[dp->arg_index].type)
1621 case TYPE_COUNT_SCHAR_POINTER:
1622 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1624 case TYPE_COUNT_SHORT_POINTER:
1625 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1627 case TYPE_COUNT_INT_POINTER:
1628 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1630 case TYPE_COUNT_LONGINT_POINTER:
1631 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1633 #if HAVE_LONG_LONG_INT
1634 case TYPE_COUNT_LONGLONGINT_POINTER:
1635 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1643 /* The unistdio extensions. */
1644 else if (dp->conversion == 'U')
1646 arg_type type = a.arg[dp->arg_index].type;
1647 int flags = dp->flags;
1655 if (dp->width_start != dp->width_end)
1657 if (dp->width_arg_index != ARG_NONE)
1661 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1663 arg = a.arg[dp->width_arg_index].a.a_int;
1666 /* "A negative field width is taken as a '-' flag
1667 followed by a positive field width." */
1669 width = (unsigned int) (-arg);
1676 const FCHAR_T *digitp = dp->width_start;
1679 width = xsum (xtimes (width, 10), *digitp++ - '0');
1680 while (digitp != dp->width_end);
1687 if (dp->precision_start != dp->precision_end)
1689 if (dp->precision_arg_index != ARG_NONE)
1693 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1695 arg = a.arg[dp->precision_arg_index].a.a_int;
1696 /* "A negative precision is taken as if the precision
1706 const FCHAR_T *digitp = dp->precision_start + 1;
1709 while (digitp != dp->precision_end)
1710 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1717 case TYPE_U8_STRING:
1719 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1720 const uint8_t *arg_end;
1725 /* Use only PRECISION characters, from the left. */
1728 for (; precision > 0; precision--)
1730 int count = u8_strmblen (arg_end);
1735 if (!(result == resultbuf || result == NULL))
1737 if (buf_malloced != NULL)
1738 free (buf_malloced);
1749 /* Use the entire string, and count the number of
1755 int count = u8_strmblen (arg_end);
1760 if (!(result == resultbuf || result == NULL))
1762 if (buf_malloced != NULL)
1763 free (buf_malloced);
1774 /* Use the entire string. */
1775 arg_end = arg + u8_strlen (arg);
1776 /* The number of characters doesn't matter. */
1780 if (has_width && width > characters
1781 && !(dp->flags & FLAG_LEFT))
1783 size_t n = width - characters;
1784 ENSURE_ALLOCATION (xsum (length, n));
1785 DCHAR_SET (result + length, ' ', n);
1789 # if DCHAR_IS_UINT8_T
1791 size_t n = arg_end - arg;
1792 ENSURE_ALLOCATION (xsum (length, n));
1793 DCHAR_CPY (result + length, arg, n);
1798 DCHAR_T *converted = result + length;
1799 size_t converted_len = allocated - length;
1801 /* Convert from UTF-8 to locale encoding. */
1803 u8_conv_to_encoding (locale_charset (),
1804 iconveh_question_mark,
1805 arg, arg_end - arg, NULL,
1806 converted, &converted_len);
1808 /* Convert from UTF-8 to UTF-16/UTF-32. */
1810 U8_TO_DCHAR (arg, arg_end - arg,
1811 converted, &converted_len);
1813 if (converted == NULL)
1815 int saved_errno = errno;
1816 if (!(result == resultbuf || result == NULL))
1818 if (buf_malloced != NULL)
1819 free (buf_malloced);
1821 errno = saved_errno;
1824 if (converted != result + length)
1826 ENSURE_ALLOCATION (xsum (length, converted_len));
1827 DCHAR_CPY (result + length, converted, converted_len);
1830 length += converted_len;
1834 if (has_width && width > characters
1835 && (dp->flags & FLAG_LEFT))
1837 size_t n = width - characters;
1838 ENSURE_ALLOCATION (xsum (length, n));
1839 DCHAR_SET (result + length, ' ', n);
1845 case TYPE_U16_STRING:
1847 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1848 const uint16_t *arg_end;
1853 /* Use only PRECISION characters, from the left. */
1856 for (; precision > 0; precision--)
1858 int count = u16_strmblen (arg_end);
1863 if (!(result == resultbuf || result == NULL))
1865 if (buf_malloced != NULL)
1866 free (buf_malloced);
1877 /* Use the entire string, and count the number of
1883 int count = u16_strmblen (arg_end);
1888 if (!(result == resultbuf || result == NULL))
1890 if (buf_malloced != NULL)
1891 free (buf_malloced);
1902 /* Use the entire string. */
1903 arg_end = arg + u16_strlen (arg);
1904 /* The number of characters doesn't matter. */
1908 if (has_width && width > characters
1909 && !(dp->flags & FLAG_LEFT))
1911 size_t n = width - characters;
1912 ENSURE_ALLOCATION (xsum (length, n));
1913 DCHAR_SET (result + length, ' ', n);
1917 # if DCHAR_IS_UINT16_T
1919 size_t n = arg_end - arg;
1920 ENSURE_ALLOCATION (xsum (length, n));
1921 DCHAR_CPY (result + length, arg, n);
1926 DCHAR_T *converted = result + length;
1927 size_t converted_len = allocated - length;
1929 /* Convert from UTF-16 to locale encoding. */
1931 u16_conv_to_encoding (locale_charset (),
1932 iconveh_question_mark,
1933 arg, arg_end - arg, NULL,
1934 converted, &converted_len);
1936 /* Convert from UTF-16 to UTF-8/UTF-32. */
1938 U16_TO_DCHAR (arg, arg_end - arg,
1939 converted, &converted_len);
1941 if (converted == NULL)
1943 int saved_errno = errno;
1944 if (!(result == resultbuf || result == NULL))
1946 if (buf_malloced != NULL)
1947 free (buf_malloced);
1949 errno = saved_errno;
1952 if (converted != result + length)
1954 ENSURE_ALLOCATION (xsum (length, converted_len));
1955 DCHAR_CPY (result + length, converted, converted_len);
1958 length += converted_len;
1962 if (has_width && width > characters
1963 && (dp->flags & FLAG_LEFT))
1965 size_t n = width - characters;
1966 ENSURE_ALLOCATION (xsum (length, n));
1967 DCHAR_SET (result + length, ' ', n);
1973 case TYPE_U32_STRING:
1975 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1976 const uint32_t *arg_end;
1981 /* Use only PRECISION characters, from the left. */
1984 for (; precision > 0; precision--)
1986 int count = u32_strmblen (arg_end);
1991 if (!(result == resultbuf || result == NULL))
1993 if (buf_malloced != NULL)
1994 free (buf_malloced);
2005 /* Use the entire string, and count the number of
2011 int count = u32_strmblen (arg_end);
2016 if (!(result == resultbuf || result == NULL))
2018 if (buf_malloced != NULL)
2019 free (buf_malloced);
2030 /* Use the entire string. */
2031 arg_end = arg + u32_strlen (arg);
2032 /* The number of characters doesn't matter. */
2036 if (has_width && width > characters
2037 && !(dp->flags & FLAG_LEFT))
2039 size_t n = width - characters;
2040 ENSURE_ALLOCATION (xsum (length, n));
2041 DCHAR_SET (result + length, ' ', n);
2045 # if DCHAR_IS_UINT32_T
2047 size_t n = arg_end - arg;
2048 ENSURE_ALLOCATION (xsum (length, n));
2049 DCHAR_CPY (result + length, arg, n);
2054 DCHAR_T *converted = result + length;
2055 size_t converted_len = allocated - length;
2057 /* Convert from UTF-32 to locale encoding. */
2059 u32_conv_to_encoding (locale_charset (),
2060 iconveh_question_mark,
2061 arg, arg_end - arg, NULL,
2062 converted, &converted_len);
2064 /* Convert from UTF-32 to UTF-8/UTF-16. */
2066 U32_TO_DCHAR (arg, arg_end - arg,
2067 converted, &converted_len);
2069 if (converted == NULL)
2071 int saved_errno = errno;
2072 if (!(result == resultbuf || result == NULL))
2074 if (buf_malloced != NULL)
2075 free (buf_malloced);
2077 errno = saved_errno;
2080 if (converted != result + length)
2082 ENSURE_ALLOCATION (xsum (length, converted_len));
2083 DCHAR_CPY (result + length, converted, converted_len);
2086 length += converted_len;
2090 if (has_width && width > characters
2091 && (dp->flags & FLAG_LEFT))
2093 size_t n = width - characters;
2094 ENSURE_ALLOCATION (xsum (length, n));
2095 DCHAR_SET (result + length, ' ', n);
2106 #if (!USE_SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T
2107 else if (dp->conversion == 's'
2108 # if WIDE_CHAR_VERSION
2109 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2111 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2115 /* The normal handling of the 's' directive below requires
2116 allocating a temporary buffer. The determination of its
2117 length (tmp_length), in the case when a precision is
2118 specified, below requires a conversion between a char[]
2119 string and a wchar_t[] wide string. It could be done, but
2120 we have no guarantee that the implementation of sprintf will
2121 use the exactly same algorithm. Without this guarantee, it
2122 is possible to have buffer overrun bugs. In order to avoid
2123 such bugs, we implement the entire processing of the 's'
2124 directive ourselves. */
2125 int flags = dp->flags;
2133 if (dp->width_start != dp->width_end)
2135 if (dp->width_arg_index != ARG_NONE)
2139 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2141 arg = a.arg[dp->width_arg_index].a.a_int;
2144 /* "A negative field width is taken as a '-' flag
2145 followed by a positive field width." */
2147 width = (unsigned int) (-arg);
2154 const FCHAR_T *digitp = dp->width_start;
2157 width = xsum (xtimes (width, 10), *digitp++ - '0');
2158 while (digitp != dp->width_end);
2165 if (dp->precision_start != dp->precision_end)
2167 if (dp->precision_arg_index != ARG_NONE)
2171 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2173 arg = a.arg[dp->precision_arg_index].a.a_int;
2174 /* "A negative precision is taken as if the precision
2184 const FCHAR_T *digitp = dp->precision_start + 1;
2187 while (digitp != dp->precision_end)
2188 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2193 # if WIDE_CHAR_VERSION
2194 /* %s in vasnwprintf. See the specification of fwprintf. */
2196 const char *arg = a.arg[dp->arg_index].a.a_string;
2197 const char *arg_end;
2202 /* Use only as many bytes as needed to produce PRECISION
2203 wide characters, from the left. */
2206 memset (&state, '\0', sizeof (mbstate_t));
2210 for (; precision > 0; precision--)
2214 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2216 count = mblen (arg_end, MB_CUR_MAX);
2219 /* Found the terminating NUL. */
2223 /* Invalid or incomplete multibyte character. */
2224 if (!(result == resultbuf || result == NULL))
2226 if (buf_malloced != NULL)
2227 free (buf_malloced);
2238 /* Use the entire string, and count the number of wide
2242 memset (&state, '\0', sizeof (mbstate_t));
2250 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2252 count = mblen (arg_end, MB_CUR_MAX);
2255 /* Found the terminating NUL. */
2259 /* Invalid or incomplete multibyte character. */
2260 if (!(result == resultbuf || result == NULL))
2262 if (buf_malloced != NULL)
2263 free (buf_malloced);
2274 /* Use the entire string. */
2275 arg_end = arg + strlen (arg);
2276 /* The number of characters doesn't matter. */
2280 if (has_width && width > characters
2281 && !(dp->flags & FLAG_LEFT))
2283 size_t n = width - characters;
2284 ENSURE_ALLOCATION (xsum (length, n));
2285 DCHAR_SET (result + length, ' ', n);
2289 if (has_precision || has_width)
2291 /* We know the number of wide characters in advance. */
2295 memset (&state, '\0', sizeof (mbstate_t));
2297 ENSURE_ALLOCATION (xsum (length, characters));
2298 for (remaining = characters; remaining > 0; remaining--)
2303 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2305 count = mbtowc (&wc, arg, arg_end - arg);
2308 /* mbrtowc not consistent with mbrlen, or mbtowc
2309 not consistent with mblen. */
2311 result[length++] = wc;
2314 if (!(arg == arg_end))
2321 memset (&state, '\0', sizeof (mbstate_t));
2323 while (arg < arg_end)
2328 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2330 count = mbtowc (&wc, arg, arg_end - arg);
2333 /* mbrtowc not consistent with mbrlen, or mbtowc
2334 not consistent with mblen. */
2336 ENSURE_ALLOCATION (xsum (length, 1));
2337 result[length++] = wc;
2342 if (has_width && width > characters
2343 && (dp->flags & FLAG_LEFT))
2345 size_t n = width - characters;
2346 ENSURE_ALLOCATION (xsum (length, n));
2347 DCHAR_SET (result + length, ' ', n);
2352 /* %ls in vasnprintf. See the specification of fprintf. */
2354 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2355 const wchar_t *arg_end;
2357 # if !DCHAR_IS_TCHAR
2358 /* This code assumes that TCHAR_T is 'char'. */
2359 typedef int TCHAR_T_verify[2 * (sizeof (TCHAR_T) == 1) - 1];
2368 /* Use only as many wide characters as needed to produce
2369 at most PRECISION bytes, from the left. */
2372 memset (&state, '\0', sizeof (mbstate_t));
2376 while (precision > 0)
2378 char buf[64]; /* Assume MB_CUR_MAX <= 64. */
2382 /* Found the terminating null wide character. */
2385 count = wcrtomb (buf, *arg_end, &state);
2387 count = wctomb (buf, *arg_end);
2391 /* Cannot convert. */
2392 if (!(result == resultbuf || result == NULL))
2394 if (buf_malloced != NULL)
2395 free (buf_malloced);
2400 if (precision < count)
2403 characters += count;
2413 /* Use the entire string, and count the number of
2417 memset (&state, '\0', sizeof (mbstate_t));
2423 char buf[64]; /* Assume MB_CUR_MAX <= 64. */
2427 /* Found the terminating null wide character. */
2430 count = wcrtomb (buf, *arg_end, &state);
2432 count = wctomb (buf, *arg_end);
2436 /* Cannot convert. */
2437 if (!(result == resultbuf || result == NULL))
2439 if (buf_malloced != NULL)
2440 free (buf_malloced);
2446 characters += count;
2452 /* Use the entire string. */
2453 arg_end = arg + local_wcslen (arg);
2454 /* The number of bytes doesn't matter. */
2459 # if !DCHAR_IS_TCHAR
2460 /* Convert the string into a piece of temporary memory. */
2461 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2465 TCHAR_T *tmpptr = tmpsrc;
2469 memset (&state, '\0', sizeof (mbstate_t));
2471 for (remaining = characters; remaining > 0; )
2473 char buf[64]; /* Assume MB_CUR_MAX <= 64. */
2479 count = wcrtomb (buf, *arg, &state);
2481 count = wctomb (buf, *arg);
2484 /* Inconsistency. */
2486 memcpy (tmpptr, buf, count);
2491 if (!(arg == arg_end))
2495 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2497 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2498 iconveh_question_mark,
2504 int saved_errno = errno;
2506 if (!(result == resultbuf || result == NULL))
2508 if (buf_malloced != NULL)
2509 free (buf_malloced);
2511 errno = saved_errno;
2519 # if ENABLE_UNISTDIO
2520 /* Outside POSIX, it's preferrable to compare the width
2521 against the number of _characters_ of the converted
2523 w = DCHAR_MBSNLEN (result + length, characters);
2525 /* The width is compared against the number of _bytes_
2526 of the converted value, says POSIX. */
2531 /* w doesn't matter. */
2534 if (has_width && width > w
2535 && !(dp->flags & FLAG_LEFT))
2537 size_t n = width - w;
2538 ENSURE_ALLOCATION (xsum (length, n));
2539 DCHAR_SET (result + length, ' ', n);
2544 if (has_precision || has_width)
2546 /* We know the number of bytes in advance. */
2550 memset (&state, '\0', sizeof (mbstate_t));
2552 ENSURE_ALLOCATION (xsum (length, characters));
2553 for (remaining = characters; remaining > 0; )
2555 char buf[64]; /* Assume MB_CUR_MAX <= 64. */
2561 count = wcrtomb (buf, *arg, &state);
2563 count = wctomb (buf, *arg);
2566 /* Inconsistency. */
2568 memcpy (result + length, buf, count);
2573 if (!(arg == arg_end))
2580 memset (&state, '\0', sizeof (mbstate_t));
2582 while (arg < arg_end)
2584 char buf[64]; /* Assume MB_CUR_MAX <= 64. */
2590 count = wcrtomb (buf, *arg, &state);
2592 count = wctomb (buf, *arg);
2595 /* Inconsistency. */
2597 ENSURE_ALLOCATION (xsum (length, count));
2598 memcpy (result + length, buf, count);
2604 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2605 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2607 length += tmpdst_len;
2610 if (has_width && width > w
2611 && (dp->flags & FLAG_LEFT))
2613 size_t n = width - w;
2614 ENSURE_ALLOCATION (xsum (length, n));
2615 DCHAR_SET (result + length, ' ', n);
2622 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2623 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2624 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2626 # if NEED_PRINTF_DOUBLE
2627 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2629 # if NEED_PRINTF_LONG_DOUBLE
2630 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2636 arg_type type = a.arg[dp->arg_index].type;
2637 int flags = dp->flags;
2643 DCHAR_T tmpbuf[700];
2650 if (dp->width_start != dp->width_end)
2652 if (dp->width_arg_index != ARG_NONE)
2656 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2658 arg = a.arg[dp->width_arg_index].a.a_int;
2661 /* "A negative field width is taken as a '-' flag
2662 followed by a positive field width." */
2664 width = (unsigned int) (-arg);
2671 const FCHAR_T *digitp = dp->width_start;
2674 width = xsum (xtimes (width, 10), *digitp++ - '0');
2675 while (digitp != dp->width_end);
2682 if (dp->precision_start != dp->precision_end)
2684 if (dp->precision_arg_index != ARG_NONE)
2688 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2690 arg = a.arg[dp->precision_arg_index].a.a_int;
2691 /* "A negative precision is taken as if the precision
2701 const FCHAR_T *digitp = dp->precision_start + 1;
2704 while (digitp != dp->precision_end)
2705 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2710 /* Allocate a temporary buffer of sufficient size. */
2711 if (type == TYPE_LONGDOUBLE)
2713 (unsigned int) ((LDBL_DIG + 1)
2714 * 0.831 /* decimal -> hexadecimal */
2716 + 1; /* turn floor into ceil */
2719 (unsigned int) ((DBL_DIG + 1)
2720 * 0.831 /* decimal -> hexadecimal */
2722 + 1; /* turn floor into ceil */
2723 if (tmp_length < precision)
2724 tmp_length = precision;
2725 /* Account for sign, decimal point etc. */
2726 tmp_length = xsum (tmp_length, 12);
2728 if (tmp_length < width)
2731 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2733 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2737 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2739 if (size_overflow_p (tmp_memsize))
2740 /* Overflow, would lead to out of memory. */
2742 tmp = (DCHAR_T *) malloc (tmp_memsize);
2744 /* Out of memory. */
2750 if (type == TYPE_LONGDOUBLE)
2752 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2753 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2757 if (dp->conversion == 'A')
2759 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2763 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2769 DECL_LONG_DOUBLE_ROUNDING
2771 BEGIN_LONG_DOUBLE_ROUNDING ();
2773 if (signbit (arg)) /* arg < 0.0L or negative zero */
2781 else if (flags & FLAG_SHOWSIGN)
2783 else if (flags & FLAG_SPACE)
2786 if (arg > 0.0L && arg + arg == arg)
2788 if (dp->conversion == 'A')
2790 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2794 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2800 long double mantissa;
2803 mantissa = printf_frexpl (arg, &exponent);
2811 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2813 /* Round the mantissa. */
2814 long double tail = mantissa;
2817 for (q = precision; ; q--)
2819 int digit = (int) tail;
2823 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2832 for (q = precision; q > 0; q--)
2838 *p++ = dp->conversion - 'A' + 'X';
2843 digit = (int) mantissa;
2846 if ((flags & FLAG_ALT)
2847 || mantissa > 0.0L || precision > 0)
2849 *p++ = decimal_point_char ();
2850 /* This loop terminates because we assume
2851 that FLT_RADIX is a power of 2. */
2852 while (mantissa > 0.0L)
2855 digit = (int) mantissa;
2860 : dp->conversion - 10);
2864 while (precision > 0)
2871 *p++ = dp->conversion - 'A' + 'P';
2872 # if WIDE_CHAR_VERSION
2874 static const wchar_t decimal_format[] =
2875 { '%', '+', 'd', '\0' };
2876 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2881 if (sizeof (DCHAR_T) == 1)
2883 sprintf ((char *) p, "%+d", exponent);
2891 sprintf (expbuf, "%+d", exponent);
2892 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2898 END_LONG_DOUBLE_ROUNDING ();
2906 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2907 double arg = a.arg[dp->arg_index].a.a_double;
2911 if (dp->conversion == 'A')
2913 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2917 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2924 if (signbit (arg)) /* arg < 0.0 or negative zero */
2932 else if (flags & FLAG_SHOWSIGN)
2934 else if (flags & FLAG_SPACE)
2937 if (arg > 0.0 && arg + arg == arg)
2939 if (dp->conversion == 'A')
2941 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2945 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2954 mantissa = printf_frexp (arg, &exponent);
2962 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2964 /* Round the mantissa. */
2965 double tail = mantissa;
2968 for (q = precision; ; q--)
2970 int digit = (int) tail;
2974 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2983 for (q = precision; q > 0; q--)
2989 *p++ = dp->conversion - 'A' + 'X';
2994 digit = (int) mantissa;
2997 if ((flags & FLAG_ALT)
2998 || mantissa > 0.0 || precision > 0)
3000 *p++ = decimal_point_char ();
3001 /* This loop terminates because we assume
3002 that FLT_RADIX is a power of 2. */
3003 while (mantissa > 0.0)
3006 digit = (int) mantissa;
3011 : dp->conversion - 10);
3015 while (precision > 0)
3022 *p++ = dp->conversion - 'A' + 'P';
3023 # if WIDE_CHAR_VERSION
3025 static const wchar_t decimal_format[] =
3026 { '%', '+', 'd', '\0' };
3027 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3032 if (sizeof (DCHAR_T) == 1)
3034 sprintf ((char *) p, "%+d", exponent);
3042 sprintf (expbuf, "%+d", exponent);
3043 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3053 /* The generated string now extends from tmp to p, with the
3054 zero padding insertion point being at pad_ptr. */
3055 if (has_width && p - tmp < width)
3057 size_t pad = width - (p - tmp);
3058 DCHAR_T *end = p + pad;
3060 if (flags & FLAG_LEFT)
3062 /* Pad with spaces on the right. */
3063 for (; pad > 0; pad--)
3066 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3068 /* Pad with zeroes. */
3073 for (; pad > 0; pad--)
3078 /* Pad with spaces on the left. */
3083 for (; pad > 0; pad--)
3091 size_t count = p - tmp;
3093 if (count >= tmp_length)
3094 /* tmp_length was incorrectly calculated - fix the
3098 /* Make room for the result. */
3099 if (count >= allocated - length)
3101 size_t n = xsum (length, count);
3103 ENSURE_ALLOCATION (n);
3106 /* Append the result. */
3107 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3114 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3115 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3116 || dp->conversion == 'e' || dp->conversion == 'E'
3117 || dp->conversion == 'g' || dp->conversion == 'G'
3118 || dp->conversion == 'a' || dp->conversion == 'A')
3120 # if NEED_PRINTF_DOUBLE
3121 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3122 # elif NEED_PRINTF_INFINITE_DOUBLE
3123 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3124 /* The systems (mingw) which produce wrong output
3125 for Inf, -Inf, and NaN also do so for -0.0.
3126 Therefore we treat this case here as well. */
3127 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3129 # if NEED_PRINTF_LONG_DOUBLE
3130 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3131 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3132 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3133 /* Some systems produce wrong output for Inf,
3134 -Inf, and NaN. Some systems in this category
3135 (IRIX 5.3) also do so for -0.0. Therefore we
3136 treat this case here as well. */
3137 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3141 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3142 arg_type type = a.arg[dp->arg_index].type;
3144 int flags = dp->flags;
3150 DCHAR_T tmpbuf[700];
3157 if (dp->width_start != dp->width_end)
3159 if (dp->width_arg_index != ARG_NONE)
3163 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3165 arg = a.arg[dp->width_arg_index].a.a_int;
3168 /* "A negative field width is taken as a '-' flag
3169 followed by a positive field width." */
3171 width = (unsigned int) (-arg);
3178 const FCHAR_T *digitp = dp->width_start;
3181 width = xsum (xtimes (width, 10), *digitp++ - '0');
3182 while (digitp != dp->width_end);
3189 if (dp->precision_start != dp->precision_end)
3191 if (dp->precision_arg_index != ARG_NONE)
3195 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3197 arg = a.arg[dp->precision_arg_index].a.a_int;
3198 /* "A negative precision is taken as if the precision
3208 const FCHAR_T *digitp = dp->precision_start + 1;
3211 while (digitp != dp->precision_end)
3212 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3217 /* POSIX specifies the default precision to be 6 for %f, %F,
3218 %e, %E, but not for %g, %G. Implementations appear to use
3219 the same default precision also for %g, %G. But for %a, %A,
3220 the default precision is 0. */
3222 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3225 /* Allocate a temporary buffer of sufficient size. */
3226 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3227 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3228 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3229 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3230 # elif NEED_PRINTF_LONG_DOUBLE
3231 tmp_length = LDBL_DIG + 1;
3232 # elif NEED_PRINTF_DOUBLE
3233 tmp_length = DBL_DIG + 1;
3237 if (tmp_length < precision)
3238 tmp_length = precision;
3239 # if NEED_PRINTF_LONG_DOUBLE
3240 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3241 if (type == TYPE_LONGDOUBLE)
3243 if (dp->conversion == 'f' || dp->conversion == 'F')
3245 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3246 if (!(isnanl (arg) || arg + arg == arg))
3248 /* arg is finite and nonzero. */
3249 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3250 if (exponent >= 0 && tmp_length < exponent + precision)
3251 tmp_length = exponent + precision;
3255 # if NEED_PRINTF_DOUBLE
3256 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3257 if (type == TYPE_DOUBLE)
3259 if (dp->conversion == 'f' || dp->conversion == 'F')
3261 double arg = a.arg[dp->arg_index].a.a_double;
3262 if (!(isnand (arg) || arg + arg == arg))
3264 /* arg is finite and nonzero. */
3265 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3266 if (exponent >= 0 && tmp_length < exponent + precision)
3267 tmp_length = exponent + precision;
3271 /* Account for sign, decimal point etc. */
3272 tmp_length = xsum (tmp_length, 12);
3274 if (tmp_length < width)
3277 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3279 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3283 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3285 if (size_overflow_p (tmp_memsize))
3286 /* Overflow, would lead to out of memory. */
3288 tmp = (DCHAR_T *) malloc (tmp_memsize);
3290 /* Out of memory. */
3297 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3298 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3299 if (type == TYPE_LONGDOUBLE)
3302 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3306 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3308 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3312 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3318 DECL_LONG_DOUBLE_ROUNDING
3320 BEGIN_LONG_DOUBLE_ROUNDING ();
3322 if (signbit (arg)) /* arg < 0.0L or negative zero */
3330 else if (flags & FLAG_SHOWSIGN)
3332 else if (flags & FLAG_SPACE)
3335 if (arg > 0.0L && arg + arg == arg)
3337 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3339 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3343 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3348 # if NEED_PRINTF_LONG_DOUBLE
3351 if (dp->conversion == 'f' || dp->conversion == 'F')
3357 scale10_round_decimal_long_double (arg, precision);
3360 END_LONG_DOUBLE_ROUNDING ();
3363 ndigits = strlen (digits);
3365 if (ndigits > precision)
3369 *p++ = digits[ndigits];
3371 while (ndigits > precision);
3374 /* Here ndigits <= precision. */
3375 if ((flags & FLAG_ALT) || precision > 0)
3377 *p++ = decimal_point_char ();
3378 for (; precision > ndigits; precision--)
3383 *p++ = digits[ndigits];
3389 else if (dp->conversion == 'e' || dp->conversion == 'E')
3397 if ((flags & FLAG_ALT) || precision > 0)
3399 *p++ = decimal_point_char ();
3400 for (; precision > 0; precision--)
3411 exponent = floorlog10l (arg);
3416 scale10_round_decimal_long_double (arg,
3417 (int)precision - exponent);
3420 END_LONG_DOUBLE_ROUNDING ();
3423 ndigits = strlen (digits);
3425 if (ndigits == precision + 1)
3427 if (ndigits < precision
3428 || ndigits > precision + 2)
3429 /* The exponent was not guessed
3430 precisely enough. */
3433 /* None of two values of exponent is
3434 the right one. Prevent an endless
3438 if (ndigits == precision)
3444 /* Here ndigits = precision+1. */
3445 if (is_borderline (digits, precision))
3447 /* Maybe the exponent guess was too high
3448 and a smaller exponent can be reached
3449 by turning a 10...0 into 9...9x. */
3451 scale10_round_decimal_long_double (arg,
3452 (int)precision - exponent + 1);
3453 if (digits2 == NULL)
3456 END_LONG_DOUBLE_ROUNDING ();
3459 if (strlen (digits2) == precision + 1)
3468 /* Here ndigits = precision+1. */
3470 *p++ = digits[--ndigits];
3471 if ((flags & FLAG_ALT) || precision > 0)
3473 *p++ = decimal_point_char ();
3477 *p++ = digits[ndigits];
3484 *p++ = dp->conversion; /* 'e' or 'E' */
3485 # if WIDE_CHAR_VERSION
3487 static const wchar_t decimal_format[] =
3488 { '%', '+', '.', '2', 'd', '\0' };
3489 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3494 if (sizeof (DCHAR_T) == 1)
3496 sprintf ((char *) p, "%+.2d", exponent);
3504 sprintf (expbuf, "%+.2d", exponent);
3505 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3510 else if (dp->conversion == 'g' || dp->conversion == 'G')
3514 /* precision >= 1. */
3517 /* The exponent is 0, >= -4, < precision.
3518 Use fixed-point notation. */
3520 size_t ndigits = precision;
3521 /* Number of trailing zeroes that have to be
3524 (flags & FLAG_ALT ? 0 : precision - 1);
3528 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3530 *p++ = decimal_point_char ();
3531 while (ndigits > nzeroes)
3547 exponent = floorlog10l (arg);
3552 scale10_round_decimal_long_double (arg,
3553 (int)(precision - 1) - exponent);
3556 END_LONG_DOUBLE_ROUNDING ();
3559 ndigits = strlen (digits);
3561 if (ndigits == precision)
3563 if (ndigits < precision - 1
3564 || ndigits > precision + 1)
3565 /* The exponent was not guessed
3566 precisely enough. */
3569 /* None of two values of exponent is
3570 the right one. Prevent an endless
3574 if (ndigits < precision)
3580 /* Here ndigits = precision. */
3581 if (is_borderline (digits, precision - 1))
3583 /* Maybe the exponent guess was too high
3584 and a smaller exponent can be reached
3585 by turning a 10...0 into 9...9x. */
3587 scale10_round_decimal_long_double (arg,
3588 (int)(precision - 1) - exponent + 1);
3589 if (digits2 == NULL)
3592 END_LONG_DOUBLE_ROUNDING ();
3595 if (strlen (digits2) == precision)
3604 /* Here ndigits = precision. */
3606 /* Determine the number of trailing zeroes
3607 that have to be dropped. */
3609 if ((flags & FLAG_ALT) == 0)
3610 while (nzeroes < ndigits
3611 && digits[nzeroes] == '0')
3614 /* The exponent is now determined. */
3616 && exponent < (long)precision)
3618 /* Fixed-point notation:
3619 max(exponent,0)+1 digits, then the
3620 decimal point, then the remaining
3621 digits without trailing zeroes. */
3624 size_t count = exponent + 1;
3625 /* Note: count <= precision = ndigits. */
3626 for (; count > 0; count--)
3627 *p++ = digits[--ndigits];
3628 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3630 *p++ = decimal_point_char ();
3631 while (ndigits > nzeroes)
3634 *p++ = digits[ndigits];
3640 size_t count = -exponent - 1;
3642 *p++ = decimal_point_char ();
3643 for (; count > 0; count--)
3645 while (ndigits > nzeroes)
3648 *p++ = digits[ndigits];
3654 /* Exponential notation. */
3655 *p++ = digits[--ndigits];
3656 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3658 *p++ = decimal_point_char ();
3659 while (ndigits > nzeroes)
3662 *p++ = digits[ndigits];
3665 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3666 # if WIDE_CHAR_VERSION
3668 static const wchar_t decimal_format[] =
3669 { '%', '+', '.', '2', 'd', '\0' };
3670 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3675 if (sizeof (DCHAR_T) == 1)
3677 sprintf ((char *) p, "%+.2d", exponent);
3685 sprintf (expbuf, "%+.2d", exponent);
3686 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3698 /* arg is finite. */
3704 if (dp->conversion == 'f' || dp->conversion == 'F')
3707 if ((flags & FLAG_ALT) || precision > 0)
3709 *p++ = decimal_point_char ();
3710 for (; precision > 0; precision--)
3714 else if (dp->conversion == 'e' || dp->conversion == 'E')
3717 if ((flags & FLAG_ALT) || precision > 0)
3719 *p++ = decimal_point_char ();
3720 for (; precision > 0; precision--)
3723 *p++ = dp->conversion; /* 'e' or 'E' */
3728 else if (dp->conversion == 'g' || dp->conversion == 'G')
3731 if (flags & FLAG_ALT)
3734 (precision > 0 ? precision - 1 : 0);
3735 *p++ = decimal_point_char ();
3736 for (; ndigits > 0; --ndigits)
3740 else if (dp->conversion == 'a' || dp->conversion == 'A')
3743 *p++ = dp->conversion - 'A' + 'X';
3746 if ((flags & FLAG_ALT) || precision > 0)
3748 *p++ = decimal_point_char ();
3749 for (; precision > 0; precision--)
3752 *p++ = dp->conversion - 'A' + 'P';
3761 END_LONG_DOUBLE_ROUNDING ();
3764 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3768 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3770 double arg = a.arg[dp->arg_index].a.a_double;
3774 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3776 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3780 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3787 if (signbit (arg)) /* arg < 0.0 or negative zero */
3795 else if (flags & FLAG_SHOWSIGN)
3797 else if (flags & FLAG_SPACE)
3800 if (arg > 0.0 && arg + arg == arg)
3802 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3804 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3808 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3813 # if NEED_PRINTF_DOUBLE
3816 if (dp->conversion == 'f' || dp->conversion == 'F')
3822 scale10_round_decimal_double (arg, precision);
3825 ndigits = strlen (digits);
3827 if (ndigits > precision)
3831 *p++ = digits[ndigits];
3833 while (ndigits > precision);
3836 /* Here ndigits <= precision. */
3837 if ((flags & FLAG_ALT) || precision > 0)
3839 *p++ = decimal_point_char ();
3840 for (; precision > ndigits; precision--)
3845 *p++ = digits[ndigits];
3851 else if (dp->conversion == 'e' || dp->conversion == 'E')
3859 if ((flags & FLAG_ALT) || precision > 0)
3861 *p++ = decimal_point_char ();
3862 for (; precision > 0; precision--)
3873 exponent = floorlog10 (arg);
3878 scale10_round_decimal_double (arg,
3879 (int)precision - exponent);
3882 ndigits = strlen (digits);
3884 if (ndigits == precision + 1)
3886 if (ndigits < precision
3887 || ndigits > precision + 2)
3888 /* The exponent was not guessed
3889 precisely enough. */
3892 /* None of two values of exponent is
3893 the right one. Prevent an endless
3897 if (ndigits == precision)
3903 /* Here ndigits = precision+1. */
3904 if (is_borderline (digits, precision))
3906 /* Maybe the exponent guess was too high
3907 and a smaller exponent can be reached
3908 by turning a 10...0 into 9...9x. */
3910 scale10_round_decimal_double (arg,
3911 (int)precision - exponent + 1);
3912 if (digits2 == NULL)
3917 if (strlen (digits2) == precision + 1)
3926 /* Here ndigits = precision+1. */
3928 *p++ = digits[--ndigits];
3929 if ((flags & FLAG_ALT) || precision > 0)
3931 *p++ = decimal_point_char ();
3935 *p++ = digits[ndigits];
3942 *p++ = dp->conversion; /* 'e' or 'E' */
3943 # if WIDE_CHAR_VERSION
3945 static const wchar_t decimal_format[] =
3946 /* Produce the same number of exponent digits
3947 as the native printf implementation. */
3948 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3949 { '%', '+', '.', '3', 'd', '\0' };
3951 { '%', '+', '.', '2', 'd', '\0' };
3953 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3959 static const char decimal_format[] =
3960 /* Produce the same number of exponent digits
3961 as the native printf implementation. */
3962 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3967 if (sizeof (DCHAR_T) == 1)
3969 sprintf ((char *) p, decimal_format, exponent);
3977 sprintf (expbuf, decimal_format, exponent);
3978 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3984 else if (dp->conversion == 'g' || dp->conversion == 'G')
3988 /* precision >= 1. */
3991 /* The exponent is 0, >= -4, < precision.
3992 Use fixed-point notation. */
3994 size_t ndigits = precision;
3995 /* Number of trailing zeroes that have to be
3998 (flags & FLAG_ALT ? 0 : precision - 1);
4002 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4004 *p++ = decimal_point_char ();
4005 while (ndigits > nzeroes)
4021 exponent = floorlog10 (arg);
4026 scale10_round_decimal_double (arg,
4027 (int)(precision - 1) - exponent);
4030 ndigits = strlen (digits);
4032 if (ndigits == precision)
4034 if (ndigits < precision - 1
4035 || ndigits > precision + 1)
4036 /* The exponent was not guessed
4037 precisely enough. */
4040 /* None of two values of exponent is
4041 the right one. Prevent an endless
4045 if (ndigits < precision)
4051 /* Here ndigits = precision. */
4052 if (is_borderline (digits, precision - 1))
4054 /* Maybe the exponent guess was too high
4055 and a smaller exponent can be reached
4056 by turning a 10...0 into 9...9x. */
4058 scale10_round_decimal_double (arg,
4059 (int)(precision - 1) - exponent + 1);
4060 if (digits2 == NULL)
4065 if (strlen (digits2) == precision)
4074 /* Here ndigits = precision. */
4076 /* Determine the number of trailing zeroes
4077 that have to be dropped. */
4079 if ((flags & FLAG_ALT) == 0)
4080 while (nzeroes < ndigits
4081 && digits[nzeroes] == '0')
4084 /* The exponent is now determined. */
4086 && exponent < (long)precision)
4088 /* Fixed-point notation:
4089 max(exponent,0)+1 digits, then the
4090 decimal point, then the remaining
4091 digits without trailing zeroes. */
4094 size_t count = exponent + 1;
4095 /* Note: count <= precision = ndigits. */
4096 for (; count > 0; count--)
4097 *p++ = digits[--ndigits];
4098 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4100 *p++ = decimal_point_char ();
4101 while (ndigits > nzeroes)
4104 *p++ = digits[ndigits];
4110 size_t count = -exponent - 1;
4112 *p++ = decimal_point_char ();
4113 for (; count > 0; count--)
4115 while (ndigits > nzeroes)
4118 *p++ = digits[ndigits];
4124 /* Exponential notation. */
4125 *p++ = digits[--ndigits];
4126 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4128 *p++ = decimal_point_char ();
4129 while (ndigits > nzeroes)
4132 *p++ = digits[ndigits];
4135 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4136 # if WIDE_CHAR_VERSION
4138 static const wchar_t decimal_format[] =
4139 /* Produce the same number of exponent digits
4140 as the native printf implementation. */
4141 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4142 { '%', '+', '.', '3', 'd', '\0' };
4144 { '%', '+', '.', '2', 'd', '\0' };
4146 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4152 static const char decimal_format[] =
4153 /* Produce the same number of exponent digits
4154 as the native printf implementation. */
4155 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4160 if (sizeof (DCHAR_T) == 1)
4162 sprintf ((char *) p, decimal_format, exponent);
4170 sprintf (expbuf, decimal_format, exponent);
4171 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4184 /* arg is finite. */
4190 if (dp->conversion == 'f' || dp->conversion == 'F')
4193 if ((flags & FLAG_ALT) || precision > 0)
4195 *p++ = decimal_point_char ();
4196 for (; precision > 0; precision--)
4200 else if (dp->conversion == 'e' || dp->conversion == 'E')
4203 if ((flags & FLAG_ALT) || precision > 0)
4205 *p++ = decimal_point_char ();
4206 for (; precision > 0; precision--)
4209 *p++ = dp->conversion; /* 'e' or 'E' */
4211 /* Produce the same number of exponent digits as
4212 the native printf implementation. */
4213 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4219 else if (dp->conversion == 'g' || dp->conversion == 'G')
4222 if (flags & FLAG_ALT)
4225 (precision > 0 ? precision - 1 : 0);
4226 *p++ = decimal_point_char ();
4227 for (; ndigits > 0; --ndigits)
4239 /* The generated string now extends from tmp to p, with the
4240 zero padding insertion point being at pad_ptr. */
4241 if (has_width && p - tmp < width)
4243 size_t pad = width - (p - tmp);
4244 DCHAR_T *end = p + pad;
4246 if (flags & FLAG_LEFT)
4248 /* Pad with spaces on the right. */
4249 for (; pad > 0; pad--)
4252 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4254 /* Pad with zeroes. */
4259 for (; pad > 0; pad--)
4264 /* Pad with spaces on the left. */
4269 for (; pad > 0; pad--)
4277 size_t count = p - tmp;
4279 if (count >= tmp_length)
4280 /* tmp_length was incorrectly calculated - fix the
4284 /* Make room for the result. */
4285 if (count >= allocated - length)
4287 size_t n = xsum (length, count);
4289 ENSURE_ALLOCATION (n);
4292 /* Append the result. */
4293 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4302 arg_type type = a.arg[dp->arg_index].type;
4303 int flags = dp->flags;
4304 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4308 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4312 #if NEED_PRINTF_UNBOUNDED_PRECISION
4315 # define prec_ourselves 0
4317 #if NEED_PRINTF_FLAG_LEFTADJUST
4318 # define pad_ourselves 1
4319 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4322 # define pad_ourselves 0
4325 unsigned int prefix_count;
4326 int prefixes[2] IF_LINT (= { 0 });
4329 TCHAR_T tmpbuf[700];
4333 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4336 if (dp->width_start != dp->width_end)
4338 if (dp->width_arg_index != ARG_NONE)
4342 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4344 arg = a.arg[dp->width_arg_index].a.a_int;
4347 /* "A negative field width is taken as a '-' flag
4348 followed by a positive field width." */
4350 width = (unsigned int) (-arg);
4357 const FCHAR_T *digitp = dp->width_start;
4360 width = xsum (xtimes (width, 10), *digitp++ - '0');
4361 while (digitp != dp->width_end);
4367 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4370 if (dp->precision_start != dp->precision_end)
4372 if (dp->precision_arg_index != ARG_NONE)
4376 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4378 arg = a.arg[dp->precision_arg_index].a.a_int;
4379 /* "A negative precision is taken as if the precision
4389 const FCHAR_T *digitp = dp->precision_start + 1;
4392 while (digitp != dp->precision_end)
4393 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4399 /* Decide whether to handle the precision ourselves. */
4400 #if NEED_PRINTF_UNBOUNDED_PRECISION
4401 switch (dp->conversion)
4403 case 'd': case 'i': case 'u':
4405 case 'x': case 'X': case 'p':
4406 prec_ourselves = has_precision && (precision > 0);
4414 /* Decide whether to perform the padding ourselves. */
4415 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4416 switch (dp->conversion)
4418 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4419 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4420 to perform the padding after this conversion. Functions
4421 with unistdio extensions perform the padding based on
4422 character count rather than element count. */
4425 # if NEED_PRINTF_FLAG_ZERO
4426 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4432 pad_ourselves = prec_ourselves;
4438 /* Allocate a temporary buffer of sufficient size for calling
4441 switch (dp->conversion)
4444 case 'd': case 'i': case 'u':
4445 # if HAVE_LONG_LONG_INT
4446 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4448 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4449 * 0.30103 /* binary -> decimal */
4451 + 1; /* turn floor into ceil */
4454 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4456 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4457 * 0.30103 /* binary -> decimal */
4459 + 1; /* turn floor into ceil */
4462 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4463 * 0.30103 /* binary -> decimal */
4465 + 1; /* turn floor into ceil */
4466 if (tmp_length < precision)
4467 tmp_length = precision;
4468 /* Multiply by 2, as an estimate for FLAG_GROUP. */
4469 tmp_length = xsum (tmp_length, tmp_length);
4470 /* Add 1, to account for a leading sign. */
4471 tmp_length = xsum (tmp_length, 1);
4475 # if HAVE_LONG_LONG_INT
4476 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4478 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4479 * 0.333334 /* binary -> octal */
4481 + 1; /* turn floor into ceil */
4484 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4486 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4487 * 0.333334 /* binary -> octal */
4489 + 1; /* turn floor into ceil */
4492 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4493 * 0.333334 /* binary -> octal */
4495 + 1; /* turn floor into ceil */
4496 if (tmp_length < precision)
4497 tmp_length = precision;
4498 /* Add 1, to account for a leading sign. */
4499 tmp_length = xsum (tmp_length, 1);
4503 # if HAVE_LONG_LONG_INT
4504 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4506 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4507 * 0.25 /* binary -> hexadecimal */
4509 + 1; /* turn floor into ceil */
4512 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4514 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4515 * 0.25 /* binary -> hexadecimal */
4517 + 1; /* turn floor into ceil */
4520 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4521 * 0.25 /* binary -> hexadecimal */
4523 + 1; /* turn floor into ceil */
4524 if (tmp_length < precision)
4525 tmp_length = precision;
4526 /* Add 2, to account for a leading sign or alternate form. */
4527 tmp_length = xsum (tmp_length, 2);
4531 if (type == TYPE_LONGDOUBLE)
4533 (unsigned int) (LDBL_MAX_EXP
4534 * 0.30103 /* binary -> decimal */
4535 * 2 /* estimate for FLAG_GROUP */
4537 + 1 /* turn floor into ceil */
4538 + 10; /* sign, decimal point etc. */
4541 (unsigned int) (DBL_MAX_EXP
4542 * 0.30103 /* binary -> decimal */
4543 * 2 /* estimate for FLAG_GROUP */
4545 + 1 /* turn floor into ceil */
4546 + 10; /* sign, decimal point etc. */
4547 tmp_length = xsum (tmp_length, precision);
4550 case 'e': case 'E': case 'g': case 'G':
4552 12; /* sign, decimal point, exponent etc. */
4553 tmp_length = xsum (tmp_length, precision);
4557 if (type == TYPE_LONGDOUBLE)
4559 (unsigned int) (LDBL_DIG
4560 * 0.831 /* decimal -> hexadecimal */
4562 + 1; /* turn floor into ceil */
4565 (unsigned int) (DBL_DIG
4566 * 0.831 /* decimal -> hexadecimal */
4568 + 1; /* turn floor into ceil */
4569 if (tmp_length < precision)
4570 tmp_length = precision;
4571 /* Account for sign, decimal point etc. */
4572 tmp_length = xsum (tmp_length, 12);
4576 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
4577 if (type == TYPE_WIDE_CHAR)
4578 tmp_length = MB_CUR_MAX;
4586 if (type == TYPE_WIDE_STRING)
4588 # if WIDE_CHAR_VERSION
4589 /* ISO C says about %ls in fwprintf:
4590 "If the precision is not specified or is greater
4591 than the size of the array, the array shall
4592 contain a null wide character."
4593 So if there is a precision, we must not use
4595 const wchar_t *arg =
4596 a.arg[dp->arg_index].a.a_wide_string;
4599 tmp_length = local_wcsnlen (arg, precision);
4601 tmp_length = local_wcslen (arg);
4603 /* ISO C says about %ls in fprintf:
4604 "If a precision is specified, no more than that
4605 many bytes are written (including shift
4606 sequences, if any), and the array shall contain
4607 a null wide character if, to equal the
4608 multibyte character sequence length given by
4609 the precision, the function would need to
4610 access a wide character one past the end of the
4612 So if there is a precision, we must not use
4614 /* This case has already been handled above. */
4621 # if WIDE_CHAR_VERSION
4622 /* ISO C says about %s in fwprintf:
4623 "If the precision is not specified or is greater
4624 than the size of the converted array, the
4625 converted array shall contain a null wide
4627 So if there is a precision, we must not use
4629 /* This case has already been handled above. */
4632 /* ISO C says about %s in fprintf:
4633 "If the precision is not specified or greater
4634 than the size of the array, the array shall
4635 contain a null character."
4636 So if there is a precision, we must not use
4638 const char *arg = a.arg[dp->arg_index].a.a_string;
4641 tmp_length = local_strnlen (arg, precision);
4643 tmp_length = strlen (arg);
4650 (unsigned int) (sizeof (void *) * CHAR_BIT
4651 * 0.25 /* binary -> hexadecimal */
4653 + 1 /* turn floor into ceil */
4654 + 2; /* account for leading 0x */
4663 # if ENABLE_UNISTDIO
4664 /* Padding considers the number of characters, therefore
4665 the number of elements after padding may be
4666 > max (tmp_length, width)
4668 <= tmp_length + width. */
4669 tmp_length = xsum (tmp_length, width);
4671 /* Padding considers the number of elements,
4673 if (tmp_length < width)
4678 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
4681 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4685 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4687 if (size_overflow_p (tmp_memsize))
4688 /* Overflow, would lead to out of memory. */
4690 tmp = (TCHAR_T *) malloc (tmp_memsize);
4692 /* Out of memory. */
4697 /* Construct the format string for calling snprintf or
4701 #if NEED_PRINTF_FLAG_GROUPING
4702 /* The underlying implementation doesn't support the ' flag.
4703 Produce no grouping characters in this case; this is
4704 acceptable because the grouping is locale dependent. */
4706 if (flags & FLAG_GROUP)
4709 if (flags & FLAG_LEFT)
4711 if (flags & FLAG_SHOWSIGN)
4713 if (flags & FLAG_SPACE)
4715 if (flags & FLAG_ALT)
4719 if (flags & FLAG_ZERO)
4721 if (dp->width_start != dp->width_end)
4723 size_t n = dp->width_end - dp->width_start;
4724 /* The width specification is known to consist only
4725 of standard ASCII characters. */
4726 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4728 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4733 const FCHAR_T *mp = dp->width_start;
4735 *fbp++ = (unsigned char) *mp++;
4740 if (!prec_ourselves)
4742 if (dp->precision_start != dp->precision_end)
4744 size_t n = dp->precision_end - dp->precision_start;
4745 /* The precision specification is known to consist only
4746 of standard ASCII characters. */
4747 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4749 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4754 const FCHAR_T *mp = dp->precision_start;
4756 *fbp++ = (unsigned char) *mp++;
4764 #if HAVE_LONG_LONG_INT
4765 case TYPE_LONGLONGINT:
4766 case TYPE_ULONGLONGINT:
4767 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4780 case TYPE_WIDE_CHAR:
4783 case TYPE_WIDE_STRING:
4787 case TYPE_LONGDOUBLE:
4793 #if NEED_PRINTF_DIRECTIVE_F
4794 if (dp->conversion == 'F')
4798 *fbp = dp->conversion;
4800 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4805 /* On glibc2 systems from glibc >= 2.3 - probably also older
4806 ones - we know that snprintf's returns value conforms to
4807 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4808 Therefore we can avoid using %n in this situation.
4809 On glibc2 systems from 2004-10-18 or newer, the use of %n
4810 in format strings in writable memory may crash the program
4811 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4812 in this situation. */
4813 /* On native Win32 systems (such as mingw), we can avoid using
4815 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4816 snprintf does not write more than the specified number
4817 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4818 '4', '5', '6' into buf, not '4', '5', '\0'.)
4819 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4820 allows us to recognize the case of an insufficient
4821 buffer size: it returns -1 in this case.
4822 On native Win32 systems (such as mingw) where the OS is
4823 Windows Vista, the use of %n in format strings by default
4824 crashes the program. See
4825 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4826 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4827 So we should avoid %n in this situation. */
4834 /* Construct the arguments for calling snprintf or sprintf. */
4836 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4838 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4840 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4842 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4844 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4846 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4850 /* The SNPRINTF result is appended after result[0..length].
4851 The latter is an array of DCHAR_T; SNPRINTF appends an
4852 array of TCHAR_T to it. This is possible because
4853 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4854 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4855 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4856 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4857 where an snprintf() with maxlen==1 acts like sprintf(). */
4858 ENSURE_ALLOCATION (xsum (length,
4859 (2 + TCHARS_PER_DCHAR - 1)
4860 / TCHARS_PER_DCHAR));
4861 /* Prepare checking whether snprintf returns the count
4863 *(TCHAR_T *) (result + length) = '\0';
4872 size_t maxlen = allocated - length;
4873 /* SNPRINTF can fail if its second argument is
4875 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4876 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4877 maxlen = maxlen * TCHARS_PER_DCHAR;
4878 # define SNPRINTF_BUF(arg) \
4879 switch (prefix_count) \
4882 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4887 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4889 prefixes[0], arg, &count); \
4892 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4894 prefixes[0], prefixes[1], arg, \
4901 # define SNPRINTF_BUF(arg) \
4902 switch (prefix_count) \
4905 count = sprintf (tmp, buf, arg); \
4908 count = sprintf (tmp, buf, prefixes[0], arg); \
4911 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4923 int arg = a.arg[dp->arg_index].a.a_schar;
4929 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4935 int arg = a.arg[dp->arg_index].a.a_short;
4941 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4947 int arg = a.arg[dp->arg_index].a.a_int;
4953 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4959 long int arg = a.arg[dp->arg_index].a.a_longint;
4965 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4969 #if HAVE_LONG_LONG_INT
4970 case TYPE_LONGLONGINT:
4972 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4976 case TYPE_ULONGLONGINT:
4978 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4985 double arg = a.arg[dp->arg_index].a.a_double;
4989 case TYPE_LONGDOUBLE:
4991 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4997 int arg = a.arg[dp->arg_index].a.a_char;
5002 case TYPE_WIDE_CHAR:
5004 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5011 const char *arg = a.arg[dp->arg_index].a.a_string;
5016 case TYPE_WIDE_STRING:
5018 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5025 void *arg = a.arg[dp->arg_index].a.a_pointer;
5034 /* Portability: Not all implementations of snprintf()
5035 are ISO C 99 compliant. Determine the number of
5036 bytes that snprintf() has produced or would have
5040 /* Verify that snprintf() has NUL-terminated its
5043 && ((TCHAR_T *) (result + length)) [count] != '\0')
5045 /* Portability hack. */
5046 if (retcount > count)
5051 /* snprintf() doesn't understand the '%n'
5055 /* Don't use the '%n' directive; instead, look
5056 at the snprintf() return value. */
5062 /* Look at the snprintf() return value. */
5065 /* HP-UX 10.20 snprintf() is doubly deficient:
5066 It doesn't understand the '%n' directive,
5067 *and* it returns -1 (rather than the length
5068 that would have been required) when the
5069 buffer is too small. */
5070 size_t bigger_need =
5071 xsum (xtimes (allocated, 2), 12);
5072 ENSURE_ALLOCATION (bigger_need);
5081 /* Attempt to handle failure. */
5084 if (!(result == resultbuf || result == NULL))
5086 if (buf_malloced != NULL)
5087 free (buf_malloced);
5094 /* Handle overflow of the allocated buffer.
5095 If such an overflow occurs, a C99 compliant snprintf()
5096 returns a count >= maxlen. However, a non-compliant
5097 snprintf() function returns only count = maxlen - 1. To
5098 cover both cases, test whether count >= maxlen - 1. */
5099 if ((unsigned int) count + 1 >= maxlen)
5101 /* If maxlen already has attained its allowed maximum,
5102 allocating more memory will not increase maxlen.
5103 Instead of looping, bail out. */
5104 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5108 /* Need at least (count + 1) * sizeof (TCHAR_T)
5109 bytes. (The +1 is for the trailing NUL.)
5110 But ask for (count + 2) * sizeof (TCHAR_T)
5111 bytes, so that in the next round, we likely get
5112 maxlen > (unsigned int) count + 1
5113 and so we don't get here again.
5114 And allocate proportionally, to avoid looping
5115 eternally if snprintf() reports a too small
5119 ((unsigned int) count + 2
5120 + TCHARS_PER_DCHAR - 1)
5121 / TCHARS_PER_DCHAR),
5122 xtimes (allocated, 2));
5124 ENSURE_ALLOCATION (n);
5130 #if NEED_PRINTF_UNBOUNDED_PRECISION
5133 /* Handle the precision. */
5136 (TCHAR_T *) (result + length);
5140 size_t prefix_count;
5144 /* Put the additional zeroes after the sign. */
5146 && (*prec_ptr == '-' || *prec_ptr == '+'
5147 || *prec_ptr == ' '))
5149 /* Put the additional zeroes after the 0x prefix if
5150 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5152 && prec_ptr[0] == '0'
5153 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5156 move = count - prefix_count;
5157 if (precision > move)
5159 /* Insert zeroes. */
5160 size_t insert = precision - move;
5166 (count + insert + TCHARS_PER_DCHAR - 1)
5167 / TCHARS_PER_DCHAR);
5168 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5169 ENSURE_ALLOCATION (n);
5170 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5171 prec_ptr = (TCHAR_T *) (result + length);
5174 prec_end = prec_ptr + count;
5175 prec_ptr += prefix_count;
5177 while (prec_end > prec_ptr)
5180 prec_end[insert] = prec_end[0];
5186 while (prec_end > prec_ptr);
5194 if (count >= tmp_length)
5195 /* tmp_length was incorrectly calculated - fix the
5201 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5202 if (dp->conversion == 'c' || dp->conversion == 's')
5204 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5206 The result string is not certainly ASCII. */
5207 const TCHAR_T *tmpsrc;
5210 /* This code assumes that TCHAR_T is 'char'. */
5211 typedef int TCHAR_T_verify
5212 [2 * (sizeof (TCHAR_T) == 1) - 1];
5214 tmpsrc = (TCHAR_T *) (result + length);
5219 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5220 iconveh_question_mark,
5226 int saved_errno = errno;
5227 if (!(result == resultbuf || result == NULL))
5229 if (buf_malloced != NULL)
5230 free (buf_malloced);
5232 errno = saved_errno;
5235 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5236 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5242 /* The result string is ASCII.
5243 Simple 1:1 conversion. */
5245 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5246 no-op conversion, in-place on the array starting
5247 at (result + length). */
5248 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5251 const TCHAR_T *tmpsrc;
5256 if (result == resultbuf)
5258 tmpsrc = (TCHAR_T *) (result + length);
5259 /* ENSURE_ALLOCATION will not move tmpsrc
5260 (because it's part of resultbuf). */
5261 ENSURE_ALLOCATION (xsum (length, count));
5265 /* ENSURE_ALLOCATION will move the array
5266 (because it uses realloc(). */
5267 ENSURE_ALLOCATION (xsum (length, count));
5268 tmpsrc = (TCHAR_T *) (result + length);
5272 ENSURE_ALLOCATION (xsum (length, count));
5274 tmpdst = result + length;
5275 /* Copy backwards, because of overlapping. */
5278 for (n = count; n > 0; n--)
5279 *--tmpdst = (unsigned char) *--tmpsrc;
5284 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5285 /* Make room for the result. */
5286 if (count > allocated - length)
5288 /* Need at least count elements. But allocate
5291 xmax (xsum (length, count), xtimes (allocated, 2));
5293 ENSURE_ALLOCATION (n);
5297 /* Here count <= allocated - length. */
5299 /* Perform padding. */
5300 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5301 if (pad_ourselves && has_width)
5304 # if ENABLE_UNISTDIO
5305 /* Outside POSIX, it's preferrable to compare the width
5306 against the number of _characters_ of the converted
5308 w = DCHAR_MBSNLEN (result + length, count);
5310 /* The width is compared against the number of _bytes_
5311 of the converted value, says POSIX. */
5316 size_t pad = width - w;
5318 /* Make room for the result. */
5319 if (xsum (count, pad) > allocated - length)
5321 /* Need at least count + pad elements. But
5322 allocate proportionally. */
5324 xmax (xsum3 (length, count, pad),
5325 xtimes (allocated, 2));
5329 ENSURE_ALLOCATION (n);
5332 ENSURE_ALLOCATION (n);
5335 /* Here count + pad <= allocated - length. */
5338 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5339 DCHAR_T * const rp = result + length;
5341 DCHAR_T * const rp = tmp;
5343 DCHAR_T *p = rp + count;
5344 DCHAR_T *end = p + pad;
5346 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5347 if (dp->conversion == 'c'
5348 || dp->conversion == 's')
5349 /* No zero-padding for string directives. */
5354 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5355 /* No zero-padding of "inf" and "nan". */
5356 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5357 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5360 /* The generated string now extends from rp to p,
5361 with the zero padding insertion point being at
5364 count = count + pad; /* = end - rp */
5366 if (flags & FLAG_LEFT)
5368 /* Pad with spaces on the right. */
5369 for (; pad > 0; pad--)
5372 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5374 /* Pad with zeroes. */
5379 for (; pad > 0; pad--)
5384 /* Pad with spaces on the left. */
5389 for (; pad > 0; pad--)
5397 /* Here still count <= allocated - length. */
5399 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5400 /* The snprintf() result did fit. */
5402 /* Append the sprintf() result. */
5403 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5410 #if NEED_PRINTF_DIRECTIVE_F
5411 if (dp->conversion == 'F')
5413 /* Convert the %f result to upper case for %F. */
5414 DCHAR_T *rp = result + length;
5416 for (rc = count; rc > 0; rc--, rp++)
5417 if (*rp >= 'a' && *rp <= 'z')
5418 *rp = *rp - 'a' + 'A';
5429 /* Add the final NUL. */
5430 ENSURE_ALLOCATION (xsum (length, 1));
5431 result[length] = '\0';
5433 if (result != resultbuf && length + 1 < allocated)
5435 /* Shrink the allocated memory if possible. */
5438 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5443 if (buf_malloced != NULL)
5444 free (buf_malloced);
5447 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5448 says that snprintf() fails with errno = EOVERFLOW in this case, but
5449 that's only because snprintf() returns an 'int'. This function does
5450 not have this limitation. */
5455 if (!(result == resultbuf || result == NULL))
5457 if (buf_malloced != NULL)
5458 free (buf_malloced);
5465 if (!(result == resultbuf || result == NULL))
5467 if (buf_malloced != NULL)
5468 free (buf_malloced);
5476 #undef TCHARS_PER_DCHAR
5483 #undef DCHAR_IS_TCHAR