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-(hightest 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. */
1802 if (u8_conv_to_encoding (locale_charset (),
1803 iconveh_question_mark,
1804 arg, arg_end - arg, NULL,
1805 &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);
1812 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. */
1930 if (u16_conv_to_encoding (locale_charset (),
1931 iconveh_question_mark,
1932 arg, arg_end - arg, NULL,
1933 &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);
1940 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. */
2058 if (u32_conv_to_encoding (locale_charset (),
2059 iconveh_question_mark,
2060 arg, arg_end - arg, NULL,
2061 &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);
2068 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[]. */
2498 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
2499 iconveh_question_mark,
2502 &tmpdst, &tmpdst_len)
2505 int saved_errno = errno;
2507 if (!(result == resultbuf || result == NULL))
2509 if (buf_malloced != NULL)
2510 free (buf_malloced);
2512 errno = saved_errno;
2520 # if ENABLE_UNISTDIO
2521 /* Outside POSIX, it's preferrable to compare the width
2522 against the number of _characters_ of the converted
2524 w = DCHAR_MBSNLEN (result + length, characters);
2526 /* The width is compared against the number of _bytes_
2527 of the converted value, says POSIX. */
2532 /* w doesn't matter. */
2535 if (has_width && width > w
2536 && !(dp->flags & FLAG_LEFT))
2538 size_t n = width - w;
2539 ENSURE_ALLOCATION (xsum (length, n));
2540 DCHAR_SET (result + length, ' ', n);
2545 if (has_precision || has_width)
2547 /* We know the number of bytes in advance. */
2551 memset (&state, '\0', sizeof (mbstate_t));
2553 ENSURE_ALLOCATION (xsum (length, characters));
2554 for (remaining = characters; remaining > 0; )
2556 char buf[64]; /* Assume MB_CUR_MAX <= 64. */
2562 count = wcrtomb (buf, *arg, &state);
2564 count = wctomb (buf, *arg);
2567 /* Inconsistency. */
2569 memcpy (result + length, buf, count);
2574 if (!(arg == arg_end))
2581 memset (&state, '\0', sizeof (mbstate_t));
2583 while (arg < arg_end)
2585 char buf[64]; /* Assume MB_CUR_MAX <= 64. */
2591 count = wcrtomb (buf, *arg, &state);
2593 count = wctomb (buf, *arg);
2596 /* Inconsistency. */
2598 ENSURE_ALLOCATION (xsum (length, count));
2599 memcpy (result + length, buf, count);
2605 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2606 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2608 length += tmpdst_len;
2611 if (has_width && width > w
2612 && (dp->flags & FLAG_LEFT))
2614 size_t n = width - w;
2615 ENSURE_ALLOCATION (xsum (length, n));
2616 DCHAR_SET (result + length, ' ', n);
2623 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2624 else if ((dp->conversion == 'a' || dp->conversion == 'A')
2625 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2627 # if NEED_PRINTF_DOUBLE
2628 || a.arg[dp->arg_index].type == TYPE_DOUBLE
2630 # if NEED_PRINTF_LONG_DOUBLE
2631 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2637 arg_type type = a.arg[dp->arg_index].type;
2638 int flags = dp->flags;
2644 DCHAR_T tmpbuf[700];
2651 if (dp->width_start != dp->width_end)
2653 if (dp->width_arg_index != ARG_NONE)
2657 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2659 arg = a.arg[dp->width_arg_index].a.a_int;
2662 /* "A negative field width is taken as a '-' flag
2663 followed by a positive field width." */
2665 width = (unsigned int) (-arg);
2672 const FCHAR_T *digitp = dp->width_start;
2675 width = xsum (xtimes (width, 10), *digitp++ - '0');
2676 while (digitp != dp->width_end);
2683 if (dp->precision_start != dp->precision_end)
2685 if (dp->precision_arg_index != ARG_NONE)
2689 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2691 arg = a.arg[dp->precision_arg_index].a.a_int;
2692 /* "A negative precision is taken as if the precision
2702 const FCHAR_T *digitp = dp->precision_start + 1;
2705 while (digitp != dp->precision_end)
2706 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2711 /* Allocate a temporary buffer of sufficient size. */
2712 if (type == TYPE_LONGDOUBLE)
2714 (unsigned int) ((LDBL_DIG + 1)
2715 * 0.831 /* decimal -> hexadecimal */
2717 + 1; /* turn floor into ceil */
2720 (unsigned int) ((DBL_DIG + 1)
2721 * 0.831 /* decimal -> hexadecimal */
2723 + 1; /* turn floor into ceil */
2724 if (tmp_length < precision)
2725 tmp_length = precision;
2726 /* Account for sign, decimal point etc. */
2727 tmp_length = xsum (tmp_length, 12);
2729 if (tmp_length < width)
2732 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2734 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2738 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2740 if (size_overflow_p (tmp_memsize))
2741 /* Overflow, would lead to out of memory. */
2743 tmp = (DCHAR_T *) malloc (tmp_memsize);
2745 /* Out of memory. */
2751 if (type == TYPE_LONGDOUBLE)
2753 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2754 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2758 if (dp->conversion == 'A')
2760 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2764 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2770 DECL_LONG_DOUBLE_ROUNDING
2772 BEGIN_LONG_DOUBLE_ROUNDING ();
2774 if (signbit (arg)) /* arg < 0.0L or negative zero */
2782 else if (flags & FLAG_SHOWSIGN)
2784 else if (flags & FLAG_SPACE)
2787 if (arg > 0.0L && arg + arg == arg)
2789 if (dp->conversion == 'A')
2791 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2795 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2801 long double mantissa;
2804 mantissa = printf_frexpl (arg, &exponent);
2812 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2814 /* Round the mantissa. */
2815 long double tail = mantissa;
2818 for (q = precision; ; q--)
2820 int digit = (int) tail;
2824 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2833 for (q = precision; q > 0; q--)
2839 *p++ = dp->conversion - 'A' + 'X';
2844 digit = (int) mantissa;
2847 if ((flags & FLAG_ALT)
2848 || mantissa > 0.0L || precision > 0)
2850 *p++ = decimal_point_char ();
2851 /* This loop terminates because we assume
2852 that FLT_RADIX is a power of 2. */
2853 while (mantissa > 0.0L)
2856 digit = (int) mantissa;
2861 : dp->conversion - 10);
2865 while (precision > 0)
2872 *p++ = dp->conversion - 'A' + 'P';
2873 # if WIDE_CHAR_VERSION
2875 static const wchar_t decimal_format[] =
2876 { '%', '+', 'd', '\0' };
2877 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2882 if (sizeof (DCHAR_T) == 1)
2884 sprintf ((char *) p, "%+d", exponent);
2892 sprintf (expbuf, "%+d", exponent);
2893 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2899 END_LONG_DOUBLE_ROUNDING ();
2907 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2908 double arg = a.arg[dp->arg_index].a.a_double;
2912 if (dp->conversion == 'A')
2914 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2918 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2925 if (signbit (arg)) /* arg < 0.0 or negative zero */
2933 else if (flags & FLAG_SHOWSIGN)
2935 else if (flags & FLAG_SPACE)
2938 if (arg > 0.0 && arg + arg == arg)
2940 if (dp->conversion == 'A')
2942 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2946 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2955 mantissa = printf_frexp (arg, &exponent);
2963 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2965 /* Round the mantissa. */
2966 double tail = mantissa;
2969 for (q = precision; ; q--)
2971 int digit = (int) tail;
2975 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2984 for (q = precision; q > 0; q--)
2990 *p++ = dp->conversion - 'A' + 'X';
2995 digit = (int) mantissa;
2998 if ((flags & FLAG_ALT)
2999 || mantissa > 0.0 || precision > 0)
3001 *p++ = decimal_point_char ();
3002 /* This loop terminates because we assume
3003 that FLT_RADIX is a power of 2. */
3004 while (mantissa > 0.0)
3007 digit = (int) mantissa;
3012 : dp->conversion - 10);
3016 while (precision > 0)
3023 *p++ = dp->conversion - 'A' + 'P';
3024 # if WIDE_CHAR_VERSION
3026 static const wchar_t decimal_format[] =
3027 { '%', '+', 'd', '\0' };
3028 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3033 if (sizeof (DCHAR_T) == 1)
3035 sprintf ((char *) p, "%+d", exponent);
3043 sprintf (expbuf, "%+d", exponent);
3044 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3054 /* The generated string now extends from tmp to p, with the
3055 zero padding insertion point being at pad_ptr. */
3056 if (has_width && p - tmp < width)
3058 size_t pad = width - (p - tmp);
3059 DCHAR_T *end = p + pad;
3061 if (flags & FLAG_LEFT)
3063 /* Pad with spaces on the right. */
3064 for (; pad > 0; pad--)
3067 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3069 /* Pad with zeroes. */
3074 for (; pad > 0; pad--)
3079 /* Pad with spaces on the left. */
3084 for (; pad > 0; pad--)
3092 size_t count = p - tmp;
3094 if (count >= tmp_length)
3095 /* tmp_length was incorrectly calculated - fix the
3099 /* Make room for the result. */
3100 if (count >= allocated - length)
3102 size_t n = xsum (length, count);
3104 ENSURE_ALLOCATION (n);
3107 /* Append the result. */
3108 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3115 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3116 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3117 || dp->conversion == 'e' || dp->conversion == 'E'
3118 || dp->conversion == 'g' || dp->conversion == 'G'
3119 || dp->conversion == 'a' || dp->conversion == 'A')
3121 # if NEED_PRINTF_DOUBLE
3122 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3123 # elif NEED_PRINTF_INFINITE_DOUBLE
3124 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3125 /* The systems (mingw) which produce wrong output
3126 for Inf, -Inf, and NaN also do so for -0.0.
3127 Therefore we treat this case here as well. */
3128 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3130 # if NEED_PRINTF_LONG_DOUBLE
3131 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3132 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3133 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3134 /* Some systems produce wrong output for Inf,
3135 -Inf, and NaN. Some systems in this category
3136 (IRIX 5.3) also do so for -0.0. Therefore we
3137 treat this case here as well. */
3138 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3142 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3143 arg_type type = a.arg[dp->arg_index].type;
3145 int flags = dp->flags;
3151 DCHAR_T tmpbuf[700];
3158 if (dp->width_start != dp->width_end)
3160 if (dp->width_arg_index != ARG_NONE)
3164 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3166 arg = a.arg[dp->width_arg_index].a.a_int;
3169 /* "A negative field width is taken as a '-' flag
3170 followed by a positive field width." */
3172 width = (unsigned int) (-arg);
3179 const FCHAR_T *digitp = dp->width_start;
3182 width = xsum (xtimes (width, 10), *digitp++ - '0');
3183 while (digitp != dp->width_end);
3190 if (dp->precision_start != dp->precision_end)
3192 if (dp->precision_arg_index != ARG_NONE)
3196 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3198 arg = a.arg[dp->precision_arg_index].a.a_int;
3199 /* "A negative precision is taken as if the precision
3209 const FCHAR_T *digitp = dp->precision_start + 1;
3212 while (digitp != dp->precision_end)
3213 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3218 /* POSIX specifies the default precision to be 6 for %f, %F,
3219 %e, %E, but not for %g, %G. Implementations appear to use
3220 the same default precision also for %g, %G. But for %a, %A,
3221 the default precision is 0. */
3223 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3226 /* Allocate a temporary buffer of sufficient size. */
3227 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3228 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3229 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3230 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3231 # elif NEED_PRINTF_LONG_DOUBLE
3232 tmp_length = LDBL_DIG + 1;
3233 # elif NEED_PRINTF_DOUBLE
3234 tmp_length = DBL_DIG + 1;
3238 if (tmp_length < precision)
3239 tmp_length = precision;
3240 # if NEED_PRINTF_LONG_DOUBLE
3241 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3242 if (type == TYPE_LONGDOUBLE)
3244 if (dp->conversion == 'f' || dp->conversion == 'F')
3246 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3247 if (!(isnanl (arg) || arg + arg == arg))
3249 /* arg is finite and nonzero. */
3250 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3251 if (exponent >= 0 && tmp_length < exponent + precision)
3252 tmp_length = exponent + precision;
3256 # if NEED_PRINTF_DOUBLE
3257 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3258 if (type == TYPE_DOUBLE)
3260 if (dp->conversion == 'f' || dp->conversion == 'F')
3262 double arg = a.arg[dp->arg_index].a.a_double;
3263 if (!(isnand (arg) || arg + arg == arg))
3265 /* arg is finite and nonzero. */
3266 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3267 if (exponent >= 0 && tmp_length < exponent + precision)
3268 tmp_length = exponent + precision;
3272 /* Account for sign, decimal point etc. */
3273 tmp_length = xsum (tmp_length, 12);
3275 if (tmp_length < width)
3278 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3280 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3284 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3286 if (size_overflow_p (tmp_memsize))
3287 /* Overflow, would lead to out of memory. */
3289 tmp = (DCHAR_T *) malloc (tmp_memsize);
3291 /* Out of memory. */
3298 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3299 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3300 if (type == TYPE_LONGDOUBLE)
3303 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3307 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3309 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3313 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3319 DECL_LONG_DOUBLE_ROUNDING
3321 BEGIN_LONG_DOUBLE_ROUNDING ();
3323 if (signbit (arg)) /* arg < 0.0L or negative zero */
3331 else if (flags & FLAG_SHOWSIGN)
3333 else if (flags & FLAG_SPACE)
3336 if (arg > 0.0L && arg + arg == arg)
3338 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3340 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3344 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3349 # if NEED_PRINTF_LONG_DOUBLE
3352 if (dp->conversion == 'f' || dp->conversion == 'F')
3358 scale10_round_decimal_long_double (arg, precision);
3361 END_LONG_DOUBLE_ROUNDING ();
3364 ndigits = strlen (digits);
3366 if (ndigits > precision)
3370 *p++ = digits[ndigits];
3372 while (ndigits > precision);
3375 /* Here ndigits <= precision. */
3376 if ((flags & FLAG_ALT) || precision > 0)
3378 *p++ = decimal_point_char ();
3379 for (; precision > ndigits; precision--)
3384 *p++ = digits[ndigits];
3390 else if (dp->conversion == 'e' || dp->conversion == 'E')
3398 if ((flags & FLAG_ALT) || precision > 0)
3400 *p++ = decimal_point_char ();
3401 for (; precision > 0; precision--)
3412 exponent = floorlog10l (arg);
3417 scale10_round_decimal_long_double (arg,
3418 (int)precision - exponent);
3421 END_LONG_DOUBLE_ROUNDING ();
3424 ndigits = strlen (digits);
3426 if (ndigits == precision + 1)
3428 if (ndigits < precision
3429 || ndigits > precision + 2)
3430 /* The exponent was not guessed
3431 precisely enough. */
3434 /* None of two values of exponent is
3435 the right one. Prevent an endless
3439 if (ndigits == precision)
3445 /* Here ndigits = precision+1. */
3446 if (is_borderline (digits, precision))
3448 /* Maybe the exponent guess was too high
3449 and a smaller exponent can be reached
3450 by turning a 10...0 into 9...9x. */
3452 scale10_round_decimal_long_double (arg,
3453 (int)precision - exponent + 1);
3454 if (digits2 == NULL)
3457 END_LONG_DOUBLE_ROUNDING ();
3460 if (strlen (digits2) == precision + 1)
3469 /* Here ndigits = precision+1. */
3471 *p++ = digits[--ndigits];
3472 if ((flags & FLAG_ALT) || precision > 0)
3474 *p++ = decimal_point_char ();
3478 *p++ = digits[ndigits];
3485 *p++ = dp->conversion; /* 'e' or 'E' */
3486 # if WIDE_CHAR_VERSION
3488 static const wchar_t decimal_format[] =
3489 { '%', '+', '.', '2', 'd', '\0' };
3490 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3495 if (sizeof (DCHAR_T) == 1)
3497 sprintf ((char *) p, "%+.2d", exponent);
3505 sprintf (expbuf, "%+.2d", exponent);
3506 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3511 else if (dp->conversion == 'g' || dp->conversion == 'G')
3515 /* precision >= 1. */
3518 /* The exponent is 0, >= -4, < precision.
3519 Use fixed-point notation. */
3521 size_t ndigits = precision;
3522 /* Number of trailing zeroes that have to be
3525 (flags & FLAG_ALT ? 0 : precision - 1);
3529 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3531 *p++ = decimal_point_char ();
3532 while (ndigits > nzeroes)
3548 exponent = floorlog10l (arg);
3553 scale10_round_decimal_long_double (arg,
3554 (int)(precision - 1) - exponent);
3557 END_LONG_DOUBLE_ROUNDING ();
3560 ndigits = strlen (digits);
3562 if (ndigits == precision)
3564 if (ndigits < precision - 1
3565 || ndigits > precision + 1)
3566 /* The exponent was not guessed
3567 precisely enough. */
3570 /* None of two values of exponent is
3571 the right one. Prevent an endless
3575 if (ndigits < precision)
3581 /* Here ndigits = precision. */
3582 if (is_borderline (digits, precision - 1))
3584 /* Maybe the exponent guess was too high
3585 and a smaller exponent can be reached
3586 by turning a 10...0 into 9...9x. */
3588 scale10_round_decimal_long_double (arg,
3589 (int)(precision - 1) - exponent + 1);
3590 if (digits2 == NULL)
3593 END_LONG_DOUBLE_ROUNDING ();
3596 if (strlen (digits2) == precision)
3605 /* Here ndigits = precision. */
3607 /* Determine the number of trailing zeroes
3608 that have to be dropped. */
3610 if ((flags & FLAG_ALT) == 0)
3611 while (nzeroes < ndigits
3612 && digits[nzeroes] == '0')
3615 /* The exponent is now determined. */
3617 && exponent < (long)precision)
3619 /* Fixed-point notation:
3620 max(exponent,0)+1 digits, then the
3621 decimal point, then the remaining
3622 digits without trailing zeroes. */
3625 size_t count = exponent + 1;
3626 /* Note: count <= precision = ndigits. */
3627 for (; count > 0; count--)
3628 *p++ = digits[--ndigits];
3629 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3631 *p++ = decimal_point_char ();
3632 while (ndigits > nzeroes)
3635 *p++ = digits[ndigits];
3641 size_t count = -exponent - 1;
3643 *p++ = decimal_point_char ();
3644 for (; count > 0; count--)
3646 while (ndigits > nzeroes)
3649 *p++ = digits[ndigits];
3655 /* Exponential notation. */
3656 *p++ = digits[--ndigits];
3657 if ((flags & FLAG_ALT) || ndigits > nzeroes)
3659 *p++ = decimal_point_char ();
3660 while (ndigits > nzeroes)
3663 *p++ = digits[ndigits];
3666 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3667 # if WIDE_CHAR_VERSION
3669 static const wchar_t decimal_format[] =
3670 { '%', '+', '.', '2', 'd', '\0' };
3671 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3676 if (sizeof (DCHAR_T) == 1)
3678 sprintf ((char *) p, "%+.2d", exponent);
3686 sprintf (expbuf, "%+.2d", exponent);
3687 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3699 /* arg is finite. */
3705 if (dp->conversion == 'f' || dp->conversion == 'F')
3708 if ((flags & FLAG_ALT) || precision > 0)
3710 *p++ = decimal_point_char ();
3711 for (; precision > 0; precision--)
3715 else if (dp->conversion == 'e' || dp->conversion == 'E')
3718 if ((flags & FLAG_ALT) || precision > 0)
3720 *p++ = decimal_point_char ();
3721 for (; precision > 0; precision--)
3724 *p++ = dp->conversion; /* 'e' or 'E' */
3729 else if (dp->conversion == 'g' || dp->conversion == 'G')
3732 if (flags & FLAG_ALT)
3735 (precision > 0 ? precision - 1 : 0);
3736 *p++ = decimal_point_char ();
3737 for (; ndigits > 0; --ndigits)
3741 else if (dp->conversion == 'a' || dp->conversion == 'A')
3744 *p++ = dp->conversion - 'A' + 'X';
3747 if ((flags & FLAG_ALT) || precision > 0)
3749 *p++ = decimal_point_char ();
3750 for (; precision > 0; precision--)
3753 *p++ = dp->conversion - 'A' + 'P';
3762 END_LONG_DOUBLE_ROUNDING ();
3765 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3769 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3771 double arg = a.arg[dp->arg_index].a.a_double;
3775 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3777 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3781 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3788 if (signbit (arg)) /* arg < 0.0 or negative zero */
3796 else if (flags & FLAG_SHOWSIGN)
3798 else if (flags & FLAG_SPACE)
3801 if (arg > 0.0 && arg + arg == arg)
3803 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3805 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3809 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3814 # if NEED_PRINTF_DOUBLE
3817 if (dp->conversion == 'f' || dp->conversion == 'F')
3823 scale10_round_decimal_double (arg, precision);
3826 ndigits = strlen (digits);
3828 if (ndigits > precision)
3832 *p++ = digits[ndigits];
3834 while (ndigits > precision);
3837 /* Here ndigits <= precision. */
3838 if ((flags & FLAG_ALT) || precision > 0)
3840 *p++ = decimal_point_char ();
3841 for (; precision > ndigits; precision--)
3846 *p++ = digits[ndigits];
3852 else if (dp->conversion == 'e' || dp->conversion == 'E')
3860 if ((flags & FLAG_ALT) || precision > 0)
3862 *p++ = decimal_point_char ();
3863 for (; precision > 0; precision--)
3874 exponent = floorlog10 (arg);
3879 scale10_round_decimal_double (arg,
3880 (int)precision - exponent);
3883 ndigits = strlen (digits);
3885 if (ndigits == precision + 1)
3887 if (ndigits < precision
3888 || ndigits > precision + 2)
3889 /* The exponent was not guessed
3890 precisely enough. */
3893 /* None of two values of exponent is
3894 the right one. Prevent an endless
3898 if (ndigits == precision)
3904 /* Here ndigits = precision+1. */
3905 if (is_borderline (digits, precision))
3907 /* Maybe the exponent guess was too high
3908 and a smaller exponent can be reached
3909 by turning a 10...0 into 9...9x. */
3911 scale10_round_decimal_double (arg,
3912 (int)precision - exponent + 1);
3913 if (digits2 == NULL)
3918 if (strlen (digits2) == precision + 1)
3927 /* Here ndigits = precision+1. */
3929 *p++ = digits[--ndigits];
3930 if ((flags & FLAG_ALT) || precision > 0)
3932 *p++ = decimal_point_char ();
3936 *p++ = digits[ndigits];
3943 *p++ = dp->conversion; /* 'e' or 'E' */
3944 # if WIDE_CHAR_VERSION
3946 static const wchar_t decimal_format[] =
3947 /* Produce the same number of exponent digits
3948 as the native printf implementation. */
3949 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3950 { '%', '+', '.', '3', 'd', '\0' };
3952 { '%', '+', '.', '2', 'd', '\0' };
3954 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3960 static const char decimal_format[] =
3961 /* Produce the same number of exponent digits
3962 as the native printf implementation. */
3963 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3968 if (sizeof (DCHAR_T) == 1)
3970 sprintf ((char *) p, decimal_format, exponent);
3978 sprintf (expbuf, decimal_format, exponent);
3979 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3985 else if (dp->conversion == 'g' || dp->conversion == 'G')
3989 /* precision >= 1. */
3992 /* The exponent is 0, >= -4, < precision.
3993 Use fixed-point notation. */
3995 size_t ndigits = precision;
3996 /* Number of trailing zeroes that have to be
3999 (flags & FLAG_ALT ? 0 : precision - 1);
4003 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4005 *p++ = decimal_point_char ();
4006 while (ndigits > nzeroes)
4022 exponent = floorlog10 (arg);
4027 scale10_round_decimal_double (arg,
4028 (int)(precision - 1) - exponent);
4031 ndigits = strlen (digits);
4033 if (ndigits == precision)
4035 if (ndigits < precision - 1
4036 || ndigits > precision + 1)
4037 /* The exponent was not guessed
4038 precisely enough. */
4041 /* None of two values of exponent is
4042 the right one. Prevent an endless
4046 if (ndigits < precision)
4052 /* Here ndigits = precision. */
4053 if (is_borderline (digits, precision - 1))
4055 /* Maybe the exponent guess was too high
4056 and a smaller exponent can be reached
4057 by turning a 10...0 into 9...9x. */
4059 scale10_round_decimal_double (arg,
4060 (int)(precision - 1) - exponent + 1);
4061 if (digits2 == NULL)
4066 if (strlen (digits2) == precision)
4075 /* Here ndigits = precision. */
4077 /* Determine the number of trailing zeroes
4078 that have to be dropped. */
4080 if ((flags & FLAG_ALT) == 0)
4081 while (nzeroes < ndigits
4082 && digits[nzeroes] == '0')
4085 /* The exponent is now determined. */
4087 && exponent < (long)precision)
4089 /* Fixed-point notation:
4090 max(exponent,0)+1 digits, then the
4091 decimal point, then the remaining
4092 digits without trailing zeroes. */
4095 size_t count = exponent + 1;
4096 /* Note: count <= precision = ndigits. */
4097 for (; count > 0; count--)
4098 *p++ = digits[--ndigits];
4099 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4101 *p++ = decimal_point_char ();
4102 while (ndigits > nzeroes)
4105 *p++ = digits[ndigits];
4111 size_t count = -exponent - 1;
4113 *p++ = decimal_point_char ();
4114 for (; count > 0; count--)
4116 while (ndigits > nzeroes)
4119 *p++ = digits[ndigits];
4125 /* Exponential notation. */
4126 *p++ = digits[--ndigits];
4127 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4129 *p++ = decimal_point_char ();
4130 while (ndigits > nzeroes)
4133 *p++ = digits[ndigits];
4136 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4137 # if WIDE_CHAR_VERSION
4139 static const wchar_t decimal_format[] =
4140 /* Produce the same number of exponent digits
4141 as the native printf implementation. */
4142 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4143 { '%', '+', '.', '3', 'd', '\0' };
4145 { '%', '+', '.', '2', 'd', '\0' };
4147 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4153 static const char decimal_format[] =
4154 /* Produce the same number of exponent digits
4155 as the native printf implementation. */
4156 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4161 if (sizeof (DCHAR_T) == 1)
4163 sprintf ((char *) p, decimal_format, exponent);
4171 sprintf (expbuf, decimal_format, exponent);
4172 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4185 /* arg is finite. */
4191 if (dp->conversion == 'f' || dp->conversion == 'F')
4194 if ((flags & FLAG_ALT) || precision > 0)
4196 *p++ = decimal_point_char ();
4197 for (; precision > 0; precision--)
4201 else if (dp->conversion == 'e' || dp->conversion == 'E')
4204 if ((flags & FLAG_ALT) || precision > 0)
4206 *p++ = decimal_point_char ();
4207 for (; precision > 0; precision--)
4210 *p++ = dp->conversion; /* 'e' or 'E' */
4212 /* Produce the same number of exponent digits as
4213 the native printf implementation. */
4214 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4220 else if (dp->conversion == 'g' || dp->conversion == 'G')
4223 if (flags & FLAG_ALT)
4226 (precision > 0 ? precision - 1 : 0);
4227 *p++ = decimal_point_char ();
4228 for (; ndigits > 0; --ndigits)
4240 /* The generated string now extends from tmp to p, with the
4241 zero padding insertion point being at pad_ptr. */
4242 if (has_width && p - tmp < width)
4244 size_t pad = width - (p - tmp);
4245 DCHAR_T *end = p + pad;
4247 if (flags & FLAG_LEFT)
4249 /* Pad with spaces on the right. */
4250 for (; pad > 0; pad--)
4253 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4255 /* Pad with zeroes. */
4260 for (; pad > 0; pad--)
4265 /* Pad with spaces on the left. */
4270 for (; pad > 0; pad--)
4278 size_t count = p - tmp;
4280 if (count >= tmp_length)
4281 /* tmp_length was incorrectly calculated - fix the
4285 /* Make room for the result. */
4286 if (count >= allocated - length)
4288 size_t n = xsum (length, count);
4290 ENSURE_ALLOCATION (n);
4293 /* Append the result. */
4294 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4303 arg_type type = a.arg[dp->arg_index].type;
4304 int flags = dp->flags;
4305 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4309 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4313 #if NEED_PRINTF_UNBOUNDED_PRECISION
4316 # define prec_ourselves 0
4318 #if NEED_PRINTF_FLAG_LEFTADJUST
4319 # define pad_ourselves 1
4320 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4323 # define pad_ourselves 0
4326 unsigned int prefix_count;
4327 int prefixes[2] IF_LINT (= { 0 });
4330 TCHAR_T tmpbuf[700];
4334 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4337 if (dp->width_start != dp->width_end)
4339 if (dp->width_arg_index != ARG_NONE)
4343 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4345 arg = a.arg[dp->width_arg_index].a.a_int;
4348 /* "A negative field width is taken as a '-' flag
4349 followed by a positive field width." */
4351 width = (unsigned int) (-arg);
4358 const FCHAR_T *digitp = dp->width_start;
4361 width = xsum (xtimes (width, 10), *digitp++ - '0');
4362 while (digitp != dp->width_end);
4368 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4371 if (dp->precision_start != dp->precision_end)
4373 if (dp->precision_arg_index != ARG_NONE)
4377 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4379 arg = a.arg[dp->precision_arg_index].a.a_int;
4380 /* "A negative precision is taken as if the precision
4390 const FCHAR_T *digitp = dp->precision_start + 1;
4393 while (digitp != dp->precision_end)
4394 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4400 /* Decide whether to handle the precision ourselves. */
4401 #if NEED_PRINTF_UNBOUNDED_PRECISION
4402 switch (dp->conversion)
4404 case 'd': case 'i': case 'u':
4406 case 'x': case 'X': case 'p':
4407 prec_ourselves = has_precision && (precision > 0);
4415 /* Decide whether to perform the padding ourselves. */
4416 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4417 switch (dp->conversion)
4419 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4420 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4421 to perform the padding after this conversion. Functions
4422 with unistdio extensions perform the padding based on
4423 character count rather than element count. */
4426 # if NEED_PRINTF_FLAG_ZERO
4427 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4433 pad_ourselves = prec_ourselves;
4439 /* Allocate a temporary buffer of sufficient size for calling
4442 switch (dp->conversion)
4445 case 'd': case 'i': case 'u':
4446 # if HAVE_LONG_LONG_INT
4447 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4449 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4450 * 0.30103 /* binary -> decimal */
4452 + 1; /* turn floor into ceil */
4455 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4457 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4458 * 0.30103 /* binary -> decimal */
4460 + 1; /* turn floor into ceil */
4463 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4464 * 0.30103 /* binary -> decimal */
4466 + 1; /* turn floor into ceil */
4467 if (tmp_length < precision)
4468 tmp_length = precision;
4469 /* Multiply by 2, as an estimate for FLAG_GROUP. */
4470 tmp_length = xsum (tmp_length, tmp_length);
4471 /* Add 1, to account for a leading sign. */
4472 tmp_length = xsum (tmp_length, 1);
4476 # if HAVE_LONG_LONG_INT
4477 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4479 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4480 * 0.333334 /* binary -> octal */
4482 + 1; /* turn floor into ceil */
4485 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4487 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4488 * 0.333334 /* binary -> octal */
4490 + 1; /* turn floor into ceil */
4493 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4494 * 0.333334 /* binary -> octal */
4496 + 1; /* turn floor into ceil */
4497 if (tmp_length < precision)
4498 tmp_length = precision;
4499 /* Add 1, to account for a leading sign. */
4500 tmp_length = xsum (tmp_length, 1);
4504 # if HAVE_LONG_LONG_INT
4505 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
4507 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
4508 * 0.25 /* binary -> hexadecimal */
4510 + 1; /* turn floor into ceil */
4513 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
4515 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
4516 * 0.25 /* binary -> hexadecimal */
4518 + 1; /* turn floor into ceil */
4521 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
4522 * 0.25 /* binary -> hexadecimal */
4524 + 1; /* turn floor into ceil */
4525 if (tmp_length < precision)
4526 tmp_length = precision;
4527 /* Add 2, to account for a leading sign or alternate form. */
4528 tmp_length = xsum (tmp_length, 2);
4532 if (type == TYPE_LONGDOUBLE)
4534 (unsigned int) (LDBL_MAX_EXP
4535 * 0.30103 /* binary -> decimal */
4536 * 2 /* estimate for FLAG_GROUP */
4538 + 1 /* turn floor into ceil */
4539 + 10; /* sign, decimal point etc. */
4542 (unsigned int) (DBL_MAX_EXP
4543 * 0.30103 /* binary -> decimal */
4544 * 2 /* estimate for FLAG_GROUP */
4546 + 1 /* turn floor into ceil */
4547 + 10; /* sign, decimal point etc. */
4548 tmp_length = xsum (tmp_length, precision);
4551 case 'e': case 'E': case 'g': case 'G':
4553 12; /* sign, decimal point, exponent etc. */
4554 tmp_length = xsum (tmp_length, precision);
4558 if (type == TYPE_LONGDOUBLE)
4560 (unsigned int) (LDBL_DIG
4561 * 0.831 /* decimal -> hexadecimal */
4563 + 1; /* turn floor into ceil */
4566 (unsigned int) (DBL_DIG
4567 * 0.831 /* decimal -> hexadecimal */
4569 + 1; /* turn floor into ceil */
4570 if (tmp_length < precision)
4571 tmp_length = precision;
4572 /* Account for sign, decimal point etc. */
4573 tmp_length = xsum (tmp_length, 12);
4577 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
4578 if (type == TYPE_WIDE_CHAR)
4579 tmp_length = MB_CUR_MAX;
4587 if (type == TYPE_WIDE_STRING)
4589 # if WIDE_CHAR_VERSION
4590 /* ISO C says about %ls in fwprintf:
4591 "If the precision is not specified or is greater
4592 than the size of the array, the array shall
4593 contain a null wide character."
4594 So if there is a precision, we must not use
4596 const wchar_t *arg =
4597 a.arg[dp->arg_index].a.a_wide_string;
4600 tmp_length = local_wcsnlen (arg, precision);
4602 tmp_length = local_wcslen (arg);
4604 /* ISO C says about %ls in fprintf:
4605 "If a precision is specified, no more than that
4606 many bytes are written (including shift
4607 sequences, if any), and the array shall contain
4608 a null wide character if, to equal the
4609 multibyte character sequence length given by
4610 the precision, the function would need to
4611 access a wide character one past the end of the
4613 So if there is a precision, we must not use
4615 /* This case has already been handled above. */
4622 # if WIDE_CHAR_VERSION
4623 /* ISO C says about %s in fwprintf:
4624 "If the precision is not specified or is greater
4625 than the size of the converted array, the
4626 converted array shall contain a null wide
4628 So if there is a precision, we must not use
4630 /* This case has already been handled above. */
4633 /* ISO C says about %s in fprintf:
4634 "If the precision is not specified or greater
4635 than the size of the array, the array shall
4636 contain a null character."
4637 So if there is a precision, we must not use
4639 const char *arg = a.arg[dp->arg_index].a.a_string;
4642 tmp_length = local_strnlen (arg, precision);
4644 tmp_length = strlen (arg);
4651 (unsigned int) (sizeof (void *) * CHAR_BIT
4652 * 0.25 /* binary -> hexadecimal */
4654 + 1 /* turn floor into ceil */
4655 + 2; /* account for leading 0x */
4664 # if ENABLE_UNISTDIO
4665 /* Padding considers the number of characters, therefore
4666 the number of elements after padding may be
4667 > max (tmp_length, width)
4669 <= tmp_length + width. */
4670 tmp_length = xsum (tmp_length, width);
4672 /* Padding considers the number of elements,
4674 if (tmp_length < width)
4679 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
4682 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4686 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4688 if (size_overflow_p (tmp_memsize))
4689 /* Overflow, would lead to out of memory. */
4691 tmp = (TCHAR_T *) malloc (tmp_memsize);
4693 /* Out of memory. */
4698 /* Construct the format string for calling snprintf or
4702 #if NEED_PRINTF_FLAG_GROUPING
4703 /* The underlying implementation doesn't support the ' flag.
4704 Produce no grouping characters in this case; this is
4705 acceptable because the grouping is locale dependent. */
4707 if (flags & FLAG_GROUP)
4710 if (flags & FLAG_LEFT)
4712 if (flags & FLAG_SHOWSIGN)
4714 if (flags & FLAG_SPACE)
4716 if (flags & FLAG_ALT)
4720 if (flags & FLAG_ZERO)
4722 if (dp->width_start != dp->width_end)
4724 size_t n = dp->width_end - dp->width_start;
4725 /* The width specification is known to consist only
4726 of standard ASCII characters. */
4727 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4729 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4734 const FCHAR_T *mp = dp->width_start;
4736 *fbp++ = (unsigned char) *mp++;
4741 if (!prec_ourselves)
4743 if (dp->precision_start != dp->precision_end)
4745 size_t n = dp->precision_end - dp->precision_start;
4746 /* The precision specification is known to consist only
4747 of standard ASCII characters. */
4748 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4750 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4755 const FCHAR_T *mp = dp->precision_start;
4757 *fbp++ = (unsigned char) *mp++;
4765 #if HAVE_LONG_LONG_INT
4766 case TYPE_LONGLONGINT:
4767 case TYPE_ULONGLONGINT:
4768 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4781 case TYPE_WIDE_CHAR:
4784 case TYPE_WIDE_STRING:
4788 case TYPE_LONGDOUBLE:
4794 #if NEED_PRINTF_DIRECTIVE_F
4795 if (dp->conversion == 'F')
4799 *fbp = dp->conversion;
4801 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4806 /* On glibc2 systems from glibc >= 2.3 - probably also older
4807 ones - we know that snprintf's returns value conforms to
4808 ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4809 Therefore we can avoid using %n in this situation.
4810 On glibc2 systems from 2004-10-18 or newer, the use of %n
4811 in format strings in writable memory may crash the program
4812 (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4813 in this situation. */
4814 /* On native Win32 systems (such as mingw), we can avoid using
4816 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4817 snprintf does not write more than the specified number
4818 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4819 '4', '5', '6' into buf, not '4', '5', '\0'.)
4820 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4821 allows us to recognize the case of an insufficient
4822 buffer size: it returns -1 in this case.
4823 On native Win32 systems (such as mingw) where the OS is
4824 Windows Vista, the use of %n in format strings by default
4825 crashes the program. See
4826 <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4827 <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4828 So we should avoid %n in this situation. */
4835 /* Construct the arguments for calling snprintf or sprintf. */
4837 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4839 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4841 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4843 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
4845 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4847 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4851 /* The SNPRINTF result is appended after result[0..length].
4852 The latter is an array of DCHAR_T; SNPRINTF appends an
4853 array of TCHAR_T to it. This is possible because
4854 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4855 alignof (TCHAR_T) <= alignof (DCHAR_T). */
4856 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4857 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
4858 where an snprintf() with maxlen==1 acts like sprintf(). */
4859 ENSURE_ALLOCATION (xsum (length,
4860 (2 + TCHARS_PER_DCHAR - 1)
4861 / TCHARS_PER_DCHAR));
4862 /* Prepare checking whether snprintf returns the count
4864 *(TCHAR_T *) (result + length) = '\0';
4873 size_t maxlen = allocated - length;
4874 /* SNPRINTF can fail if its second argument is
4876 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4877 maxlen = INT_MAX / TCHARS_PER_DCHAR;
4878 maxlen = maxlen * TCHARS_PER_DCHAR;
4879 # define SNPRINTF_BUF(arg) \
4880 switch (prefix_count) \
4883 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4888 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4890 prefixes[0], arg, &count); \
4893 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4895 prefixes[0], prefixes[1], arg, \
4902 # define SNPRINTF_BUF(arg) \
4903 switch (prefix_count) \
4906 count = sprintf (tmp, buf, arg); \
4909 count = sprintf (tmp, buf, prefixes[0], arg); \
4912 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4924 int arg = a.arg[dp->arg_index].a.a_schar;
4930 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4936 int arg = a.arg[dp->arg_index].a.a_short;
4942 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4948 int arg = a.arg[dp->arg_index].a.a_int;
4954 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4960 long int arg = a.arg[dp->arg_index].a.a_longint;
4966 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4970 #if HAVE_LONG_LONG_INT
4971 case TYPE_LONGLONGINT:
4973 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4977 case TYPE_ULONGLONGINT:
4979 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4986 double arg = a.arg[dp->arg_index].a.a_double;
4990 case TYPE_LONGDOUBLE:
4992 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4998 int arg = a.arg[dp->arg_index].a.a_char;
5003 case TYPE_WIDE_CHAR:
5005 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5012 const char *arg = a.arg[dp->arg_index].a.a_string;
5017 case TYPE_WIDE_STRING:
5019 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5026 void *arg = a.arg[dp->arg_index].a.a_pointer;
5035 /* Portability: Not all implementations of snprintf()
5036 are ISO C 99 compliant. Determine the number of
5037 bytes that snprintf() has produced or would have
5041 /* Verify that snprintf() has NUL-terminated its
5044 && ((TCHAR_T *) (result + length)) [count] != '\0')
5046 /* Portability hack. */
5047 if (retcount > count)
5052 /* snprintf() doesn't understand the '%n'
5056 /* Don't use the '%n' directive; instead, look
5057 at the snprintf() return value. */
5063 /* Look at the snprintf() return value. */
5066 /* HP-UX 10.20 snprintf() is doubly deficient:
5067 It doesn't understand the '%n' directive,
5068 *and* it returns -1 (rather than the length
5069 that would have been required) when the
5070 buffer is too small. */
5071 size_t bigger_need =
5072 xsum (xtimes (allocated, 2), 12);
5073 ENSURE_ALLOCATION (bigger_need);
5082 /* Attempt to handle failure. */
5085 if (!(result == resultbuf || result == NULL))
5087 if (buf_malloced != NULL)
5088 free (buf_malloced);
5095 /* Handle overflow of the allocated buffer.
5096 If such an overflow occurs, a C99 compliant snprintf()
5097 returns a count >= maxlen. However, a non-compliant
5098 snprintf() function returns only count = maxlen - 1. To
5099 cover both cases, test whether count >= maxlen - 1. */
5100 if ((unsigned int) count + 1 >= maxlen)
5102 /* If maxlen already has attained its allowed maximum,
5103 allocating more memory will not increase maxlen.
5104 Instead of looping, bail out. */
5105 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5109 /* Need at least (count + 1) * sizeof (TCHAR_T)
5110 bytes. (The +1 is for the trailing NUL.)
5111 But ask for (count + 2) * sizeof (TCHAR_T)
5112 bytes, so that in the next round, we likely get
5113 maxlen > (unsigned int) count + 1
5114 and so we don't get here again.
5115 And allocate proportionally, to avoid looping
5116 eternally if snprintf() reports a too small
5120 ((unsigned int) count + 2
5121 + TCHARS_PER_DCHAR - 1)
5122 / TCHARS_PER_DCHAR),
5123 xtimes (allocated, 2));
5125 ENSURE_ALLOCATION (n);
5131 #if NEED_PRINTF_UNBOUNDED_PRECISION
5134 /* Handle the precision. */
5137 (TCHAR_T *) (result + length);
5141 size_t prefix_count;
5145 /* Put the additional zeroes after the sign. */
5147 && (*prec_ptr == '-' || *prec_ptr == '+'
5148 || *prec_ptr == ' '))
5150 /* Put the additional zeroes after the 0x prefix if
5151 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5153 && prec_ptr[0] == '0'
5154 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5157 move = count - prefix_count;
5158 if (precision > move)
5160 /* Insert zeroes. */
5161 size_t insert = precision - move;
5167 (count + insert + TCHARS_PER_DCHAR - 1)
5168 / TCHARS_PER_DCHAR);
5169 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5170 ENSURE_ALLOCATION (n);
5171 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5172 prec_ptr = (TCHAR_T *) (result + length);
5175 prec_end = prec_ptr + count;
5176 prec_ptr += prefix_count;
5178 while (prec_end > prec_ptr)
5181 prec_end[insert] = prec_end[0];
5187 while (prec_end > prec_ptr);
5195 if (count >= tmp_length)
5196 /* tmp_length was incorrectly calculated - fix the
5202 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5203 if (dp->conversion == 'c' || dp->conversion == 's')
5205 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5207 The result string is not certainly ASCII. */
5208 const TCHAR_T *tmpsrc;
5211 /* This code assumes that TCHAR_T is 'char'. */
5212 typedef int TCHAR_T_verify
5213 [2 * (sizeof (TCHAR_T) == 1) - 1];
5215 tmpsrc = (TCHAR_T *) (result + length);
5221 if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
5222 iconveh_question_mark,
5225 &tmpdst, &tmpdst_len)
5228 int saved_errno = errno;
5229 if (!(result == resultbuf || result == NULL))
5231 if (buf_malloced != NULL)
5232 free (buf_malloced);
5234 errno = saved_errno;
5237 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5238 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5244 /* The result string is ASCII.
5245 Simple 1:1 conversion. */
5247 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5248 no-op conversion, in-place on the array starting
5249 at (result + length). */
5250 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5253 const TCHAR_T *tmpsrc;
5258 if (result == resultbuf)
5260 tmpsrc = (TCHAR_T *) (result + length);
5261 /* ENSURE_ALLOCATION will not move tmpsrc
5262 (because it's part of resultbuf). */
5263 ENSURE_ALLOCATION (xsum (length, count));
5267 /* ENSURE_ALLOCATION will move the array
5268 (because it uses realloc(). */
5269 ENSURE_ALLOCATION (xsum (length, count));
5270 tmpsrc = (TCHAR_T *) (result + length);
5274 ENSURE_ALLOCATION (xsum (length, count));
5276 tmpdst = result + length;
5277 /* Copy backwards, because of overlapping. */
5280 for (n = count; n > 0; n--)
5281 *--tmpdst = (unsigned char) *--tmpsrc;
5286 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5287 /* Make room for the result. */
5288 if (count > allocated - length)
5290 /* Need at least count elements. But allocate
5293 xmax (xsum (length, count), xtimes (allocated, 2));
5295 ENSURE_ALLOCATION (n);
5299 /* Here count <= allocated - length. */
5301 /* Perform padding. */
5302 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5303 if (pad_ourselves && has_width)
5306 # if ENABLE_UNISTDIO
5307 /* Outside POSIX, it's preferrable to compare the width
5308 against the number of _characters_ of the converted
5310 w = DCHAR_MBSNLEN (result + length, count);
5312 /* The width is compared against the number of _bytes_
5313 of the converted value, says POSIX. */
5318 size_t pad = width - w;
5320 /* Make room for the result. */
5321 if (xsum (count, pad) > allocated - length)
5323 /* Need at least count + pad elements. But
5324 allocate proportionally. */
5326 xmax (xsum3 (length, count, pad),
5327 xtimes (allocated, 2));
5331 ENSURE_ALLOCATION (n);
5334 ENSURE_ALLOCATION (n);
5337 /* Here count + pad <= allocated - length. */
5340 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5341 DCHAR_T * const rp = result + length;
5343 DCHAR_T * const rp = tmp;
5345 DCHAR_T *p = rp + count;
5346 DCHAR_T *end = p + pad;
5348 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5349 if (dp->conversion == 'c'
5350 || dp->conversion == 's')
5351 /* No zero-padding for string directives. */
5356 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5357 /* No zero-padding of "inf" and "nan". */
5358 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5359 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5362 /* The generated string now extends from rp to p,
5363 with the zero padding insertion point being at
5366 count = count + pad; /* = end - rp */
5368 if (flags & FLAG_LEFT)
5370 /* Pad with spaces on the right. */
5371 for (; pad > 0; pad--)
5374 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5376 /* Pad with zeroes. */
5381 for (; pad > 0; pad--)
5386 /* Pad with spaces on the left. */
5391 for (; pad > 0; pad--)
5399 /* Here still count <= allocated - length. */
5401 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5402 /* The snprintf() result did fit. */
5404 /* Append the sprintf() result. */
5405 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5412 #if NEED_PRINTF_DIRECTIVE_F
5413 if (dp->conversion == 'F')
5415 /* Convert the %f result to upper case for %F. */
5416 DCHAR_T *rp = result + length;
5418 for (rc = count; rc > 0; rc--, rp++)
5419 if (*rp >= 'a' && *rp <= 'z')
5420 *rp = *rp - 'a' + 'A';
5431 /* Add the final NUL. */
5432 ENSURE_ALLOCATION (xsum (length, 1));
5433 result[length] = '\0';
5435 if (result != resultbuf && length + 1 < allocated)
5437 /* Shrink the allocated memory if possible. */
5440 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5445 if (buf_malloced != NULL)
5446 free (buf_malloced);
5449 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5450 says that snprintf() fails with errno = EOVERFLOW in this case, but
5451 that's only because snprintf() returns an 'int'. This function does
5452 not have this limitation. */
5457 if (!(result == resultbuf || result == NULL))
5459 if (buf_malloced != NULL)
5460 free (buf_malloced);
5467 if (!(result == resultbuf || result == NULL))
5469 if (buf_malloced != NULL)
5470 free (buf_malloced);
5478 #undef TCHARS_PER_DCHAR
5485 #undef DCHAR_IS_TCHAR