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. */
626 for (i = b_len; i > 0; )
631 (i + 1 < r_len ? r_ptr[i + 1] >> (GMP_LIMB_BITS - 1) : 0)
632 | (i < r_len ? r_ptr[i] << 1 : 0);
633 mp_limb_t b_i = b_ptr[i];
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 to decimal representation.
660 Destroys the contents of a.
661 Return the allocated memory - containing the decimal digits in low-to-high
662 order, terminated with a NUL character - in case of success, NULL in case
663 of memory allocation failure. */
665 convert_to_decimal (mpn_t a)
667 mp_limb_t *a_ptr = a.limbs;
668 size_t a_len = a.nlimbs;
669 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
670 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
671 char *c_ptr = (char *) malloc (c_len);
677 /* Divide a by 10^9, in-place. */
678 mp_limb_t remainder = 0;
679 mp_limb_t *ptr = a_ptr + a_len;
681 for (count = a_len; count > 0; count--)
684 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
685 *ptr = num / 1000000000;
686 remainder = num % 1000000000;
688 /* Store the remainder as 9 decimal digits. */
689 for (count = 9; count > 0; count--)
691 *d_ptr++ = '0' + (remainder % 10);
692 remainder = remainder / 10;
695 if (a_ptr[a_len - 1] == 0)
698 /* Remove leading zeroes. */
699 while (d_ptr > c_ptr && d_ptr[-1] == '0')
701 /* But keep at least one zero. */
704 /* Terminate the string. */
710 /* Assuming x is finite and >= 0:
711 write x as x = 2^e * m, where m is a bignum.
712 Return the allocated memory in case of success, NULL in case of memory
713 allocation failure. */
715 decode_long_double (long double x, int *ep, mpn_t *mp)
722 /* Allocate memory for result. */
723 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
724 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
727 /* Split into exponential part and mantissa. */
728 y = frexpl (x, &exp);
729 if (!(y >= 0.0L && y < 1.0L))
731 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
732 latter is an integer. */
733 /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
734 I'm not sure whether it's safe to cast a 'long double' value between
735 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
736 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
738 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
739 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
742 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
745 if (!(y >= 0.0L && y < 1.0L))
747 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
750 if (!(y >= 0.0L && y < 1.0L))
752 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
757 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
760 if (!(y >= 0.0L && y < 1.0L))
762 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
766 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
769 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
772 if (!(y >= 0.0L && y < 1.0L))
774 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
777 if (!(y >= 0.0L && y < 1.0L))
779 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
784 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
787 *ep = exp - LDBL_MANT_BIT;
791 /* Assuming x is finite and >= 0, and n is an integer:
792 Compute y = round (x * 10^n) as a bignum >= 0.
793 Return the allocated memory in case of success, NULL in case of memory
794 allocation failure. */
796 scale10_round_long_double (long double x, int n, mpn_t *yp)
800 void *memory = decode_long_double (x, &e, &m);
806 unsigned int s_limbs;
812 /* x = 2^e * m, hence
813 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
814 = round (2^s * 5^n * m). */
816 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
817 sign. 2.322 is slightly larger than log(5)/log(2). */
818 abs_n = (n >= 0 ? n : -n);
819 abs_s = (s >= 0 ? s : -s);
820 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
821 + abs_s / GMP_LIMB_BITS + 1)
822 * sizeof (mp_limb_t));
823 if (pow5_ptr == NULL)
828 /* Initialize with 1. */
831 /* Multiply with 5^|n|. */
834 static mp_limb_t const small_pow5[13 + 1] =
836 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
837 48828125, 244140625, 1220703125
840 for (n13 = 0; n13 <= abs_n; n13 += 13)
842 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
844 mp_twolimb_t carry = 0;
845 for (j = 0; j < pow5_len; j++)
847 mp_limb_t digit2 = pow5_ptr[j];
848 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
849 pow5_ptr[j] = (mp_limb_t) carry;
850 carry = carry >> GMP_LIMB_BITS;
853 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
856 s_limbs = abs_s / GMP_LIMB_BITS;
857 s_bits = abs_s % GMP_LIMB_BITS;
858 if (n >= 0 ? s >= 0 : s <= 0)
860 /* Multiply with 2^|s|. */
863 mp_limb_t *ptr = pow5_ptr;
864 mp_twolimb_t accu = 0;
866 for (count = pow5_len; count > 0; count--)
868 accu += (mp_twolimb_t) *ptr << s_bits;
869 *ptr++ = (mp_limb_t) accu;
870 accu = accu >> GMP_LIMB_BITS;
874 *ptr = (mp_limb_t) accu;
881 for (count = pow5_len; count > 0;)
884 pow5_ptr[s_limbs + count] = pow5_ptr[count];
886 for (count = s_limbs; count > 0;)
893 pow5.limbs = pow5_ptr;
894 pow5.nlimbs = pow5_len;
897 /* Multiply m with pow5. No division needed. */
898 void *result_memory = multiply (m, pow5, yp);
901 return result_memory;
905 /* Divide m by pow5 and round. */
906 void *result_memory = divide (m, pow5, yp);
909 return result_memory;
914 pow5.limbs = pow5_ptr;
915 pow5.nlimbs = pow5_len;
919 Multiply m with pow5, then divide by 2^|s|. */
924 tmp_memory = multiply (m, pow5, &numerator);
925 if (tmp_memory == NULL)
931 /* Construct 2^|s|. */
933 mp_limb_t *ptr = pow5_ptr + pow5_len;
935 for (i = 0; i < s_limbs; i++)
937 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
938 denominator.limbs = ptr;
939 denominator.nlimbs = s_limbs + 1;
941 result_memory = divide (numerator, denominator, yp);
945 return result_memory;
950 Multiply m with 2^s, then divide by pow5. */
954 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
955 * sizeof (mp_limb_t));
963 mp_limb_t *destptr = num_ptr;
966 for (i = 0; i < s_limbs; i++)
971 const mp_limb_t *sourceptr = m.limbs;
972 mp_twolimb_t accu = 0;
974 for (count = m.nlimbs; count > 0; count--)
976 accu += (mp_twolimb_t) *sourceptr++ << s;
977 *destptr++ = (mp_limb_t) accu;
978 accu = accu >> GMP_LIMB_BITS;
981 *destptr++ = (mp_limb_t) accu;
985 const mp_limb_t *sourceptr = m.limbs;
987 for (count = m.nlimbs; count > 0; count--)
988 *destptr++ = *sourceptr++;
990 numerator.limbs = num_ptr;
991 numerator.nlimbs = destptr - num_ptr;
993 result_memory = divide (numerator, pow5, yp);
997 return result_memory;
1002 /* Assuming x is finite and >= 0, and n is an integer:
1003 Returns the decimal representation of round (x * 10^n).
1004 Return the allocated memory - containing the decimal digits in low-to-high
1005 order, terminated with a NUL character - in case of success, NULL in case
1006 of memory allocation failure. */
1008 scale10_round_decimal_long_double (long double x, int n)
1014 memory = scale10_round_long_double (x, n, &y);
1017 digits = convert_to_decimal (y);
1022 /* Assuming x is finite and > 0:
1023 Return an approximation for n with 10^n <= x < 10^(n+1).
1024 The approximation is usually the right n, but may be off by 1 sometimes. */
1026 floorlog10l (long double x)
1033 /* Split into exponential part and mantissa. */
1034 y = frexpl (x, &exp);
1035 if (!(y >= 0.0L && y < 1.0L))
1041 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1043 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1044 exp -= GMP_LIMB_BITS;
1046 if (y < (1.0L / (1 << 16)))
1048 y *= 1.0L * (1 << 16);
1051 if (y < (1.0L / (1 << 8)))
1053 y *= 1.0L * (1 << 8);
1056 if (y < (1.0L / (1 << 4)))
1058 y *= 1.0L * (1 << 4);
1061 if (y < (1.0L / (1 << 2)))
1063 y *= 1.0L * (1 << 2);
1066 if (y < (1.0L / (1 << 1)))
1068 y *= 1.0L * (1 << 1);
1072 if (!(y >= 0.5L && y < 1.0L))
1074 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1077 if (z < 0.70710678118654752444)
1079 z *= 1.4142135623730950488;
1082 if (z < 0.8408964152537145431)
1084 z *= 1.1892071150027210667;
1087 if (z < 0.91700404320467123175)
1089 z *= 1.0905077326652576592;
1092 if (z < 0.9576032806985736469)
1094 z *= 1.0442737824274138403;
1097 /* Now 0.95 <= z <= 1.01. */
1099 /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1100 Four terms are enough to get an approximation with error < 10^-7. */
1101 l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1102 /* Finally multiply with log(2)/log(10), yields an approximation for
1104 l *= 0.30102999566398119523;
1105 /* Round down to the next integer. */
1106 return (int) l + (l < 0 ? -1 : 0);
1112 VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list args)
1117 if (PRINTF_PARSE (format, &d, &a) < 0)
1128 if (printf_fetchargs (args, &a) < 0)
1136 size_t buf_neededlength;
1138 CHAR_T *buf_malloced;
1142 /* Output string accumulator. */
1147 /* Allocate a small buffer that will hold a directive passed to
1148 sprintf or snprintf. */
1150 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1152 if (buf_neededlength < 4000 / sizeof (CHAR_T))
1154 buf = (CHAR_T *) alloca (buf_neededlength * sizeof (CHAR_T));
1155 buf_malloced = NULL;
1160 size_t buf_memsize = xtimes (buf_neededlength, sizeof (CHAR_T));
1161 if (size_overflow_p (buf_memsize))
1162 goto out_of_memory_1;
1163 buf = (CHAR_T *) malloc (buf_memsize);
1165 goto out_of_memory_1;
1169 if (resultbuf != NULL)
1172 allocated = *lengthp;
1181 result is either == resultbuf or == NULL or malloc-allocated.
1182 If length > 0, then result != NULL. */
1184 /* Ensures that allocated >= needed. Aborts through a jump to
1185 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1186 #define ENSURE_ALLOCATION(needed) \
1187 if ((needed) > allocated) \
1189 size_t memory_size; \
1192 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1193 if ((needed) > allocated) \
1194 allocated = (needed); \
1195 memory_size = xtimes (allocated, sizeof (CHAR_T)); \
1196 if (size_overflow_p (memory_size)) \
1197 goto out_of_memory; \
1198 if (result == resultbuf || result == NULL) \
1199 memory = (CHAR_T *) malloc (memory_size); \
1201 memory = (CHAR_T *) realloc (result, memory_size); \
1202 if (memory == NULL) \
1203 goto out_of_memory; \
1204 if (result == resultbuf && length > 0) \
1205 memcpy (memory, result, length * sizeof (CHAR_T)); \
1209 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1211 if (cp != dp->dir_start)
1213 size_t n = dp->dir_start - cp;
1214 size_t augmented_length = xsum (length, n);
1216 ENSURE_ALLOCATION (augmented_length);
1217 memcpy (result + length, cp, n * sizeof (CHAR_T));
1218 length = augmented_length;
1223 /* Execute a single directive. */
1224 if (dp->conversion == '%')
1226 size_t augmented_length;
1228 if (!(dp->arg_index == ARG_NONE))
1230 augmented_length = xsum (length, 1);
1231 ENSURE_ALLOCATION (augmented_length);
1232 result[length] = '%';
1233 length = augmented_length;
1237 if (!(dp->arg_index != ARG_NONE))
1240 if (dp->conversion == 'n')
1242 switch (a.arg[dp->arg_index].type)
1244 case TYPE_COUNT_SCHAR_POINTER:
1245 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1247 case TYPE_COUNT_SHORT_POINTER:
1248 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1250 case TYPE_COUNT_INT_POINTER:
1251 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1253 case TYPE_COUNT_LONGINT_POINTER:
1254 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1256 #if HAVE_LONG_LONG_INT
1257 case TYPE_COUNT_LONGLONGINT_POINTER:
1258 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1265 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
1266 else if ((dp->conversion == 'f' || dp->conversion == 'F'
1267 || dp->conversion == 'e' || dp->conversion == 'E'
1268 || dp->conversion == 'g' || dp->conversion == 'G')
1269 && a.arg[dp->arg_index].type == TYPE_LONGDOUBLE)
1271 int flags = dp->flags;
1285 if (dp->width_start != dp->width_end)
1287 if (dp->width_arg_index != ARG_NONE)
1291 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1293 arg = a.arg[dp->width_arg_index].a.a_int;
1296 /* "A negative field width is taken as a '-' flag
1297 followed by a positive field width." */
1299 width = (unsigned int) (-arg);
1306 const CHAR_T *digitp = dp->width_start;
1309 width = xsum (xtimes (width, 10), *digitp++ - '0');
1310 while (digitp != dp->width_end);
1317 if (dp->precision_start != dp->precision_end)
1319 if (dp->precision_arg_index != ARG_NONE)
1323 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1325 arg = a.arg[dp->precision_arg_index].a.a_int;
1326 /* "A negative precision is taken as if the precision
1336 const CHAR_T *digitp = dp->precision_start + 1;
1339 while (digitp != dp->precision_end)
1340 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1345 arg = a.arg[dp->arg_index].a.a_longdouble;
1347 /* Allocate a temporary buffer of sufficient size. */
1348 tmp_length = LDBL_DIG + 1;
1349 if (tmp_length < precision)
1350 tmp_length = precision;
1351 if (dp->conversion == 'f' || dp->conversion == 'F')
1352 if (!(isnanl (arg) || arg + arg == arg))
1354 int exponent = floorlog10l (arg < 0 ? -arg : arg);
1355 if (exponent >= 0 && tmp_length < exponent + precision)
1356 tmp_length = exponent + precision;
1358 /* Account for sign, decimal point etc. */
1359 tmp_length = xsum (tmp_length, 12);
1361 if (tmp_length < width)
1364 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1366 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1370 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1372 if (size_overflow_p (tmp_memsize))
1373 /* Overflow, would lead to out of memory. */
1375 tmp = (CHAR_T *) malloc (tmp_memsize);
1377 /* Out of memory. */
1386 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1388 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1392 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1398 DECL_LONG_DOUBLE_ROUNDING
1400 BEGIN_LONG_DOUBLE_ROUNDING ();
1402 if (signbit (arg)) /* arg < 0.0L or negative zero */
1410 else if (flags & FLAG_SHOWSIGN)
1412 else if (flags & FLAG_SPACE)
1415 if (arg > 0.0L && arg + arg == arg)
1417 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1419 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1423 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1430 if (dp->conversion == 'f' || dp->conversion == 'F')
1439 scale10_round_decimal_long_double (arg, precision);
1442 END_LONG_DOUBLE_ROUNDING ();
1445 ndigits = strlen (digits);
1447 if (ndigits > precision)
1451 *p++ = digits[ndigits];
1453 while (ndigits > precision);
1456 /* Here ndigits <= precision. */
1457 if ((flags & FLAG_ALT) || precision > 0)
1459 *p++ = decimal_point_char ();
1460 for (; precision > ndigits; precision--)
1465 *p++ = digits[ndigits];
1471 else if (dp->conversion == 'e' || dp->conversion == 'E')
1482 if ((flags & FLAG_ALT) || precision > 0)
1484 *p++ = decimal_point_char ();
1485 for (; precision > 0; precision--)
1496 exponent = floorlog10l (arg);
1501 scale10_round_decimal_long_double (arg,
1502 (int)precision - exponent);
1505 END_LONG_DOUBLE_ROUNDING ();
1508 ndigits = strlen (digits);
1510 if (ndigits == precision + 1)
1512 if (ndigits < precision
1513 || ndigits > precision + 2)
1514 /* The exponent was not guessed precisely
1518 /* None of two values of exponent is the
1519 right one. Prevent an endless loop. */
1522 if (ndigits == precision)
1529 /* Here ndigits = precision+1. */
1530 *p++ = digits[--ndigits];
1531 if ((flags & FLAG_ALT) || precision > 0)
1533 *p++ = decimal_point_char ();
1537 *p++ = digits[ndigits];
1544 *p++ = dp->conversion; /* 'e' or 'E' */
1545 # if WIDE_CHAR_VERSION
1547 static const wchar_t decimal_format[] =
1548 { '%', '+', '.', '2', 'd', '\0' };
1549 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1552 sprintf (p, "%+.2d", exponent);
1557 else if (dp->conversion == 'g' || dp->conversion == 'G')
1559 /* This is not specified by POSIX, but
1560 implementations appear to do this. */
1566 /* precision >= 1. */
1569 /* The exponent is 0, >= -4, < precision.
1570 Use fixed-point notation. */
1572 size_t ndigits = precision;
1573 /* Number of trailing zeroes that have to be
1576 (flags & FLAG_ALT ? 0 : precision - 1);
1580 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1582 *p++ = decimal_point_char ();
1583 while (ndigits > nzeroes)
1599 exponent = floorlog10l (arg);
1604 scale10_round_decimal_long_double (arg,
1605 (int)(precision - 1) - exponent);
1608 END_LONG_DOUBLE_ROUNDING ();
1611 ndigits = strlen (digits);
1613 if (ndigits == precision)
1615 if (ndigits < precision - 1
1616 || ndigits > precision + 1)
1617 /* The exponent was not guessed precisely
1621 /* None of two values of exponent is the
1622 right one. Prevent an endless loop. */
1625 if (ndigits < precision)
1631 /* Here ndigits = precision. */
1633 /* Determine the number of trailing zeroes that
1634 have to be dropped. */
1636 if ((flags & FLAG_ALT) == 0)
1637 while (nzeroes < ndigits
1638 && digits[nzeroes] == '0')
1641 /* The exponent is now determined. */
1642 if (exponent >= -4 && exponent < (long)precision)
1644 /* Fixed-point notation: max(exponent,0)+1
1645 digits, then the decimal point, then the
1646 remaining digits without trailing zeroes. */
1649 size_t count = exponent + 1;
1650 /* Note: count <= precision = ndigits. */
1651 for (; count > 0; count--)
1652 *p++ = digits[--ndigits];
1653 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1655 *p++ = decimal_point_char ();
1656 while (ndigits > nzeroes)
1659 *p++ = digits[ndigits];
1665 size_t count = -exponent - 1;
1667 *p++ = decimal_point_char ();
1668 for (; count > 0; count--)
1670 while (ndigits > nzeroes)
1673 *p++ = digits[ndigits];
1679 /* Exponential notation. */
1680 *p++ = digits[--ndigits];
1681 if ((flags & FLAG_ALT) || ndigits > nzeroes)
1683 *p++ = decimal_point_char ();
1684 while (ndigits > nzeroes)
1687 *p++ = digits[ndigits];
1690 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
1691 # if WIDE_CHAR_VERSION
1693 static const wchar_t decimal_format[] =
1694 { '%', '+', '.', '2', 'd', '\0' };
1695 SNPRINTF (p, 6 + 1, decimal_format, exponent);
1698 sprintf (p, "%+.2d", exponent);
1711 END_LONG_DOUBLE_ROUNDING ();
1714 /* The generated string now extends from tmp to p, with the
1715 zero padding insertion point being at pad_ptr. */
1716 if (has_width && p - tmp < width)
1718 size_t pad = width - (p - tmp);
1719 CHAR_T *end = p + pad;
1721 if (flags & FLAG_LEFT)
1723 /* Pad with spaces on the right. */
1724 for (; pad > 0; pad--)
1727 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
1729 /* Pad with zeroes. */
1734 for (; pad > 0; pad--)
1739 /* Pad with spaces on the left. */
1744 for (; pad > 0; pad--)
1752 size_t count = p - tmp;
1754 if (count >= tmp_length)
1755 /* tmp_length was incorrectly calculated - fix the
1759 /* Make room for the result. */
1760 if (count >= allocated - length)
1762 size_t n = xsum (length, count);
1764 ENSURE_ALLOCATION (n);
1767 /* Append the result. */
1768 memcpy (result + length, tmp, count * sizeof (CHAR_T));
1775 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
1776 else if (dp->conversion == 'a' || dp->conversion == 'A')
1778 arg_type type = a.arg[dp->arg_index].type;
1779 int flags = dp->flags;
1792 if (dp->width_start != dp->width_end)
1794 if (dp->width_arg_index != ARG_NONE)
1798 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1800 arg = a.arg[dp->width_arg_index].a.a_int;
1803 /* "A negative field width is taken as a '-' flag
1804 followed by a positive field width." */
1806 width = (unsigned int) (-arg);
1813 const CHAR_T *digitp = dp->width_start;
1816 width = xsum (xtimes (width, 10), *digitp++ - '0');
1817 while (digitp != dp->width_end);
1824 if (dp->precision_start != dp->precision_end)
1826 if (dp->precision_arg_index != ARG_NONE)
1830 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1832 arg = a.arg[dp->precision_arg_index].a.a_int;
1833 /* "A negative precision is taken as if the precision
1843 const CHAR_T *digitp = dp->precision_start + 1;
1846 while (digitp != dp->precision_end)
1847 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1852 /* Allocate a temporary buffer of sufficient size. */
1853 if (type == TYPE_LONGDOUBLE)
1855 (unsigned int) ((LDBL_DIG + 1)
1856 * 0.831 /* decimal -> hexadecimal */
1858 + 1; /* turn floor into ceil */
1861 (unsigned int) ((DBL_DIG + 1)
1862 * 0.831 /* decimal -> hexadecimal */
1864 + 1; /* turn floor into ceil */
1865 if (tmp_length < precision)
1866 tmp_length = precision;
1867 /* Account for sign, decimal point etc. */
1868 tmp_length = xsum (tmp_length, 12);
1870 if (tmp_length < width)
1873 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1875 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1879 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1881 if (size_overflow_p (tmp_memsize))
1882 /* Overflow, would lead to out of memory. */
1884 tmp = (CHAR_T *) malloc (tmp_memsize);
1886 /* Out of memory. */
1892 if (type == TYPE_LONGDOUBLE)
1894 long double arg = a.arg[dp->arg_index].a.a_longdouble;
1898 if (dp->conversion == 'A')
1900 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1904 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1910 DECL_LONG_DOUBLE_ROUNDING
1912 BEGIN_LONG_DOUBLE_ROUNDING ();
1914 if (signbit (arg)) /* arg < 0.0L or negative zero */
1922 else if (flags & FLAG_SHOWSIGN)
1924 else if (flags & FLAG_SPACE)
1927 if (arg > 0.0L && arg + arg == arg)
1929 if (dp->conversion == 'A')
1931 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1935 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1941 long double mantissa;
1944 mantissa = printf_frexpl (arg, &exponent);
1952 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
1954 /* Round the mantissa. */
1955 long double tail = mantissa;
1958 for (q = precision; ; q--)
1960 int digit = (int) tail;
1964 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
1973 for (q = precision; q > 0; q--)
1979 *p++ = dp->conversion - 'A' + 'X';
1984 digit = (int) mantissa;
1987 if ((flags & FLAG_ALT)
1988 || mantissa > 0.0L || precision > 0)
1990 *p++ = decimal_point_char ();
1991 /* This loop terminates because we assume
1992 that FLT_RADIX is a power of 2. */
1993 while (mantissa > 0.0L)
1996 digit = (int) mantissa;
2001 : dp->conversion - 10);
2005 while (precision > 0)
2012 *p++ = dp->conversion - 'A' + 'P';
2013 # if WIDE_CHAR_VERSION
2015 static const wchar_t decimal_format[] =
2016 { '%', '+', 'd', '\0' };
2017 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2020 sprintf (p, "%+d", exponent);
2026 END_LONG_DOUBLE_ROUNDING ();
2031 double arg = a.arg[dp->arg_index].a.a_double;
2035 if (dp->conversion == 'A')
2037 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2041 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2048 if (signbit (arg)) /* arg < 0.0 or negative zero */
2056 else if (flags & FLAG_SHOWSIGN)
2058 else if (flags & FLAG_SPACE)
2061 if (arg > 0.0 && arg + arg == arg)
2063 if (dp->conversion == 'A')
2065 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2069 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2078 mantissa = printf_frexp (arg, &exponent);
2086 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2088 /* Round the mantissa. */
2089 double tail = mantissa;
2092 for (q = precision; ; q--)
2094 int digit = (int) tail;
2098 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2107 for (q = precision; q > 0; q--)
2113 *p++ = dp->conversion - 'A' + 'X';
2118 digit = (int) mantissa;
2121 if ((flags & FLAG_ALT)
2122 || mantissa > 0.0 || precision > 0)
2124 *p++ = decimal_point_char ();
2125 /* This loop terminates because we assume
2126 that FLT_RADIX is a power of 2. */
2127 while (mantissa > 0.0)
2130 digit = (int) mantissa;
2135 : dp->conversion - 10);
2139 while (precision > 0)
2146 *p++ = dp->conversion - 'A' + 'P';
2147 # if WIDE_CHAR_VERSION
2149 static const wchar_t decimal_format[] =
2150 { '%', '+', 'd', '\0' };
2151 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2154 sprintf (p, "%+d", exponent);
2161 /* The generated string now extends from tmp to p, with the
2162 zero padding insertion point being at pad_ptr. */
2163 if (has_width && p - tmp < width)
2165 size_t pad = width - (p - tmp);
2166 CHAR_T *end = p + pad;
2168 if (flags & FLAG_LEFT)
2170 /* Pad with spaces on the right. */
2171 for (; pad > 0; pad--)
2174 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2176 /* Pad with zeroes. */
2181 for (; pad > 0; pad--)
2186 /* Pad with spaces on the left. */
2191 for (; pad > 0; pad--)
2199 size_t count = p - tmp;
2201 if (count >= tmp_length)
2202 /* tmp_length was incorrectly calculated - fix the
2206 /* Make room for the result. */
2207 if (count >= allocated - length)
2209 size_t n = xsum (length, count);
2211 ENSURE_ALLOCATION (n);
2214 /* Append the result. */
2215 memcpy (result + length, tmp, count * sizeof (CHAR_T));
2224 arg_type type = a.arg[dp->arg_index].type;
2225 int flags = dp->flags;
2226 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2230 #if NEED_PRINTF_FLAG_ZERO
2233 # define pad_ourselves 0
2236 unsigned int prefix_count;
2244 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2247 if (dp->width_start != dp->width_end)
2249 if (dp->width_arg_index != ARG_NONE)
2253 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2255 arg = a.arg[dp->width_arg_index].a.a_int;
2258 /* "A negative field width is taken as a '-' flag
2259 followed by a positive field width." */
2261 width = (unsigned int) (-arg);
2268 const CHAR_T *digitp = dp->width_start;
2271 width = xsum (xtimes (width, 10), *digitp++ - '0');
2272 while (digitp != dp->width_end);
2279 /* Allocate a temporary buffer of sufficient size for calling
2285 if (dp->precision_start != dp->precision_end)
2287 if (dp->precision_arg_index != ARG_NONE)
2291 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2293 arg = a.arg[dp->precision_arg_index].a.a_int;
2294 precision = (arg < 0 ? 0 : arg);
2298 const CHAR_T *digitp = dp->precision_start + 1;
2301 while (digitp != dp->precision_end)
2302 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2306 switch (dp->conversion)
2309 case 'd': case 'i': case 'u':
2310 # if HAVE_LONG_LONG_INT
2311 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2313 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2314 * 0.30103 /* binary -> decimal */
2316 + 1; /* turn floor into ceil */
2319 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2321 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2322 * 0.30103 /* binary -> decimal */
2324 + 1; /* turn floor into ceil */
2327 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2328 * 0.30103 /* binary -> decimal */
2330 + 1; /* turn floor into ceil */
2331 if (tmp_length < precision)
2332 tmp_length = precision;
2333 /* Multiply by 2, as an estimate for FLAG_GROUP. */
2334 tmp_length = xsum (tmp_length, tmp_length);
2335 /* Add 1, to account for a leading sign. */
2336 tmp_length = xsum (tmp_length, 1);
2340 # if HAVE_LONG_LONG_INT
2341 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2343 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2344 * 0.333334 /* binary -> octal */
2346 + 1; /* turn floor into ceil */
2349 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2351 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2352 * 0.333334 /* binary -> octal */
2354 + 1; /* turn floor into ceil */
2357 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2358 * 0.333334 /* binary -> octal */
2360 + 1; /* turn floor into ceil */
2361 if (tmp_length < precision)
2362 tmp_length = precision;
2363 /* Add 1, to account for a leading sign. */
2364 tmp_length = xsum (tmp_length, 1);
2368 # if HAVE_LONG_LONG_INT
2369 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2371 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2372 * 0.25 /* binary -> hexadecimal */
2374 + 1; /* turn floor into ceil */
2377 if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2379 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2380 * 0.25 /* binary -> hexadecimal */
2382 + 1; /* turn floor into ceil */
2385 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2386 * 0.25 /* binary -> hexadecimal */
2388 + 1; /* turn floor into ceil */
2389 if (tmp_length < precision)
2390 tmp_length = precision;
2391 /* Add 2, to account for a leading sign or alternate form. */
2392 tmp_length = xsum (tmp_length, 2);
2396 if (type == TYPE_LONGDOUBLE)
2398 (unsigned int) (LDBL_MAX_EXP
2399 * 0.30103 /* binary -> decimal */
2400 * 2 /* estimate for FLAG_GROUP */
2402 + 1 /* turn floor into ceil */
2403 + 10; /* sign, decimal point etc. */
2406 (unsigned int) (DBL_MAX_EXP
2407 * 0.30103 /* binary -> decimal */
2408 * 2 /* estimate for FLAG_GROUP */
2410 + 1 /* turn floor into ceil */
2411 + 10; /* sign, decimal point etc. */
2412 tmp_length = xsum (tmp_length, precision);
2415 case 'e': case 'E': case 'g': case 'G':
2417 12; /* sign, decimal point, exponent etc. */
2418 tmp_length = xsum (tmp_length, precision);
2422 if (type == TYPE_LONGDOUBLE)
2424 (unsigned int) (LDBL_DIG
2425 * 0.831 /* decimal -> hexadecimal */
2427 + 1; /* turn floor into ceil */
2430 (unsigned int) (DBL_DIG
2431 * 0.831 /* decimal -> hexadecimal */
2433 + 1; /* turn floor into ceil */
2434 if (tmp_length < precision)
2435 tmp_length = precision;
2436 /* Account for sign, decimal point etc. */
2437 tmp_length = xsum (tmp_length, 12);
2441 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
2442 if (type == TYPE_WIDE_CHAR)
2443 tmp_length = MB_CUR_MAX;
2451 if (type == TYPE_WIDE_STRING)
2454 local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
2456 # if !WIDE_CHAR_VERSION
2457 tmp_length = xtimes (tmp_length, MB_CUR_MAX);
2462 tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
2467 (unsigned int) (sizeof (void *) * CHAR_BIT
2468 * 0.25 /* binary -> hexadecimal */
2470 + 1 /* turn floor into ceil */
2471 + 2; /* account for leading 0x */
2478 if (tmp_length < width)
2481 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2484 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2488 size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2490 if (size_overflow_p (tmp_memsize))
2491 /* Overflow, would lead to out of memory. */
2493 tmp = (CHAR_T *) malloc (tmp_memsize);
2495 /* Out of memory. */
2500 /* Decide whether to perform the padding ourselves. */
2501 #if NEED_PRINTF_FLAG_ZERO
2502 switch (dp->conversion)
2504 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
2514 /* Construct the format string for calling snprintf or
2518 #if NEED_PRINTF_FLAG_GROUPING
2519 /* The underlying implementation doesn't support the ' flag.
2520 Produce no grouping characters in this case; this is
2521 acceptable because the grouping is locale dependent. */
2523 if (flags & FLAG_GROUP)
2526 if (flags & FLAG_LEFT)
2528 if (flags & FLAG_SHOWSIGN)
2530 if (flags & FLAG_SPACE)
2532 if (flags & FLAG_ALT)
2536 if (flags & FLAG_ZERO)
2538 if (dp->width_start != dp->width_end)
2540 size_t n = dp->width_end - dp->width_start;
2541 memcpy (fbp, dp->width_start, n * sizeof (CHAR_T));
2545 if (dp->precision_start != dp->precision_end)
2547 size_t n = dp->precision_end - dp->precision_start;
2548 memcpy (fbp, dp->precision_start, n * sizeof (CHAR_T));
2554 #if HAVE_LONG_LONG_INT
2555 case TYPE_LONGLONGINT:
2556 case TYPE_ULONGLONGINT:
2557 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2570 case TYPE_WIDE_CHAR:
2573 case TYPE_WIDE_STRING:
2577 case TYPE_LONGDOUBLE:
2583 #if NEED_PRINTF_DIRECTIVE_F
2584 if (dp->conversion == 'F')
2588 *fbp = dp->conversion;
2597 /* Construct the arguments for calling snprintf or sprintf. */
2599 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
2601 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2603 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
2605 if (dp->precision_arg_index != ARG_NONE)
2607 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2609 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
2613 /* Prepare checking whether snprintf returns the count
2615 ENSURE_ALLOCATION (xsum (length, 1));
2616 result[length] = '\0';
2625 maxlen = allocated - length;
2630 /* SNPRINTF can fail if maxlen > INT_MAX. */
2631 if (maxlen > INT_MAX)
2633 # define SNPRINTF_BUF(arg) \
2634 switch (prefix_count) \
2637 retcount = SNPRINTF (result + length, maxlen, buf, \
2641 retcount = SNPRINTF (result + length, maxlen, buf, \
2642 prefixes[0], arg, &count); \
2645 retcount = SNPRINTF (result + length, maxlen, buf, \
2646 prefixes[0], prefixes[1], arg, \
2653 # define SNPRINTF_BUF(arg) \
2654 switch (prefix_count) \
2657 count = sprintf (tmp, buf, arg); \
2660 count = sprintf (tmp, buf, prefixes[0], arg); \
2663 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
2675 int arg = a.arg[dp->arg_index].a.a_schar;
2681 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
2687 int arg = a.arg[dp->arg_index].a.a_short;
2693 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
2699 int arg = a.arg[dp->arg_index].a.a_int;
2705 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
2711 long int arg = a.arg[dp->arg_index].a.a_longint;
2717 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
2721 #if HAVE_LONG_LONG_INT
2722 case TYPE_LONGLONGINT:
2724 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
2728 case TYPE_ULONGLONGINT:
2730 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
2737 double arg = a.arg[dp->arg_index].a.a_double;
2741 case TYPE_LONGDOUBLE:
2743 long double arg = a.arg[dp->arg_index].a.a_longdouble;
2749 int arg = a.arg[dp->arg_index].a.a_char;
2754 case TYPE_WIDE_CHAR:
2756 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
2763 const char *arg = a.arg[dp->arg_index].a.a_string;
2768 case TYPE_WIDE_STRING:
2770 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2777 void *arg = a.arg[dp->arg_index].a.a_pointer;
2786 /* Portability: Not all implementations of snprintf()
2787 are ISO C 99 compliant. Determine the number of
2788 bytes that snprintf() has produced or would have
2792 /* Verify that snprintf() has NUL-terminated its
2794 if (count < maxlen && result[length + count] != '\0')
2796 /* Portability hack. */
2797 if (retcount > count)
2802 /* snprintf() doesn't understand the '%n'
2806 /* Don't use the '%n' directive; instead, look
2807 at the snprintf() return value. */
2813 /* Look at the snprintf() return value. */
2816 /* HP-UX 10.20 snprintf() is doubly deficient:
2817 It doesn't understand the '%n' directive,
2818 *and* it returns -1 (rather than the length
2819 that would have been required) when the
2820 buffer is too small. */
2821 size_t bigger_need =
2822 xsum (xtimes (allocated, 2), 12);
2823 ENSURE_ALLOCATION (bigger_need);
2832 /* Attempt to handle failure. */
2835 if (!(result == resultbuf || result == NULL))
2837 if (buf_malloced != NULL)
2838 free (buf_malloced);
2844 /* Perform padding. */
2845 #if NEED_PRINTF_FLAG_ZERO
2846 if (pad_ourselves && has_width && count < width)
2849 /* Make room for the result. */
2850 if (width >= maxlen)
2852 /* Need at least width bytes. But allocate
2853 proportionally, to avoid looping eternally if
2854 snprintf() reports a too small count. */
2856 xmax (xsum (length, width),
2857 xtimes (allocated, 2));
2860 ENSURE_ALLOCATION (n);
2862 maxlen = allocated - length; /* >= width */
2867 CHAR_T * const rp = result + length;
2869 CHAR_T * const rp = tmp;
2871 CHAR_T *p = rp + count;
2872 size_t pad = width - count;
2873 CHAR_T *end = p + pad;
2874 CHAR_T *pad_ptr = (*rp == '-' ? rp + 1 : rp);
2875 /* No zero-padding of "inf" and "nan". */
2876 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
2877 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
2879 /* The generated string now extends from rp to p,
2880 with the zero padding insertion point being at
2883 if (flags & FLAG_LEFT)
2885 /* Pad with spaces on the right. */
2886 for (; pad > 0; pad--)
2889 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2891 /* Pad with zeroes. */
2896 for (; pad > 0; pad--)
2901 /* Pad with spaces on the left. */
2906 for (; pad > 0; pad--)
2910 count = width; /* = count + pad = end - rp */
2916 if (count >= tmp_length)
2917 /* tmp_length was incorrectly calculated - fix the
2922 /* Make room for the result. */
2923 if (count >= maxlen)
2925 /* Need at least count bytes. But allocate
2926 proportionally, to avoid looping eternally if
2927 snprintf() reports a too small count. */
2929 xmax (xsum (length, count), xtimes (allocated, 2));
2931 ENSURE_ALLOCATION (n);
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);