1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2007 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
19 This must come before <config.h> because <config.h> may include
20 <features.h>, and once <features.h> has been included, it's too late. */
22 # define _GNU_SOURCE 1
32 # include "vasnwprintf.h"
34 # include "vasnprintf.h"
37 #include <locale.h> /* localeconv() */
38 #include <stdio.h> /* snprintf(), sprintf() */
39 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
40 #include <string.h> /* memcpy(), strlen() */
41 #include <errno.h> /* errno */
42 #include <limits.h> /* CHAR_BIT */
43 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
45 # include <langinfo.h>
48 # include "wprintf-parse.h"
50 # include "printf-parse.h"
53 /* Checked size_t computations. */
56 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
59 # include "printf-frexp.h"
60 # include "isnanl-nolibm.h"
61 # include "printf-frexpl.h"
65 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
70 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
72 # define EOVERFLOW E2BIG
77 # define local_wcslen wcslen
79 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
80 a dependency towards this library, here is a local substitute.
81 Define this substitute only once, even if this file is included
82 twice in the same compilation unit. */
83 # ifndef local_wcslen_defined
84 # define local_wcslen_defined 1
86 local_wcslen (const wchar_t *s)
90 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
99 # define VASNPRINTF vasnwprintf
100 # define CHAR_T wchar_t
101 # define DIRECTIVE wchar_t_directive
102 # define DIRECTIVES wchar_t_directives
103 # define PRINTF_PARSE wprintf_parse
104 # define USE_SNPRINTF 1
105 # if HAVE_DECL__SNWPRINTF
106 /* On Windows, the function swprintf() has a different signature than
107 on Unix; we use the _snwprintf() function instead. */
108 # define SNPRINTF _snwprintf
111 # define SNPRINTF swprintf
114 # define VASNPRINTF vasnprintf
116 # define DIRECTIVE char_directive
117 # define DIRECTIVES char_directives
118 # define PRINTF_PARSE printf_parse
119 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
120 But don't use it on BeOS, since BeOS snprintf produces no output if the
121 size argument is >= 0x3000000. */
122 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
123 # define USE_SNPRINTF 1
125 # define USE_SNPRINTF 0
127 # if HAVE_DECL__SNPRINTF
129 # define SNPRINTF _snprintf
132 # define SNPRINTF snprintf
133 /* Here we need to call the native snprintf, not rpl_snprintf. */
137 /* Here we need to call the native sprintf, not rpl_sprintf. */
140 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
141 /* Determine the decimal-point character according to the current locale. */
142 # ifndef decimal_point_char_defined
143 # define decimal_point_char_defined 1
145 decimal_point_char ()
148 /* Determine it in a multithread-safe way. We know nl_langinfo is
149 multithread-safe on glibc systems, but is not required to be multithread-
150 safe by POSIX. sprintf(), however, is multithread-safe. localeconv()
151 is rarely multithread-safe. */
152 # if HAVE_NL_LANGINFO && __GLIBC__
153 point = nl_langinfo (RADIXCHAR);
156 sprintf (pointbuf, "%#.0f", 1.0);
157 point = &pointbuf[1];
159 point = localeconv () -> decimal_point;
161 /* The decimal point is always a single byte: either '.' or ','. */
162 return (point[0] != '\0' ? point[0] : '.');
167 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
169 /* Converting 'long double' to decimal without rare rounding bugs requires
170 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
171 (and slower) algorithms. */
173 typedef unsigned int mp_limb_t;
174 # define GMP_LIMB_BITS 32
175 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
177 typedef unsigned long long mp_twolimb_t;
178 # define GMP_TWOLIMB_BITS 64
179 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
181 /* Representation of a bignum >= 0. */
185 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
188 /* Compute the product of two bignums >= 0.
189 Return the allocated memory in case of success, NULL in case of memory
190 allocation failure. */
192 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
199 if (src1.nlimbs <= src2.nlimbs)
213 /* Now 0 <= len1 <= len2. */
216 /* src1 or src2 is zero. */
218 dest->limbs = (mp_limb_t *) malloc (1);
222 /* Here 1 <= len1 <= len2. */
228 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
231 for (k = len2; k > 0; )
233 for (i = 0; i < len1; i++)
235 mp_limb_t digit1 = p1[i];
236 mp_twolimb_t carry = 0;
237 for (j = 0; j < len2; j++)
239 mp_limb_t digit2 = p2[j];
240 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
242 dp[i + j] = (mp_limb_t) carry;
243 carry = carry >> GMP_LIMB_BITS;
245 dp[i + len2] = (mp_limb_t) carry;
248 while (dlen > 0 && dp[dlen - 1] == 0)
256 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
257 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
259 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
261 Return the allocated memory in case of success, NULL in case of memory
262 allocation failure. */
264 divide (mpn_t a, mpn_t b, mpn_t *q)
267 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
268 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
269 If m<n, then q:=0 and r:=a.
270 If m>=n=1, perform a single-precision division:
273 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
274 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
275 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
276 Normalise [q[m-1],...,q[0]], yields q.
277 If m>=n>1, perform a multiple-precision division:
278 We have a/b < beta^(m-n+1).
279 s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
280 Shift a and b left by s bits, copying them. r:=a.
281 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
282 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
284 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
285 In case of overflow (q* >= beta) set q* := beta-1.
286 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
287 and c3 := b[n-2] * q*.
288 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
289 occurred. Furthermore 0 <= c3 < beta^2.
290 If there was overflow and
291 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
292 the next test can be skipped.}
293 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
294 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
296 Put r := r - b * q* * beta^j. In detail:
297 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
298 hence: u:=0, for i:=0 to n-1 do
300 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
301 u:=u div beta (+ 1, if carry in subtraction)
303 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
305 the carry u does not overflow.}
306 If a negative carry occurs, put q* := q* - 1
307 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
309 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
310 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
312 The room for q[j] can be allocated at the memory location of r[n+j].
313 Finally, round-to-even:
314 Shift r left by 1 bit.
315 If r > b or if r = b and q[0] is odd, q := q+1.
317 const mp_limb_t *a_ptr = a.limbs;
318 size_t a_len = a.nlimbs;
319 const mp_limb_t *b_ptr = b.limbs;
320 size_t b_len = b.nlimbs;
322 mp_limb_t *tmp_roomptr = NULL;
328 /* Allocate room for a_len+2 digits.
329 (Need a_len+1 digits for the real division and 1 more digit for the
330 final rounding of q.) */
331 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
336 while (a_len > 0 && a_ptr[a_len - 1] == 0)
343 /* Division by zero. */
345 if (b_ptr[b_len - 1] == 0)
351 /* Here m = a_len >= 0 and n = b_len > 0. */
355 /* m<n: trivial case. q=0, r := copy of a. */
358 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
359 q_ptr = roomptr + a_len;
364 /* n=1: single precision division.
365 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
369 mp_limb_t den = b_ptr[0];
370 mp_limb_t remainder = 0;
371 const mp_limb_t *sourceptr = a_ptr + a_len;
372 mp_limb_t *destptr = q_ptr + a_len;
374 for (count = a_len; count > 0; count--)
377 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
378 *--destptr = num / den;
379 remainder = num % den;
381 /* Normalise and store r. */
384 r_ptr[0] = remainder;
391 if (q_ptr[q_len - 1] == 0)
397 /* n>1: multiple precision division.
398 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
399 beta^(m-n-1) <= a/b < beta^(m-n+1). */
403 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
431 /* 0 <= s < GMP_LIMB_BITS.
432 Copy b, shifting it left by s bits. */
435 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
436 if (tmp_roomptr == NULL)
442 const mp_limb_t *sourceptr = b_ptr;
443 mp_limb_t *destptr = tmp_roomptr;
444 mp_twolimb_t accu = 0;
446 for (count = b_len; count > 0; count--)
448 accu += (mp_twolimb_t) *sourceptr++ << s;
449 *destptr++ = (mp_limb_t) accu;
450 accu = accu >> GMP_LIMB_BITS;
452 /* accu must be zero, since that was how s was determined. */
458 /* Copy a, shifting it left by s bits, yields r.
460 At the beginning: r = roomptr[0..a_len],
461 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
465 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
470 const mp_limb_t *sourceptr = a_ptr;
471 mp_limb_t *destptr = r_ptr;
472 mp_twolimb_t accu = 0;
474 for (count = a_len; count > 0; count--)
476 accu += (mp_twolimb_t) *sourceptr++ << s;
477 *destptr++ = (mp_limb_t) accu;
478 accu = accu >> GMP_LIMB_BITS;
480 *destptr++ = (mp_limb_t) accu;
482 q_ptr = roomptr + b_len;
483 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
485 size_t j = a_len - b_len; /* m-n */
486 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
487 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
488 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
489 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
490 /* Division loop, traversed m-n+1 times.
491 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
496 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
498 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
500 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
501 | r_ptr[j + b_len - 1];
502 q_star = num / b_msd;
507 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
508 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
509 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
510 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
511 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
513 If yes, jump directly to the subtraction loop.
514 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
515 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
516 if (r_ptr[j + b_len] > b_msd
517 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
518 /* r[j+n] >= b[n-1]+1 or
519 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
524 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
526 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
527 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
528 mp_twolimb_t c3 = /* b[n-2] * q* */
529 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
530 /* While c2 < c3, increase c2 and decrease c3.
531 Consider c3-c2. While it is > 0, decrease it by
532 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
533 this can happen only twice. */
536 q_star = q_star - 1; /* q* := q* - 1 */
537 if (c3 - c2 > b_msdd)
538 q_star = q_star - 1; /* q* := q* - 1 */
544 /* Subtract r := r - b * q* * beta^j. */
547 const mp_limb_t *sourceptr = b_ptr;
548 mp_limb_t *destptr = r_ptr + j;
549 mp_twolimb_t carry = 0;
551 for (count = b_len; count > 0; count--)
553 /* Here 0 <= carry <= q*. */
556 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
557 + (mp_limb_t) ~(*destptr);
558 /* Here 0 <= carry <= beta*q* + beta-1. */
559 *destptr++ = ~(mp_limb_t) carry;
560 carry = carry >> GMP_LIMB_BITS; /* <= q* */
562 cr = (mp_limb_t) carry;
564 /* Subtract cr from r_ptr[j + b_len], then forget about
566 if (cr > r_ptr[j + b_len])
568 /* Subtraction gave a carry. */
569 q_star = q_star - 1; /* q* := q* - 1 */
572 const mp_limb_t *sourceptr = b_ptr;
573 mp_limb_t *destptr = r_ptr + j;
576 for (count = b_len; count > 0; count--)
578 mp_limb_t source1 = *sourceptr++;
579 mp_limb_t source2 = *destptr;
580 *destptr++ = source1 + source2 + carry;
583 ? source1 >= (mp_limb_t) ~source2
584 : source1 > (mp_limb_t) ~source2);
587 /* Forget about the carry and about r[j+n]. */
590 /* q* is determined. Store it as q[j]. */
599 if (q_ptr[q_len - 1] == 0)
601 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
602 b is shifted left by s bits. */
603 /* Shift r right by s bits. */
606 mp_limb_t ptr = r_ptr + r_len;
607 mp_twolimb_t accu = 0;
609 for (count = r_len; count > 0; count--)
611 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
612 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
613 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
618 while (r_len > 0 && r_ptr[r_len - 1] == 0)
621 /* Compare r << 1 with b. */
629 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
630 | (i < r_len ? r_ptr[i] << 1 : 0);
631 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
641 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
646 for (i = 0; i < q_len; i++)
647 if (++(q_ptr[i]) != 0)
652 if (tmp_roomptr != NULL)
659 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
661 Destroys the contents of a.
662 Return the allocated memory - containing the decimal digits in low-to-high
663 order, terminated with a NUL character - in case of success, NULL in case
664 of memory allocation failure. */
666 convert_to_decimal (mpn_t a, size_t extra_zeroes)
668 mp_limb_t *a_ptr = a.limbs;
669 size_t a_len = a.nlimbs;
670 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
671 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
672 char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
676 for (; extra_zeroes > 0; extra_zeroes--)
680 /* Divide a by 10^9, in-place. */
681 mp_limb_t remainder = 0;
682 mp_limb_t *ptr = a_ptr + a_len;
684 for (count = a_len; count > 0; count--)
687 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
688 *ptr = num / 1000000000;
689 remainder = num % 1000000000;
691 /* Store the remainder as 9 decimal digits. */
692 for (count = 9; count > 0; count--)
694 *d_ptr++ = '0' + (remainder % 10);
695 remainder = remainder / 10;
698 if (a_ptr[a_len - 1] == 0)
701 /* Remove leading zeroes. */
702 while (d_ptr > c_ptr && d_ptr[-1] == '0')
704 /* But keep at least one zero. */
707 /* Terminate the string. */
713 /* Assuming x is finite and >= 0:
714 write x as x = 2^e * m, where m is a bignum.
715 Return the allocated memory in case of success, NULL in case of memory
716 allocation failure. */
718 decode_long_double (long double x, int *ep, mpn_t *mp)
725 /* Allocate memory for result. */
726 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
727 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
730 /* Split into exponential part and mantissa. */
731 y = frexpl (x, &exp);
732 if (!(y >= 0.0L && y < 1.0L))
734 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
735 latter is an integer. */
736 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
737 I'm not sure whether it's safe to cast a 'long double' value between
738 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
739 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
741 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
742 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
745 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
748 if (!(y >= 0.0L && y < 1.0L))
750 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
753 if (!(y >= 0.0L && y < 1.0L))
755 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
760 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
763 if (!(y >= 0.0L && y < 1.0L))
765 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
769 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
772 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
775 if (!(y >= 0.0L && y < 1.0L))
777 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
780 if (!(y >= 0.0L && y < 1.0L))
782 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
787 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
790 *ep = exp - LDBL_MANT_BIT;
794 /* Assuming x is finite and >= 0, and n is an integer:
795 Returns the decimal representation of round (x * 10^n).
796 Return the allocated memory - containing the decimal digits in low-to-high
797 order, terminated with a NUL character - in case of success, NULL in case
798 of memory allocation failure. */
800 scale10_round_decimal_long_double (long double x, int n)
804 void *memory = decode_long_double (x, &e, &m);
811 unsigned int s_limbs;
820 /* x = 2^e * m, hence
821 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
822 = round (2^s * 5^n * m). */
825 /* Factor out a common power of 10 if possible. */
828 extra_zeroes = (s < n ? s : n);
832 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
833 Before converting to decimal, we need to compute
834 z = round (2^s * 5^n * m). */
835 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
836 sign. 2.322 is slightly larger than log(5)/log(2). */
837 abs_n = (n >= 0 ? n : -n);
838 abs_s = (s >= 0 ? s : -s);
839 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
840 + abs_s / GMP_LIMB_BITS + 1)
841 * sizeof (mp_limb_t));
842 if (pow5_ptr == NULL)
847 /* Initialize with 1. */
850 /* Multiply with 5^|n|. */
853 static mp_limb_t const small_pow5[13 + 1] =
855 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
856 48828125, 244140625, 1220703125
859 for (n13 = 0; n13 <= abs_n; n13 += 13)
861 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
863 mp_twolimb_t carry = 0;
864 for (j = 0; j < pow5_len; j++)
866 mp_limb_t digit2 = pow5_ptr[j];
867 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
868 pow5_ptr[j] = (mp_limb_t) carry;
869 carry = carry >> GMP_LIMB_BITS;
872 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
875 s_limbs = abs_s / GMP_LIMB_BITS;
876 s_bits = abs_s % GMP_LIMB_BITS;
877 if (n >= 0 ? s >= 0 : s <= 0)
879 /* Multiply with 2^|s|. */
882 mp_limb_t *ptr = pow5_ptr;
883 mp_twolimb_t accu = 0;
885 for (count = pow5_len; count > 0; count--)
887 accu += (mp_twolimb_t) *ptr << s_bits;
888 *ptr++ = (mp_limb_t) accu;
889 accu = accu >> GMP_LIMB_BITS;
893 *ptr = (mp_limb_t) accu;
900 for (count = pow5_len; count > 0;)
903 pow5_ptr[s_limbs + count] = pow5_ptr[count];
905 for (count = s_limbs; count > 0;)
912 pow5.limbs = pow5_ptr;
913 pow5.nlimbs = pow5_len;
916 /* Multiply m with pow5. No division needed. */
917 z_memory = multiply (m, pow5, &z);
921 /* Divide m by pow5 and round. */
922 z_memory = divide (m, pow5, &z);
927 pow5.limbs = pow5_ptr;
928 pow5.nlimbs = pow5_len;
932 Multiply m with pow5, then divide by 2^|s|. */
936 tmp_memory = multiply (m, pow5, &numerator);
937 if (tmp_memory == NULL)
943 /* Construct 2^|s|. */
945 mp_limb_t *ptr = pow5_ptr + pow5_len;
947 for (i = 0; i < s_limbs; i++)
949 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
950 denominator.limbs = ptr;
951 denominator.nlimbs = s_limbs + 1;
953 z_memory = divide (numerator, denominator, &z);
959 Multiply m with 2^s, then divide by pow5. */
962 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
963 * sizeof (mp_limb_t));
971 mp_limb_t *destptr = num_ptr;
974 for (i = 0; i < s_limbs; i++)
979 const mp_limb_t *sourceptr = m.limbs;
980 mp_twolimb_t accu = 0;
982 for (count = m.nlimbs; count > 0; count--)
984 accu += (mp_twolimb_t) *sourceptr++ << s;
985 *destptr++ = (mp_limb_t) accu;
986 accu = accu >> GMP_LIMB_BITS;
989 *destptr++ = (mp_limb_t) accu;
993 const mp_limb_t *sourceptr = m.limbs;
995 for (count = m.nlimbs; count > 0; count--)
996 *destptr++ = *sourceptr++;
998 numerator.limbs = num_ptr;
999 numerator.nlimbs = destptr - num_ptr;
1001 z_memory = divide (numerator, pow5, &z);
1008 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1010 if (z_memory == NULL)
1012 digits = convert_to_decimal (z, extra_zeroes);
1017 /* Assuming x is finite and > 0:
1018 Return an approximation for n with 10^n <= x < 10^(n+1).
1019 The approximation is usually the right n, but may be off by 1 sometimes. */
1021 floorlog10l (long double x)
1028 /* Split into exponential part and mantissa. */
1029 y = frexpl (x, &exp);
1030 if (!(y >= 0.0L && y < 1.0L))
1036 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1038 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1039 exp -= GMP_LIMB_BITS;
1041 if (y < (1.0L / (1 << 16)))
1043 y *= 1.0L * (1 << 16);
1046 if (y < (1.0L / (1 << 8)))
1048 y *= 1.0L * (1 << 8);
1051 if (y < (1.0L / (1 << 4)))
1053 y *= 1.0L * (1 << 4);
1056 if (y < (1.0L / (1 << 2)))
1058 y *= 1.0L * (1 << 2);
1061 if (y < (1.0L / (1 << 1)))
1063 y *= 1.0L * (1 << 1);
1067 if (!(y >= 0.5L && y < 1.0L))
1069 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1072 if (z < 0.70710678118654752444)
1074 z *= 1.4142135623730950488;
1077 if (z < 0.8408964152537145431)
1079 z *= 1.1892071150027210667;
1082 if (z < 0.91700404320467123175)
1084 z *= 1.0905077326652576592;
1087 if (z < 0.9576032806985736469)
1089 z *= 1.0442737824274138403;
1092 /* Now 0.95 <= z <= 1.01. */
1094 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1095 Four terms are enough to get an approximation with error < 10^-7. */
1096 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1097 /* Finally multiply with log(2)/log(10), yields an approximation for
1099 l *= 0.30102999566398119523;
1100 /* Round down to the next integer. */
1101 return (int) l + (l < 0 ? -1 : 0);
1107 VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list args)
1112 if (PRINTF_PARSE (format, &d, &a) < 0)
1123 if (printf_fetchargs (args, &a) < 0)
1131 size_t buf_neededlength;
1133 CHAR_T *buf_malloced;
1137 /* Output string accumulator. */
1142 /* Allocate a small buffer that will hold a directive passed to
1143 sprintf or snprintf. */
1145 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1147 if (buf_neededlength < 4000 / sizeof (CHAR_T))
1149 buf = (CHAR_T *) alloca (buf_neededlength * sizeof (CHAR_T));
1150 buf_malloced = NULL;
1155 size_t buf_memsize = xtimes (buf_neededlength, sizeof (CHAR_T));
1156 if (size_overflow_p (buf_memsize))
1157 goto out_of_memory_1;
1158 buf = (CHAR_T *) malloc (buf_memsize);
1160 goto out_of_memory_1;
1164 if (resultbuf != NULL)
1167 allocated = *lengthp;
1176 result is either == resultbuf or == NULL or malloc-allocated.
1177 If length > 0, then result != NULL. */
1179 /* Ensures that allocated >= needed. Aborts through a jump to
1180 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1181 #define ENSURE_ALLOCATION(needed) \
1182 if ((needed) > allocated) \
1184 size_t memory_size; \
1187 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1188 if ((needed) > allocated) \
1189 allocated = (needed); \
1190 memory_size = xtimes (allocated, sizeof (CHAR_T)); \
1191 if (size_overflow_p (memory_size)) \
1192 goto out_of_memory; \
1193 if (result == resultbuf || result == NULL) \
1194 memory = (CHAR_T *) malloc (memory_size); \
1196 memory = (CHAR_T *) realloc (result, memory_size); \
1197 if (memory == NULL) \
1198 goto out_of_memory; \
1199 if (result == resultbuf && length > 0) \
1200 memcpy (memory, result, length * sizeof (CHAR_T)); \
1204 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1206 if (cp != dp->dir_start)
1208 size_t n = dp->dir_start - cp;
1209 size_t augmented_length = xsum (length, n);
1211 ENSURE_ALLOCATION (augmented_length);
1212 memcpy (result + length, cp, n * sizeof (CHAR_T));
1213 length = augmented_length;
1218 /* Execute a single directive. */
1219 if (dp->conversion == '%')
1221 size_t augmented_length;
1223 if (!(dp->arg_index == ARG_NONE))
1225 augmented_length = xsum (length, 1);
1226 ENSURE_ALLOCATION (augmented_length);
1227 result[length] = '%';
1228 length = augmented_length;
1232 if (!(dp->arg_index != ARG_NONE))
1235 if (dp->conversion == 'n')
1237 switch (a.arg[dp->arg_index].type)
1239 case TYPE_COUNT_SCHAR_POINTER:
1240 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1242 case TYPE_COUNT_SHORT_POINTER:
1243 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1245 case TYPE_COUNT_INT_POINTER:
1246 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1248 case TYPE_COUNT_LONGINT_POINTER:
1249 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1251 #if HAVE_LONG_LONG_INT
1252 case TYPE_COUNT_LONGLONGINT_POINTER:
1253 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1260 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
1261 else if ((dp->conversion == 'f' || dp->conversion == 'F'
1262 || dp->conversion == 'e' || dp->conversion == 'E'
1263 || dp->conversion == 'g' || dp->conversion == 'G')
1264 && a.arg[dp->arg_index].type == TYPE_LONGDOUBLE)
1266 int flags = dp->flags;
1280 if (dp->width_start != dp->width_end)
1282 if (dp->width_arg_index != ARG_NONE)
1286 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1288 arg = a.arg[dp->width_arg_index].a.a_int;
1291 /* "A negative field width is taken as a '-' flag
1292 followed by a positive field width." */
1294 width = (unsigned int) (-arg);
1301 const CHAR_T *digitp = dp->width_start;
1304 width = xsum (xtimes (width, 10), *digitp++ - '0');
1305 while (digitp != dp->width_end);
1312 if (dp->precision_start != dp->precision_end)
1314 if (dp->precision_arg_index != ARG_NONE)
1318 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1320 arg = a.arg[dp->precision_arg_index].a.a_int;
1321 /* "A negative precision is taken as if the precision
1331 const CHAR_T *digitp = dp->precision_start + 1;
1334 while (digitp != dp->precision_end)
1335 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1340 arg = a.arg[dp->arg_index].a.a_longdouble;
1342 /* Allocate a temporary buffer of sufficient size. */
1343 tmp_length = LDBL_DIG + 1;
1344 if (tmp_length < precision)
1345 tmp_length = precision;
1346 if (dp->conversion == 'f' || dp->conversion == 'F')
1347 if (!(isnanl (arg) || arg + arg == arg))
1349 int exponent = floorlog10l (arg < 0 ? -arg : arg);
1350 if (exponent >= 0 && tmp_length < exponent + precision)
1351 tmp_length = exponent + precision;
1353 /* Account for sign, decimal point etc. */
1354 tmp_length = xsum (tmp_length, 12);
1356 if (tmp_length < width)
1359 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1361 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1365 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1367 if (size_overflow_p (tmp_memsize))
1368 /* Overflow, would lead to out of memory. */
1370 tmp = (CHAR_T *) malloc (tmp_memsize);
1372 /* Out of memory. */
1381 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1383 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1387 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1393 DECL_LONG_DOUBLE_ROUNDING
1395 BEGIN_LONG_DOUBLE_ROUNDING ();
1397 if (signbit (arg)) /* arg < 0.0L or negative zero */
1405 else if (flags & FLAG_SHOWSIGN)
1407 else if (flags & FLAG_SPACE)
1410 if (arg > 0.0L && arg + arg == arg)
1412 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1414 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1418 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1425 if (dp->conversion == 'f' || dp->conversion == 'F')
1434 scale10_round_decimal_long_double (arg, precision);
1437 END_LONG_DOUBLE_ROUNDING ();
1440 ndigits = strlen (digits);
1442 if (ndigits > precision)
1446 *p++ = digits[ndigits];
1448 while (ndigits > precision);
1451 /* Here ndigits <= precision. */
1452 if ((flags & FLAG_ALT) || precision > 0)
1454 *p++ = decimal_point_char ();
1455 for (; precision > ndigits; precision--)
1460 *p++ = digits[ndigits];
1466 else if (dp->conversion == 'e' || dp->conversion == 'E')
1477 if ((flags & FLAG_ALT) || precision > 0)
1479 *p++ = decimal_point_char ();
1480 for (; precision > 0; precision--)
1491 exponent = floorlog10l (arg);
1496 scale10_round_decimal_long_double (arg,
1497 (int)precision - exponent);
1500 END_LONG_DOUBLE_ROUNDING ();
1503 ndigits = strlen (digits);
1505 if (ndigits == precision + 1)
1507 if (ndigits < precision
1508 || ndigits > precision + 2)
1509 /* The exponent was not guessed precisely
1513 /* None of two values of exponent is the
1514 right one. Prevent an endless loop. */
1517 if (ndigits == precision)
1524 /* Here ndigits = precision+1. */
1525 *p++ = digits[--ndigits];
1526 if ((flags & FLAG_ALT) || precision > 0)
1528 *p++ = decimal_point_char ();
1532 *p++ = digits[ndigits];
1539 *p++ = dp->conversion; /* 'e' or 'E' */
1540 # if WIDE_CHAR_VERSION
1542 static const wchar_t decimal_format[] =
1543 { '%', '+', '.', '2', 'd', '\0' };
1544 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1547 sprintf (p, "%+.2d", exponent);
1552 else if (dp->conversion == 'g' || dp->conversion == 'G')
1554 /* This is not specified by POSIX, but
1555 implementations appear to do this. */
1561 /* precision >= 1. */
1564 /* The exponent is 0, >= -4, < precision.
1565 Use fixed-point notation. */
1567 size_t ndigits = precision;
1568 /* Number of trailing zeroes that have to be
1571 (flags & FLAG_ALT ? 0 : precision - 1);
1575 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1577 *p++ = decimal_point_char ();
1578 while (ndigits > nzeroes)
1594 exponent = floorlog10l (arg);
1599 scale10_round_decimal_long_double (arg,
1600 (int)(precision - 1) - exponent);
1603 END_LONG_DOUBLE_ROUNDING ();
1606 ndigits = strlen (digits);
1608 if (ndigits == precision)
1610 if (ndigits < precision - 1
1611 || ndigits > precision + 1)
1612 /* The exponent was not guessed precisely
1616 /* None of two values of exponent is the
1617 right one. Prevent an endless loop. */
1620 if (ndigits < precision)
1626 /* Here ndigits = precision. */
1628 /* Determine the number of trailing zeroes that
1629 have to be dropped. */
1631 if ((flags & FLAG_ALT) == 0)
1632 while (nzeroes < ndigits
1633 && digits[nzeroes] == '0')
1636 /* The exponent is now determined. */
1637 if (exponent >= -4 && exponent < (long)precision)
1639 /* Fixed-point notation: max(exponent,0)+1
1640 digits, then the decimal point, then the
1641 remaining digits without trailing zeroes. */
1644 size_t count = exponent + 1;
1645 /* Note: count <= precision = ndigits. */
1646 for (; count > 0; count--)
1647 *p++ = digits[--ndigits];
1648 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1650 *p++ = decimal_point_char ();
1651 while (ndigits > nzeroes)
1654 *p++ = digits[ndigits];
1660 size_t count = -exponent - 1;
1662 *p++ = decimal_point_char ();
1663 for (; count > 0; count--)
1665 while (ndigits > nzeroes)
1668 *p++ = digits[ndigits];
1674 /* Exponential notation. */
1675 *p++ = digits[--ndigits];
1676 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1678 *p++ = decimal_point_char ();
1679 while (ndigits > nzeroes)
1682 *p++ = digits[ndigits];
1685 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
1686 # if WIDE_CHAR_VERSION
1688 static const wchar_t decimal_format[] =
1689 { '%', '+', '.', '2', 'd', '\0' };
1690 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1693 sprintf (p, "%+.2d", exponent);
1706 END_LONG_DOUBLE_ROUNDING ();
1709 /* The generated string now extends from tmp to p, with the
1710 zero padding insertion point being at pad_ptr. */
1711 if (has_width && p - tmp < width)
1713 size_t pad = width - (p - tmp);
1714 CHAR_T *end = p + pad;
1716 if (flags & FLAG_LEFT)
1718 /* Pad with spaces on the right. */
1719 for (; pad > 0; pad--)
1722 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
1724 /* Pad with zeroes. */
1729 for (; pad > 0; pad--)
1734 /* Pad with spaces on the left. */
1739 for (; pad > 0; pad--)
1747 size_t count = p - tmp;
1749 if (count >= tmp_length)
1750 /* tmp_length was incorrectly calculated - fix the
1754 /* Make room for the result. */
1755 if (count >= allocated - length)
1757 size_t n = xsum (length, count);
1759 ENSURE_ALLOCATION (n);
1762 /* Append the result. */
1763 memcpy (result + length, tmp, count * sizeof (CHAR_T));
1770 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
1771 else if (dp->conversion == 'a' || dp->conversion == 'A')
1773 arg_type type = a.arg[dp->arg_index].type;
1774 int flags = dp->flags;
1787 if (dp->width_start != dp->width_end)
1789 if (dp->width_arg_index != ARG_NONE)
1793 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1795 arg = a.arg[dp->width_arg_index].a.a_int;
1798 /* "A negative field width is taken as a '-' flag
1799 followed by a positive field width." */
1801 width = (unsigned int) (-arg);
1808 const CHAR_T *digitp = dp->width_start;
1811 width = xsum (xtimes (width, 10), *digitp++ - '0');
1812 while (digitp != dp->width_end);
1819 if (dp->precision_start != dp->precision_end)
1821 if (dp->precision_arg_index != ARG_NONE)
1825 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1827 arg = a.arg[dp->precision_arg_index].a.a_int;
1828 /* "A negative precision is taken as if the precision
1838 const CHAR_T *digitp = dp->precision_start + 1;
1841 while (digitp != dp->precision_end)
1842 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1847 /* Allocate a temporary buffer of sufficient size. */
1848 if (type == TYPE_LONGDOUBLE)
1850 (unsigned int) ((LDBL_DIG + 1)
1851 * 0.831 /* decimal -> hexadecimal */
1853 + 1; /* turn floor into ceil */
1856 (unsigned int) ((DBL_DIG + 1)
1857 * 0.831 /* decimal -> hexadecimal */
1859 + 1; /* turn floor into ceil */
1860 if (tmp_length < precision)
1861 tmp_length = precision;
1862 /* Account for sign, decimal point etc. */
1863 tmp_length = xsum (tmp_length, 12);
1865 if (tmp_length < width)
1868 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1870 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1874 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1876 if (size_overflow_p (tmp_memsize))
1877 /* Overflow, would lead to out of memory. */
1879 tmp = (CHAR_T *) malloc (tmp_memsize);
1881 /* Out of memory. */
1887 if (type == TYPE_LONGDOUBLE)
1889 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1893 if (dp->conversion == 'A')
1895 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1899 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1905 DECL_LONG_DOUBLE_ROUNDING
1907 BEGIN_LONG_DOUBLE_ROUNDING ();
1909 if (signbit (arg)) /* arg < 0.0L or negative zero */
1917 else if (flags & FLAG_SHOWSIGN)
1919 else if (flags & FLAG_SPACE)
1922 if (arg > 0.0L && arg + arg == arg)
1924 if (dp->conversion == 'A')
1926 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1930 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1936 long double mantissa;
1939 mantissa = printf_frexpl (arg, &exponent);
1947 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
1949 /* Round the mantissa. */
1950 long double tail = mantissa;
1953 for (q = precision; ; q--)
1955 int digit = (int) tail;
1959 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
1968 for (q = precision; q > 0; q--)
1974 *p++ = dp->conversion - 'A' + 'X';
1979 digit = (int) mantissa;
1982 if ((flags & FLAG_ALT)
1983 || mantissa > 0.0L || precision > 0)
1985 *p++ = decimal_point_char ();
1986 /* This loop terminates because we assume
1987 that FLT_RADIX is a power of 2. */
1988 while (mantissa > 0.0L)
1991 digit = (int) mantissa;
1996 : dp->conversion - 10);
2000 while (precision > 0)
2007 *p++ = dp->conversion - 'A' + 'P';
2008 # if WIDE_CHAR_VERSION
2010 static const wchar_t decimal_format[] =
2011 { '%', '+', 'd', '\0' };
2012 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2015 sprintf (p, "%+d", exponent);
2021 END_LONG_DOUBLE_ROUNDING ();
2026 double arg = a.arg[dp->arg_index].a.a_double;
2030 if (dp->conversion == 'A')
2032 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2036 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2043 if (signbit (arg)) /* arg < 0.0 or negative zero */
2051 else if (flags & FLAG_SHOWSIGN)
2053 else if (flags & FLAG_SPACE)
2056 if (arg > 0.0 && arg + arg == arg)
2058 if (dp->conversion == 'A')
2060 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2064 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2073 mantissa = printf_frexp (arg, &exponent);
2081 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2083 /* Round the mantissa. */
2084 double tail = mantissa;
2087 for (q = precision; ; q--)
2089 int digit = (int) tail;
2093 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2102 for (q = precision; q > 0; q--)
2108 *p++ = dp->conversion - 'A' + 'X';
2113 digit = (int) mantissa;
2116 if ((flags & FLAG_ALT)
2117 || mantissa > 0.0 || precision > 0)
2119 *p++ = decimal_point_char ();
2120 /* This loop terminates because we assume
2121 that FLT_RADIX is a power of 2. */
2122 while (mantissa > 0.0)
2125 digit = (int) mantissa;
2130 : dp->conversion - 10);
2134 while (precision > 0)
2141 *p++ = dp->conversion - 'A' + 'P';
2142 # if WIDE_CHAR_VERSION
2144 static const wchar_t decimal_format[] =
2145 { '%', '+', 'd', '\0' };
2146 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2149 sprintf (p, "%+d", exponent);
2156 /* The generated string now extends from tmp to p, with the
2157 zero padding insertion point being at pad_ptr. */
2158 if (has_width && p - tmp < width)
2160 size_t pad = width - (p - tmp);
2161 CHAR_T *end = p + pad;
2163 if (flags & FLAG_LEFT)
2165 /* Pad with spaces on the right. */
2166 for (; pad > 0; pad--)
2169 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2171 /* Pad with zeroes. */
2176 for (; pad > 0; pad--)
2181 /* Pad with spaces on the left. */
2186 for (; pad > 0; pad--)
2194 size_t count = p - tmp;
2196 if (count >= tmp_length)
2197 /* tmp_length was incorrectly calculated - fix the
2201 /* Make room for the result. */
2202 if (count >= allocated - length)
2204 size_t n = xsum (length, count);
2206 ENSURE_ALLOCATION (n);
2209 /* Append the result. */
2210 memcpy (result + length, tmp, count * sizeof (CHAR_T));
2219 arg_type type = a.arg[dp->arg_index].type;
2220 int flags = dp->flags;
2221 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2225 #if NEED_PRINTF_FLAG_ZERO
2228 # define pad_ourselves 0
2231 unsigned int prefix_count;
2239 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2242 if (dp->width_start != dp->width_end)
2244 if (dp->width_arg_index != ARG_NONE)
2248 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2250 arg = a.arg[dp->width_arg_index].a.a_int;
2253 /* "A negative field width is taken as a '-' flag
2254 followed by a positive field width." */
2256 width = (unsigned int) (-arg);
2263 const CHAR_T *digitp = dp->width_start;
2266 width = xsum (xtimes (width, 10), *digitp++ - '0');
2267 while (digitp != dp->width_end);
2274 /* Allocate a temporary buffer of sufficient size for calling
2280 if (dp->precision_start != dp->precision_end)
2282 if (dp->precision_arg_index != ARG_NONE)
2286 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2288 arg = a.arg[dp->precision_arg_index].a.a_int;
2289 precision = (arg < 0 ? 0 : arg);
2293 const CHAR_T *digitp = dp->precision_start + 1;
2296 while (digitp != dp->precision_end)
2297 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2301 switch (dp->conversion)
2304 case 'd': case 'i': case 'u':
2305 # if HAVE_LONG_LONG_INT
2306 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2308 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2309 * 0.30103 /* binary -> decimal */
2311 + 1; /* turn floor into ceil */
2314 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2316 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2317 * 0.30103 /* binary -> decimal */
2319 + 1; /* turn floor into ceil */
2322 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2323 * 0.30103 /* binary -> decimal */
2325 + 1; /* turn floor into ceil */
2326 if (tmp_length < precision)
2327 tmp_length = precision;
2328 /* Multiply by 2, as an estimate for FLAG_GROUP. */
2329 tmp_length = xsum (tmp_length, tmp_length);
2330 /* Add 1, to account for a leading sign. */
2331 tmp_length = xsum (tmp_length, 1);
2335 # if HAVE_LONG_LONG_INT
2336 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2338 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2339 * 0.333334 /* binary -> octal */
2341 + 1; /* turn floor into ceil */
2344 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2346 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2347 * 0.333334 /* binary -> octal */
2349 + 1; /* turn floor into ceil */
2352 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2353 * 0.333334 /* binary -> octal */
2355 + 1; /* turn floor into ceil */
2356 if (tmp_length < precision)
2357 tmp_length = precision;
2358 /* Add 1, to account for a leading sign. */
2359 tmp_length = xsum (tmp_length, 1);
2363 # if HAVE_LONG_LONG_INT
2364 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2366 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2367 * 0.25 /* binary -> hexadecimal */
2369 + 1; /* turn floor into ceil */
2372 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2374 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2375 * 0.25 /* binary -> hexadecimal */
2377 + 1; /* turn floor into ceil */
2380 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2381 * 0.25 /* binary -> hexadecimal */
2383 + 1; /* turn floor into ceil */
2384 if (tmp_length < precision)
2385 tmp_length = precision;
2386 /* Add 2, to account for a leading sign or alternate form. */
2387 tmp_length = xsum (tmp_length, 2);
2391 if (type == TYPE_LONGDOUBLE)
2393 (unsigned int) (LDBL_MAX_EXP
2394 * 0.30103 /* binary -> decimal */
2395 * 2 /* estimate for FLAG_GROUP */
2397 + 1 /* turn floor into ceil */
2398 + 10; /* sign, decimal point etc. */
2401 (unsigned int) (DBL_MAX_EXP
2402 * 0.30103 /* binary -> decimal */
2403 * 2 /* estimate for FLAG_GROUP */
2405 + 1 /* turn floor into ceil */
2406 + 10; /* sign, decimal point etc. */
2407 tmp_length = xsum (tmp_length, precision);
2410 case 'e': case 'E': case 'g': case 'G':
2412 12; /* sign, decimal point, exponent etc. */
2413 tmp_length = xsum (tmp_length, precision);
2417 if (type == TYPE_LONGDOUBLE)
2419 (unsigned int) (LDBL_DIG
2420 * 0.831 /* decimal -> hexadecimal */
2422 + 1; /* turn floor into ceil */
2425 (unsigned int) (DBL_DIG
2426 * 0.831 /* decimal -> hexadecimal */
2428 + 1; /* turn floor into ceil */
2429 if (tmp_length < precision)
2430 tmp_length = precision;
2431 /* Account for sign, decimal point etc. */
2432 tmp_length = xsum (tmp_length, 12);
2436 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
2437 if (type == TYPE_WIDE_CHAR)
2438 tmp_length = MB_CUR_MAX;
2446 if (type == TYPE_WIDE_STRING)
2449 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
2451 # if !WIDE_CHAR_VERSION
2452 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
2457 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
2462 (unsigned int) (sizeof (void *) * CHAR_BIT
2463 * 0.25 /* binary -> hexadecimal */
2465 + 1 /* turn floor into ceil */
2466 + 2; /* account for leading 0x */
2473 if (tmp_length < width)
2476 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2479 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2483 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2485 if (size_overflow_p (tmp_memsize))
2486 /* Overflow, would lead to out of memory. */
2488 tmp = (CHAR_T *) malloc (tmp_memsize);
2490 /* Out of memory. */
2495 /* Decide whether to perform the padding ourselves. */
2496 #if NEED_PRINTF_FLAG_ZERO
2497 switch (dp->conversion)
2499 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
2509 /* Construct the format string for calling snprintf or
2513 #if NEED_PRINTF_FLAG_GROUPING
2514 /* The underlying implementation doesn't support the ' flag.
2515 Produce no grouping characters in this case; this is
2516 acceptable because the grouping is locale dependent. */
2518 if (flags & FLAG_GROUP)
2521 if (flags & FLAG_LEFT)
2523 if (flags & FLAG_SHOWSIGN)
2525 if (flags & FLAG_SPACE)
2527 if (flags & FLAG_ALT)
2531 if (flags & FLAG_ZERO)
2533 if (dp->width_start != dp->width_end)
2535 size_t n = dp->width_end - dp->width_start;
2536 memcpy (fbp, dp->width_start, n * sizeof (CHAR_T));
2540 if (dp->precision_start != dp->precision_end)
2542 size_t n = dp->precision_end - dp->precision_start;
2543 memcpy (fbp, dp->precision_start, n * sizeof (CHAR_T));
2549 #if HAVE_LONG_LONG_INT
2550 case TYPE_LONGLONGINT:
2551 case TYPE_ULONGLONGINT:
2552 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2565 case TYPE_WIDE_CHAR:
2568 case TYPE_WIDE_STRING:
2572 case TYPE_LONGDOUBLE:
2578 #if NEED_PRINTF_DIRECTIVE_F
2579 if (dp->conversion == 'F')
2583 *fbp = dp->conversion;
2592 /* Construct the arguments for calling snprintf or sprintf. */
2594 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
2596 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2598 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
2600 if (dp->precision_arg_index != ARG_NONE)
2602 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2604 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
2608 /* Prepare checking whether snprintf returns the count
2610 ENSURE_ALLOCATION (xsum (length, 1));
2611 result[length] = '\0';
2620 maxlen = allocated - length;
2625 /* SNPRINTF can fail if maxlen > INT_MAX. */
2626 if (maxlen > INT_MAX)
2628 # define SNPRINTF_BUF(arg) \
2629 switch (prefix_count) \
2632 retcount = SNPRINTF (result + length, maxlen, buf, \
2636 retcount = SNPRINTF (result + length, maxlen, buf, \
2637 prefixes[0], arg, &count); \
2640 retcount = SNPRINTF (result + length, maxlen, buf, \
2641 prefixes[0], prefixes[1], arg, \
2648 # define SNPRINTF_BUF(arg) \
2649 switch (prefix_count) \
2652 count = sprintf (tmp, buf, arg); \
2655 count = sprintf (tmp, buf, prefixes[0], arg); \
2658 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
2670 int arg = a.arg[dp->arg_index].a.a_schar;
2676 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
2682 int arg = a.arg[dp->arg_index].a.a_short;
2688 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
2694 int arg = a.arg[dp->arg_index].a.a_int;
2700 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
2706 long int arg = a.arg[dp->arg_index].a.a_longint;
2712 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
2716 #if HAVE_LONG_LONG_INT
2717 case TYPE_LONGLONGINT:
2719 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
2723 case TYPE_ULONGLONGINT:
2725 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
2732 double arg = a.arg[dp->arg_index].a.a_double;
2736 case TYPE_LONGDOUBLE:
2738 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2744 int arg = a.arg[dp->arg_index].a.a_char;
2749 case TYPE_WIDE_CHAR:
2751 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
2758 const char *arg = a.arg[dp->arg_index].a.a_string;
2763 case TYPE_WIDE_STRING:
2765 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2772 void *arg = a.arg[dp->arg_index].a.a_pointer;
2781 /* Portability: Not all implementations of snprintf()
2782 are ISO C 99 compliant. Determine the number of
2783 bytes that snprintf() has produced or would have
2787 /* Verify that snprintf() has NUL-terminated its
2789 if (count < maxlen && result[length + count] != '\0')
2791 /* Portability hack. */
2792 if (retcount > count)
2797 /* snprintf() doesn't understand the '%n'
2801 /* Don't use the '%n' directive; instead, look
2802 at the snprintf() return value. */
2808 /* Look at the snprintf() return value. */
2811 /* HP-UX 10.20 snprintf() is doubly deficient:
2812 It doesn't understand the '%n' directive,
2813 *and* it returns -1 (rather than the length
2814 that would have been required) when the
2815 buffer is too small. */
2816 size_t bigger_need =
2817 xsum (xtimes (allocated, 2), 12);
2818 ENSURE_ALLOCATION (bigger_need);
2827 /* Attempt to handle failure. */
2830 if (!(result == resultbuf || result == NULL))
2832 if (buf_malloced != NULL)
2833 free (buf_malloced);
2839 /* Make room for the result. */
2840 if (count >= maxlen)
2842 /* Need at least count bytes. But allocate
2843 proportionally, to avoid looping eternally if
2844 snprintf() reports a too small count. */
2846 xmax (xsum (length, count), xtimes (allocated, 2));
2848 ENSURE_ALLOCATION (n);
2852 maxlen = allocated - length;
2856 /* Perform padding. */
2857 #if NEED_PRINTF_FLAG_ZERO
2858 if (pad_ourselves && has_width && count < width)
2861 /* Make room for the result. */
2862 if (width >= maxlen)
2864 /* Need at least width bytes. But allocate
2865 proportionally, to avoid looping eternally if
2866 snprintf() reports a too small count. */
2868 xmax (xsum (length + 1, width),
2869 xtimes (allocated, 2));
2872 ENSURE_ALLOCATION (n);
2874 maxlen = allocated - length; /* > width */
2876 /* Here width < maxlen. */
2880 CHAR_T * const rp = result + length;
2882 CHAR_T * const rp = tmp;
2884 CHAR_T *p = rp + count;
2885 size_t pad = width - count;
2886 CHAR_T *end = p + pad;
2887 CHAR_T *pad_ptr = (*rp == '-' ? rp + 1 : rp);
2888 /* No zero-padding of "inf" and "nan". */
2889 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
2890 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
2892 /* The generated string now extends from rp to p,
2893 with the zero padding insertion point being at
2896 if (flags & FLAG_LEFT)
2898 /* Pad with spaces on the right. */
2899 for (; pad > 0; pad--)
2902 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2904 /* Pad with zeroes. */
2909 for (; pad > 0; pad--)
2914 /* Pad with spaces on the left. */
2919 for (; pad > 0; pad--)
2923 count = width; /* = count + pad = end - rp */
2929 if (count >= tmp_length)
2930 /* tmp_length was incorrectly calculated - fix the
2935 /* Here still count < maxlen. */
2938 /* The snprintf() result did fit. */
2940 /* Append the sprintf() result. */
2941 memcpy (result + length, tmp, count * sizeof (CHAR_T));
2946 #if NEED_PRINTF_DIRECTIVE_F
2947 if (dp->conversion == 'F')
2949 /* Convert the %f result to upper case for %F. */
2950 CHAR_T *rp = result + length;
2952 for (rc = count; rc > 0; rc--, rp++)
2953 if (*rp >= 'a' && *rp <= 'z')
2954 *rp = *rp - 'a' + 'A';
2965 /* Add the final NUL. */
2966 ENSURE_ALLOCATION (xsum (length, 1));
2967 result[length] = '\0';
2969 if (result != resultbuf && length + 1 < allocated)
2971 /* Shrink the allocated memory if possible. */
2974 memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
2979 if (buf_malloced != NULL)
2980 free (buf_malloced);
2983 /* Note that we can produce a big string of a length > INT_MAX. POSIX
2984 says that snprintf() fails with errno = EOVERFLOW in this case, but
2985 that's only because snprintf() returns an 'int'. This function does
2986 not have this limitation. */
2990 if (!(result == resultbuf || result == NULL))
2992 if (buf_malloced != NULL)
2993 free (buf_malloced);
2999 if (!(result == resultbuf || result == NULL))
3001 if (buf_malloced != NULL)
3002 free (buf_malloced);