Fix rounding when a precision is given.
[gnulib.git] / lib / vasnprintf.c
1 /* vsprintf with automatic memory allocation.
2    Copyright (C) 1999, 2002-2008 Free Software Foundation, Inc.
3
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)
7    any later version.
8
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.
13
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.  */
17
18 /* This file can be parametrized with the following macros:
19      VASNPRINTF         The name of the function being defined.
20      FCHAR_T            The element type of the format string.
21      DCHAR_T            The element type of the destination (result) string.
22      FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
23                         in the format string are ASCII. MUST be set if
24                         FCHAR_T and DCHAR_T are not the same type.
25      DIRECTIVE          Structure denoting a format directive.
26                         Depends on FCHAR_T.
27      DIRECTIVES         Structure denoting the set of format directives of a
28                         format string.  Depends on FCHAR_T.
29      PRINTF_PARSE       Function that parses a format string.
30                         Depends on FCHAR_T.
31      DCHAR_CPY          memcpy like function for DCHAR_T[] arrays.
32      DCHAR_SET          memset like function for DCHAR_T[] arrays.
33      DCHAR_MBSNLEN      mbsnlen like function for DCHAR_T[] arrays.
34      SNPRINTF           The system's snprintf (or similar) function.
35                         This may be either snprintf or swprintf.
36      TCHAR_T            The element type of the argument and result string
37                         of the said SNPRINTF function.  This may be either
38                         char or wchar_t.  The code exploits that
39                         sizeof (TCHAR_T) | sizeof (DCHAR_T) and
40                         alignof (TCHAR_T) <= alignof (DCHAR_T).
41      DCHAR_IS_TCHAR     Set to 1 if DCHAR_T and TCHAR_T are the same type.
42      DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
43      DCHAR_IS_UINT8_T   Set to 1 if DCHAR_T is uint8_t.
44      DCHAR_IS_UINT16_T  Set to 1 if DCHAR_T is uint16_t.
45      DCHAR_IS_UINT32_T  Set to 1 if DCHAR_T is uint32_t.  */
46
47 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
48    This must come before <config.h> because <config.h> may include
49    <features.h>, and once <features.h> has been included, it's too late.  */
50 #ifndef _GNU_SOURCE
51 # define _GNU_SOURCE    1
52 #endif
53
54 #ifndef VASNPRINTF
55 # include <config.h>
56 #endif
57 #ifndef IN_LIBINTL
58 # include <alloca.h>
59 #endif
60
61 /* Specification.  */
62 #ifndef VASNPRINTF
63 # if WIDE_CHAR_VERSION
64 #  include "vasnwprintf.h"
65 # else
66 #  include "vasnprintf.h"
67 # endif
68 #endif
69
70 #include <locale.h>     /* localeconv() */
71 #include <stdio.h>      /* snprintf(), sprintf() */
72 #include <stdlib.h>     /* abort(), malloc(), realloc(), free() */
73 #include <string.h>     /* memcpy(), strlen() */
74 #include <errno.h>      /* errno */
75 #include <limits.h>     /* CHAR_BIT */
76 #include <float.h>      /* DBL_MAX_EXP, LDBL_MAX_EXP */
77 #if HAVE_NL_LANGINFO
78 # include <langinfo.h>
79 #endif
80 #ifndef VASNPRINTF
81 # if WIDE_CHAR_VERSION
82 #  include "wprintf-parse.h"
83 # else
84 #  include "printf-parse.h"
85 # endif
86 #endif
87
88 /* Checked size_t computations.  */
89 #include "xsize.h"
90
91 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
92 # include <math.h>
93 # include "float+.h"
94 #endif
95
96 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
97 # include <math.h>
98 # include "isnand.h"
99 #endif
100
101 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
102 # include <math.h>
103 # include "isnanl-nolibm.h"
104 # include "fpucw.h"
105 #endif
106
107 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
108 # include <math.h>
109 # include "isnand.h"
110 # include "printf-frexp.h"
111 #endif
112
113 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
114 # include <math.h>
115 # include "isnanl-nolibm.h"
116 # include "printf-frexpl.h"
117 # include "fpucw.h"
118 #endif
119
120 #if HAVE_WCHAR_T
121 # if HAVE_WCSLEN
122 #  define local_wcslen wcslen
123 # else
124    /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
125       a dependency towards this library, here is a local substitute.
126       Define this substitute only once, even if this file is included
127       twice in the same compilation unit.  */
128 #  ifndef local_wcslen_defined
129 #   define local_wcslen_defined 1
130 static size_t
131 local_wcslen (const wchar_t *s)
132 {
133   const wchar_t *ptr;
134
135   for (ptr = s; *ptr != (wchar_t) 0; ptr++)
136     ;
137   return ptr - s;
138 }
139 #  endif
140 # endif
141 #endif
142
143 /* Default parameters.  */
144 #ifndef VASNPRINTF
145 # if WIDE_CHAR_VERSION
146 #  define VASNPRINTF vasnwprintf
147 #  define FCHAR_T wchar_t
148 #  define DCHAR_T wchar_t
149 #  define TCHAR_T wchar_t
150 #  define DCHAR_IS_TCHAR 1
151 #  define DIRECTIVE wchar_t_directive
152 #  define DIRECTIVES wchar_t_directives
153 #  define PRINTF_PARSE wprintf_parse
154 #  define DCHAR_CPY wmemcpy
155 # else
156 #  define VASNPRINTF vasnprintf
157 #  define FCHAR_T char
158 #  define DCHAR_T char
159 #  define TCHAR_T char
160 #  define DCHAR_IS_TCHAR 1
161 #  define DIRECTIVE char_directive
162 #  define DIRECTIVES char_directives
163 #  define PRINTF_PARSE printf_parse
164 #  define DCHAR_CPY memcpy
165 # endif
166 #endif
167 #if WIDE_CHAR_VERSION
168   /* TCHAR_T is wchar_t.  */
169 # define USE_SNPRINTF 1
170 # if HAVE_DECL__SNWPRINTF
171    /* On Windows, the function swprintf() has a different signature than
172       on Unix; we use the _snwprintf() function instead.  */
173 #  define SNPRINTF _snwprintf
174 # else
175    /* Unix.  */
176 #  define SNPRINTF swprintf
177 # endif
178 #else
179   /* TCHAR_T is char.  */
180 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
181      But don't use it on BeOS, since BeOS snprintf produces no output if the
182      size argument is >= 0x3000000.  */
183 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
184 #  define USE_SNPRINTF 1
185 # else
186 #  define USE_SNPRINTF 0
187 # endif
188 # if HAVE_DECL__SNPRINTF
189    /* Windows.  */
190 #  define SNPRINTF _snprintf
191 # else
192    /* Unix.  */
193 #  define SNPRINTF snprintf
194    /* Here we need to call the native snprintf, not rpl_snprintf.  */
195 #  undef snprintf
196 # endif
197 #endif
198 /* Here we need to call the native sprintf, not rpl_sprintf.  */
199 #undef sprintf
200
201 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
202 /* Determine the decimal-point character according to the current locale.  */
203 # ifndef decimal_point_char_defined
204 #  define decimal_point_char_defined 1
205 static char
206 decimal_point_char ()
207 {
208   const char *point;
209   /* Determine it in a multithread-safe way.  We know nl_langinfo is
210      multithread-safe on glibc systems, but is not required to be multithread-
211      safe by POSIX.  sprintf(), however, is multithread-safe.  localeconv()
212      is rarely multithread-safe.  */
213 #  if HAVE_NL_LANGINFO && __GLIBC__
214   point = nl_langinfo (RADIXCHAR);
215 #  elif 1
216   char pointbuf[5];
217   sprintf (pointbuf, "%#.0f", 1.0);
218   point = &pointbuf[1];
219 #  else
220   point = localeconv () -> decimal_point;
221 #  endif
222   /* The decimal point is always a single byte: either '.' or ','.  */
223   return (point[0] != '\0' ? point[0] : '.');
224 }
225 # endif
226 #endif
227
228 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
229
230 /* Equivalent to !isfinite(x) || x == 0, but does not require libm.  */
231 static int
232 is_infinite_or_zero (double x)
233 {
234   return isnand (x) || x + x == x;
235 }
236
237 #endif
238
239 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
240
241 /* Equivalent to !isfinite(x), but does not require libm.  */
242 static int
243 is_infinitel (long double x)
244 {
245   return isnanl (x) || (x + x == x && x != 0.0L);
246 }
247
248 #endif
249
250 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
251
252 /* Converting 'long double' to decimal without rare rounding bugs requires
253    real bignums.  We use the naming conventions of GNU gmp, but vastly simpler
254    (and slower) algorithms.  */
255
256 typedef unsigned int mp_limb_t;
257 # define GMP_LIMB_BITS 32
258 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
259
260 typedef unsigned long long mp_twolimb_t;
261 # define GMP_TWOLIMB_BITS 64
262 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
263
264 /* Representation of a bignum >= 0.  */
265 typedef struct
266 {
267   size_t nlimbs;
268   mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc().  */
269 } mpn_t;
270
271 /* Compute the product of two bignums >= 0.
272    Return the allocated memory in case of success, NULL in case of memory
273    allocation failure.  */
274 static void *
275 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
276 {
277   const mp_limb_t *p1;
278   const mp_limb_t *p2;
279   size_t len1;
280   size_t len2;
281
282   if (src1.nlimbs <= src2.nlimbs)
283     {
284       len1 = src1.nlimbs;
285       p1 = src1.limbs;
286       len2 = src2.nlimbs;
287       p2 = src2.limbs;
288     }
289   else
290     {
291       len1 = src2.nlimbs;
292       p1 = src2.limbs;
293       len2 = src1.nlimbs;
294       p2 = src1.limbs;
295     }
296   /* Now 0 <= len1 <= len2.  */
297   if (len1 == 0)
298     {
299       /* src1 or src2 is zero.  */
300       dest->nlimbs = 0;
301       dest->limbs = (mp_limb_t *) malloc (1);
302     }
303   else
304     {
305       /* Here 1 <= len1 <= len2.  */
306       size_t dlen;
307       mp_limb_t *dp;
308       size_t k, i, j;
309
310       dlen = len1 + len2;
311       dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
312       if (dp == NULL)
313         return NULL;
314       for (k = len2; k > 0; )
315         dp[--k] = 0;
316       for (i = 0; i < len1; i++)
317         {
318           mp_limb_t digit1 = p1[i];
319           mp_twolimb_t carry = 0;
320           for (j = 0; j < len2; j++)
321             {
322               mp_limb_t digit2 = p2[j];
323               carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
324               carry += dp[i + j];
325               dp[i + j] = (mp_limb_t) carry;
326               carry = carry >> GMP_LIMB_BITS;
327             }
328           dp[i + len2] = (mp_limb_t) carry;
329         }
330       /* Normalise.  */
331       while (dlen > 0 && dp[dlen - 1] == 0)
332         dlen--;
333       dest->nlimbs = dlen;
334       dest->limbs = dp;
335     }
336   return dest->limbs;
337 }
338
339 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
340    a is written as  a = q * b + r  with 0 <= r < b.  q is the quotient, r
341    the remainder.
342    Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
343    q is incremented.
344    Return the allocated memory in case of success, NULL in case of memory
345    allocation failure.  */
346 static void *
347 divide (mpn_t a, mpn_t b, mpn_t *q)
348 {
349   /* Algorithm:
350      First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
351      with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
352      If m<n, then q:=0 and r:=a.
353      If m>=n=1, perform a single-precision division:
354        r:=0, j:=m,
355        while j>0 do
356          {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
357                = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
358          j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
359        Normalise [q[m-1],...,q[0]], yields q.
360      If m>=n>1, perform a multiple-precision division:
361        We have a/b < beta^(m-n+1).
362        s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
363        Shift a and b left by s bits, copying them. r:=a.
364        r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
365        For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
366          Compute q* :
367            q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
368            In case of overflow (q* >= beta) set q* := beta-1.
369            Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
370            and c3 := b[n-2] * q*.
371            {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
372             occurred.  Furthermore 0 <= c3 < beta^2.
373             If there was overflow and
374             r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
375             the next test can be skipped.}
376            While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
377              Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
378            If q* > 0:
379              Put r := r - b * q* * beta^j. In detail:
380                [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
381                hence: u:=0, for i:=0 to n-1 do
382                               u := u + q* * b[i],
383                               r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
384                               u:=u div beta (+ 1, if carry in subtraction)
385                       r[n+j]:=r[n+j]-u.
386                {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
387                                < q* + 1 <= beta,
388                 the carry u does not overflow.}
389              If a negative carry occurs, put q* := q* - 1
390                and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
391          Set q[j] := q*.
392        Normalise [q[m-n],..,q[0]]; this yields the quotient q.
393        Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
394        rest r.
395        The room for q[j] can be allocated at the memory location of r[n+j].
396      Finally, round-to-even:
397        Shift r left by 1 bit.
398        If r > b or if r = b and q[0] is odd, q := q+1.
399    */
400   const mp_limb_t *a_ptr = a.limbs;
401   size_t a_len = a.nlimbs;
402   const mp_limb_t *b_ptr = b.limbs;
403   size_t b_len = b.nlimbs;
404   mp_limb_t *roomptr;
405   mp_limb_t *tmp_roomptr = NULL;
406   mp_limb_t *q_ptr;
407   size_t q_len;
408   mp_limb_t *r_ptr;
409   size_t r_len;
410
411   /* Allocate room for a_len+2 digits.
412      (Need a_len+1 digits for the real division and 1 more digit for the
413      final rounding of q.)  */
414   roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
415   if (roomptr == NULL)
416     return NULL;
417
418   /* Normalise a.  */
419   while (a_len > 0 && a_ptr[a_len - 1] == 0)
420     a_len--;
421
422   /* Normalise b.  */
423   for (;;)
424     {
425       if (b_len == 0)
426         /* Division by zero.  */
427         abort ();
428       if (b_ptr[b_len - 1] == 0)
429         b_len--;
430       else
431         break;
432     }
433
434   /* Here m = a_len >= 0 and n = b_len > 0.  */
435
436   if (a_len < b_len)
437     {
438       /* m<n: trivial case.  q=0, r := copy of a.  */
439       r_ptr = roomptr;
440       r_len = a_len;
441       memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
442       q_ptr = roomptr + a_len;
443       q_len = 0;
444     }
445   else if (b_len == 1)
446     {
447       /* n=1: single precision division.
448          beta^(m-1) <= a < beta^m  ==>  beta^(m-2) <= a/b < beta^m  */
449       r_ptr = roomptr;
450       q_ptr = roomptr + 1;
451       {
452         mp_limb_t den = b_ptr[0];
453         mp_limb_t remainder = 0;
454         const mp_limb_t *sourceptr = a_ptr + a_len;
455         mp_limb_t *destptr = q_ptr + a_len;
456         size_t count;
457         for (count = a_len; count > 0; count--)
458           {
459             mp_twolimb_t num =
460               ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
461             *--destptr = num / den;
462             remainder = num % den;
463           }
464         /* Normalise and store r.  */
465         if (remainder > 0)
466           {
467             r_ptr[0] = remainder;
468             r_len = 1;
469           }
470         else
471           r_len = 0;
472         /* Normalise q.  */
473         q_len = a_len;
474         if (q_ptr[q_len - 1] == 0)
475           q_len--;
476       }
477     }
478   else
479     {
480       /* n>1: multiple precision division.
481          beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n  ==>
482          beta^(m-n-1) <= a/b < beta^(m-n+1).  */
483       /* Determine s.  */
484       size_t s;
485       {
486         mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
487         s = 31;
488         if (msd >= 0x10000)
489           {
490             msd = msd >> 16;
491             s -= 16;
492           }
493         if (msd >= 0x100)
494           {
495             msd = msd >> 8;
496             s -= 8;
497           }
498         if (msd >= 0x10)
499           {
500             msd = msd >> 4;
501             s -= 4;
502           }
503         if (msd >= 0x4)
504           {
505             msd = msd >> 2;
506             s -= 2;
507           }
508         if (msd >= 0x2)
509           {
510             msd = msd >> 1;
511             s -= 1;
512           }
513       }
514       /* 0 <= s < GMP_LIMB_BITS.
515          Copy b, shifting it left by s bits.  */
516       if (s > 0)
517         {
518           tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
519           if (tmp_roomptr == NULL)
520             {
521               free (roomptr);
522               return NULL;
523             }
524           {
525             const mp_limb_t *sourceptr = b_ptr;
526             mp_limb_t *destptr = tmp_roomptr;
527             mp_twolimb_t accu = 0;
528             size_t count;
529             for (count = b_len; count > 0; count--)
530               {
531                 accu += (mp_twolimb_t) *sourceptr++ << s;
532                 *destptr++ = (mp_limb_t) accu;
533                 accu = accu >> GMP_LIMB_BITS;
534               }
535             /* accu must be zero, since that was how s was determined.  */
536             if (accu != 0)
537               abort ();
538           }
539           b_ptr = tmp_roomptr;
540         }
541       /* Copy a, shifting it left by s bits, yields r.
542          Memory layout:
543          At the beginning: r = roomptr[0..a_len],
544          at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len]  */
545       r_ptr = roomptr;
546       if (s == 0)
547         {
548           memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
549           r_ptr[a_len] = 0;
550         }
551       else
552         {
553           const mp_limb_t *sourceptr = a_ptr;
554           mp_limb_t *destptr = r_ptr;
555           mp_twolimb_t accu = 0;
556           size_t count;
557           for (count = a_len; count > 0; count--)
558             {
559               accu += (mp_twolimb_t) *sourceptr++ << s;
560               *destptr++ = (mp_limb_t) accu;
561               accu = accu >> GMP_LIMB_BITS;
562             }
563           *destptr++ = (mp_limb_t) accu;
564         }
565       q_ptr = roomptr + b_len;
566       q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
567       {
568         size_t j = a_len - b_len; /* m-n */
569         mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
570         mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
571         mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
572           ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
573         /* Division loop, traversed m-n+1 times.
574            j counts down, b is unchanged, beta/2 <= b[n-1] < beta.  */
575         for (;;)
576           {
577             mp_limb_t q_star;
578             mp_limb_t c1;
579             if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
580               {
581                 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow.  */
582                 mp_twolimb_t num =
583                   ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
584                   | r_ptr[j + b_len - 1];
585                 q_star = num / b_msd;
586                 c1 = num % b_msd;
587               }
588             else
589               {
590                 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1].  */
591                 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
592                 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
593                    <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
594                    <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
595                         {<= beta !}.
596                    If yes, jump directly to the subtraction loop.
597                    (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
598                     <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
599                 if (r_ptr[j + b_len] > b_msd
600                     || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
601                   /* r[j+n] >= b[n-1]+1 or
602                      r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
603                      carry.  */
604                   goto subtract;
605               }
606             /* q_star = q*,
607                c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta).  */
608             {
609               mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
610                 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
611               mp_twolimb_t c3 = /* b[n-2] * q* */
612                 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
613               /* While c2 < c3, increase c2 and decrease c3.
614                  Consider c3-c2.  While it is > 0, decrease it by
615                  b[n-1]*beta+b[n-2].  Because of b[n-1]*beta+b[n-2] >= beta^2/2
616                  this can happen only twice.  */
617               if (c3 > c2)
618                 {
619                   q_star = q_star - 1; /* q* := q* - 1 */
620                   if (c3 - c2 > b_msdd)
621                     q_star = q_star - 1; /* q* := q* - 1 */
622                 }
623             }
624             if (q_star > 0)
625               subtract:
626               {
627                 /* Subtract r := r - b * q* * beta^j.  */
628                 mp_limb_t cr;
629                 {
630                   const mp_limb_t *sourceptr = b_ptr;
631                   mp_limb_t *destptr = r_ptr + j;
632                   mp_twolimb_t carry = 0;
633                   size_t count;
634                   for (count = b_len; count > 0; count--)
635                     {
636                       /* Here 0 <= carry <= q*.  */
637                       carry =
638                         carry
639                         + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
640                         + (mp_limb_t) ~(*destptr);
641                       /* Here 0 <= carry <= beta*q* + beta-1.  */
642                       *destptr++ = ~(mp_limb_t) carry;
643                       carry = carry >> GMP_LIMB_BITS; /* <= q* */
644                     }
645                   cr = (mp_limb_t) carry;
646                 }
647                 /* Subtract cr from r_ptr[j + b_len], then forget about
648                    r_ptr[j + b_len].  */
649                 if (cr > r_ptr[j + b_len])
650                   {
651                     /* Subtraction gave a carry.  */
652                     q_star = q_star - 1; /* q* := q* - 1 */
653                     /* Add b back.  */
654                     {
655                       const mp_limb_t *sourceptr = b_ptr;
656                       mp_limb_t *destptr = r_ptr + j;
657                       mp_limb_t carry = 0;
658                       size_t count;
659                       for (count = b_len; count > 0; count--)
660                         {
661                           mp_limb_t source1 = *sourceptr++;
662                           mp_limb_t source2 = *destptr;
663                           *destptr++ = source1 + source2 + carry;
664                           carry =
665                             (carry
666                              ? source1 >= (mp_limb_t) ~source2
667                              : source1 > (mp_limb_t) ~source2);
668                         }
669                     }
670                     /* Forget about the carry and about r[j+n].  */
671                   }
672               }
673             /* q* is determined.  Store it as q[j].  */
674             q_ptr[j] = q_star;
675             if (j == 0)
676               break;
677             j--;
678           }
679       }
680       r_len = b_len;
681       /* Normalise q.  */
682       if (q_ptr[q_len - 1] == 0)
683         q_len--;
684 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
685           b is shifted left by s bits.  */
686       /* Shift r right by s bits.  */
687       if (s > 0)
688         {
689           mp_limb_t ptr = r_ptr + r_len;
690           mp_twolimb_t accu = 0;
691           size_t count;
692           for (count = r_len; count > 0; count--)
693             {
694               accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
695               accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
696               *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
697             }
698         }
699 # endif
700       /* Normalise r.  */
701       while (r_len > 0 && r_ptr[r_len - 1] == 0)
702         r_len--;
703     }
704   /* Compare r << 1 with b.  */
705   if (r_len > b_len)
706     goto increment_q;
707   {
708     size_t i;
709     for (i = b_len;;)
710       {
711         mp_limb_t r_i =
712           (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
713           | (i < r_len ? r_ptr[i] << 1 : 0);
714         mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
715         if (r_i > b_i)
716           goto increment_q;
717         if (r_i < b_i)
718           goto keep_q;
719         if (i == 0)
720           break;
721         i--;
722       }
723   }
724   if (q_len > 0 && ((q_ptr[0] & 1) != 0))
725     /* q is odd.  */
726     increment_q:
727     {
728       size_t i;
729       for (i = 0; i < q_len; i++)
730         if (++(q_ptr[i]) != 0)
731           goto keep_q;
732       q_ptr[q_len++] = 1;
733     }
734   keep_q:
735   if (tmp_roomptr != NULL)
736     free (tmp_roomptr);
737   q->limbs = q_ptr;
738   q->nlimbs = q_len;
739   return roomptr;
740 }
741
742 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
743    representation.
744    Destroys the contents of a.
745    Return the allocated memory - containing the decimal digits in low-to-high
746    order, terminated with a NUL character - in case of success, NULL in case
747    of memory allocation failure.  */
748 static char *
749 convert_to_decimal (mpn_t a, size_t extra_zeroes)
750 {
751   mp_limb_t *a_ptr = a.limbs;
752   size_t a_len = a.nlimbs;
753   /* 0.03345 is slightly larger than log(2)/(9*log(10)).  */
754   size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
755   char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
756   if (c_ptr != NULL)
757     {
758       char *d_ptr = c_ptr;
759       for (; extra_zeroes > 0; extra_zeroes--)
760         *d_ptr++ = '0';
761       while (a_len > 0)
762         {
763           /* Divide a by 10^9, in-place.  */
764           mp_limb_t remainder = 0;
765           mp_limb_t *ptr = a_ptr + a_len;
766           size_t count;
767           for (count = a_len; count > 0; count--)
768             {
769               mp_twolimb_t num =
770                 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
771               *ptr = num / 1000000000;
772               remainder = num % 1000000000;
773             }
774           /* Store the remainder as 9 decimal digits.  */
775           for (count = 9; count > 0; count--)
776             {
777               *d_ptr++ = '0' + (remainder % 10);
778               remainder = remainder / 10;
779             }
780           /* Normalize a.  */
781           if (a_ptr[a_len - 1] == 0)
782             a_len--;
783         }
784       /* Remove leading zeroes.  */
785       while (d_ptr > c_ptr && d_ptr[-1] == '0')
786         d_ptr--;
787       /* But keep at least one zero.  */
788       if (d_ptr == c_ptr)
789         *d_ptr++ = '0';
790       /* Terminate the string.  */
791       *d_ptr = '\0';
792     }
793   return c_ptr;
794 }
795
796 # if NEED_PRINTF_LONG_DOUBLE
797
798 /* Assuming x is finite and >= 0:
799    write x as x = 2^e * m, where m is a bignum.
800    Return the allocated memory in case of success, NULL in case of memory
801    allocation failure.  */
802 static void *
803 decode_long_double (long double x, int *ep, mpn_t *mp)
804 {
805   mpn_t m;
806   int exp;
807   long double y;
808   size_t i;
809
810   /* Allocate memory for result.  */
811   m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
812   m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
813   if (m.limbs == NULL)
814     return NULL;
815   /* Split into exponential part and mantissa.  */
816   y = frexpl (x, &exp);
817   if (!(y >= 0.0L && y < 1.0L))
818     abort ();
819   /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
820      latter is an integer.  */
821   /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
822      I'm not sure whether it's safe to cast a 'long double' value between
823      2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
824      'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
825      doesn't matter).  */
826 #  if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
827 #   if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
828     {
829       mp_limb_t hi, lo;
830       y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
831       hi = (int) y;
832       y -= hi;
833       if (!(y >= 0.0L && y < 1.0L))
834         abort ();
835       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
836       lo = (int) y;
837       y -= lo;
838       if (!(y >= 0.0L && y < 1.0L))
839         abort ();
840       m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
841     }
842 #   else
843     {
844       mp_limb_t d;
845       y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
846       d = (int) y;
847       y -= d;
848       if (!(y >= 0.0L && y < 1.0L))
849         abort ();
850       m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
851     }
852 #   endif
853 #  endif
854   for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
855     {
856       mp_limb_t hi, lo;
857       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
858       hi = (int) y;
859       y -= hi;
860       if (!(y >= 0.0L && y < 1.0L))
861         abort ();
862       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
863       lo = (int) y;
864       y -= lo;
865       if (!(y >= 0.0L && y < 1.0L))
866         abort ();
867       m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
868     }
869 #if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
870          precision.  */
871   if (!(y == 0.0L))
872     abort ();
873 #endif
874   /* Normalise.  */
875   while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
876     m.nlimbs--;
877   *mp = m;
878   *ep = exp - LDBL_MANT_BIT;
879   return m.limbs;
880 }
881
882 # endif
883
884 # if NEED_PRINTF_DOUBLE
885
886 /* Assuming x is finite and >= 0:
887    write x as x = 2^e * m, where m is a bignum.
888    Return the allocated memory in case of success, NULL in case of memory
889    allocation failure.  */
890 static void *
891 decode_double (double x, int *ep, mpn_t *mp)
892 {
893   mpn_t m;
894   int exp;
895   double y;
896   size_t i;
897
898   /* Allocate memory for result.  */
899   m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
900   m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
901   if (m.limbs == NULL)
902     return NULL;
903   /* Split into exponential part and mantissa.  */
904   y = frexp (x, &exp);
905   if (!(y >= 0.0 && y < 1.0))
906     abort ();
907   /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
908      latter is an integer.  */
909   /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
910      I'm not sure whether it's safe to cast a 'double' value between
911      2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
912      'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
913      doesn't matter).  */
914 #  if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
915 #   if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
916     {
917       mp_limb_t hi, lo;
918       y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
919       hi = (int) y;
920       y -= hi;
921       if (!(y >= 0.0 && y < 1.0))
922         abort ();
923       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
924       lo = (int) y;
925       y -= lo;
926       if (!(y >= 0.0 && y < 1.0))
927         abort ();
928       m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
929     }
930 #   else
931     {
932       mp_limb_t d;
933       y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
934       d = (int) y;
935       y -= d;
936       if (!(y >= 0.0 && y < 1.0))
937         abort ();
938       m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
939     }
940 #   endif
941 #  endif
942   for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
943     {
944       mp_limb_t hi, lo;
945       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
946       hi = (int) y;
947       y -= hi;
948       if (!(y >= 0.0 && y < 1.0))
949         abort ();
950       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
951       lo = (int) y;
952       y -= lo;
953       if (!(y >= 0.0 && y < 1.0))
954         abort ();
955       m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
956     }
957   if (!(y == 0.0))
958     abort ();
959   /* Normalise.  */
960   while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
961     m.nlimbs--;
962   *mp = m;
963   *ep = exp - DBL_MANT_BIT;
964   return m.limbs;
965 }
966
967 # endif
968
969 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
970    Returns the decimal representation of round (x * 10^n).
971    Return the allocated memory - containing the decimal digits in low-to-high
972    order, terminated with a NUL character - in case of success, NULL in case
973    of memory allocation failure.  */
974 static char *
975 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
976 {
977   int s;
978   size_t extra_zeroes;
979   unsigned int abs_n;
980   unsigned int abs_s;
981   mp_limb_t *pow5_ptr;
982   size_t pow5_len;
983   unsigned int s_limbs;
984   unsigned int s_bits;
985   mpn_t pow5;
986   mpn_t z;
987   void *z_memory;
988   char *digits;
989
990   if (memory == NULL)
991     return NULL;
992   /* x = 2^e * m, hence
993      y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
994        = round (2^s * 5^n * m).  */
995   s = e + n;
996   extra_zeroes = 0;
997   /* Factor out a common power of 10 if possible.  */
998   if (s > 0 && n > 0)
999     {
1000       extra_zeroes = (s < n ? s : n);
1001       s -= extra_zeroes;
1002       n -= extra_zeroes;
1003     }
1004   /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1005      Before converting to decimal, we need to compute
1006      z = round (2^s * 5^n * m).  */
1007   /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1008      sign.  2.322 is slightly larger than log(5)/log(2).  */
1009   abs_n = (n >= 0 ? n : -n);
1010   abs_s = (s >= 0 ? s : -s);
1011   pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1012                                     + abs_s / GMP_LIMB_BITS + 1)
1013                                    * sizeof (mp_limb_t));
1014   if (pow5_ptr == NULL)
1015     {
1016       free (memory);
1017       return NULL;
1018     }
1019   /* Initialize with 1.  */
1020   pow5_ptr[0] = 1;
1021   pow5_len = 1;
1022   /* Multiply with 5^|n|.  */
1023   if (abs_n > 0)
1024     {
1025       static mp_limb_t const small_pow5[13 + 1] =
1026         {
1027           1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1028           48828125, 244140625, 1220703125
1029         };
1030       unsigned int n13;
1031       for (n13 = 0; n13 <= abs_n; n13 += 13)
1032         {
1033           mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1034           size_t j;
1035           mp_twolimb_t carry = 0;
1036           for (j = 0; j < pow5_len; j++)
1037             {
1038               mp_limb_t digit2 = pow5_ptr[j];
1039               carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1040               pow5_ptr[j] = (mp_limb_t) carry;
1041               carry = carry >> GMP_LIMB_BITS;
1042             }
1043           if (carry > 0)
1044             pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1045         }
1046     }
1047   s_limbs = abs_s / GMP_LIMB_BITS;
1048   s_bits = abs_s % GMP_LIMB_BITS;
1049   if (n >= 0 ? s >= 0 : s <= 0)
1050     {
1051       /* Multiply with 2^|s|.  */
1052       if (s_bits > 0)
1053         {
1054           mp_limb_t *ptr = pow5_ptr;
1055           mp_twolimb_t accu = 0;
1056           size_t count;
1057           for (count = pow5_len; count > 0; count--)
1058             {
1059               accu += (mp_twolimb_t) *ptr << s_bits;
1060               *ptr++ = (mp_limb_t) accu;
1061               accu = accu >> GMP_LIMB_BITS;
1062             }
1063           if (accu > 0)
1064             {
1065               *ptr = (mp_limb_t) accu;
1066               pow5_len++;
1067             }
1068         }
1069       if (s_limbs > 0)
1070         {
1071           size_t count;
1072           for (count = pow5_len; count > 0;)
1073             {
1074               count--;
1075               pow5_ptr[s_limbs + count] = pow5_ptr[count];
1076             }
1077           for (count = s_limbs; count > 0;)
1078             {
1079               count--;
1080               pow5_ptr[count] = 0;
1081             }
1082           pow5_len += s_limbs;
1083         }
1084       pow5.limbs = pow5_ptr;
1085       pow5.nlimbs = pow5_len;
1086       if (n >= 0)
1087         {
1088           /* Multiply m with pow5.  No division needed.  */
1089           z_memory = multiply (m, pow5, &z);
1090         }
1091       else
1092         {
1093           /* Divide m by pow5 and round.  */
1094           z_memory = divide (m, pow5, &z);
1095         }
1096     }
1097   else
1098     {
1099       pow5.limbs = pow5_ptr;
1100       pow5.nlimbs = pow5_len;
1101       if (n >= 0)
1102         {
1103           /* n >= 0, s < 0.
1104              Multiply m with pow5, then divide by 2^|s|.  */
1105           mpn_t numerator;
1106           mpn_t denominator;
1107           void *tmp_memory;
1108           tmp_memory = multiply (m, pow5, &numerator);
1109           if (tmp_memory == NULL)
1110             {
1111               free (pow5_ptr);
1112               free (memory);
1113               return NULL;
1114             }
1115           /* Construct 2^|s|.  */
1116           {
1117             mp_limb_t *ptr = pow5_ptr + pow5_len;
1118             size_t i;
1119             for (i = 0; i < s_limbs; i++)
1120               ptr[i] = 0;
1121             ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1122             denominator.limbs = ptr;
1123             denominator.nlimbs = s_limbs + 1;
1124           }
1125           z_memory = divide (numerator, denominator, &z);
1126           free (tmp_memory);
1127         }
1128       else
1129         {
1130           /* n < 0, s > 0.
1131              Multiply m with 2^s, then divide by pow5.  */
1132           mpn_t numerator;
1133           mp_limb_t *num_ptr;
1134           num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1135                                           * sizeof (mp_limb_t));
1136           if (num_ptr == NULL)
1137             {
1138               free (pow5_ptr);
1139               free (memory);
1140               return NULL;
1141             }
1142           {
1143             mp_limb_t *destptr = num_ptr;
1144             {
1145               size_t i;
1146               for (i = 0; i < s_limbs; i++)
1147                 *destptr++ = 0;
1148             }
1149             if (s_bits > 0)
1150               {
1151                 const mp_limb_t *sourceptr = m.limbs;
1152                 mp_twolimb_t accu = 0;
1153                 size_t count;
1154                 for (count = m.nlimbs; count > 0; count--)
1155                   {
1156                     accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1157                     *destptr++ = (mp_limb_t) accu;
1158                     accu = accu >> GMP_LIMB_BITS;
1159                   }
1160                 if (accu > 0)
1161                   *destptr++ = (mp_limb_t) accu;
1162               }
1163             else
1164               {
1165                 const mp_limb_t *sourceptr = m.limbs;
1166                 size_t count;
1167                 for (count = m.nlimbs; count > 0; count--)
1168                   *destptr++ = *sourceptr++;
1169               }
1170             numerator.limbs = num_ptr;
1171             numerator.nlimbs = destptr - num_ptr;
1172           }
1173           z_memory = divide (numerator, pow5, &z);
1174           free (num_ptr);
1175         }
1176     }
1177   free (pow5_ptr);
1178   free (memory);
1179
1180   /* Here y = round (x * 10^n) = z * 10^extra_zeroes.  */
1181
1182   if (z_memory == NULL)
1183     return NULL;
1184   digits = convert_to_decimal (z, extra_zeroes);
1185   free (z_memory);
1186   return digits;
1187 }
1188
1189 # if NEED_PRINTF_LONG_DOUBLE
1190
1191 /* Assuming x is finite and >= 0, and n is an integer:
1192    Returns the decimal representation of round (x * 10^n).
1193    Return the allocated memory - containing the decimal digits in low-to-high
1194    order, terminated with a NUL character - in case of success, NULL in case
1195    of memory allocation failure.  */
1196 static char *
1197 scale10_round_decimal_long_double (long double x, int n)
1198 {
1199   int e;
1200   mpn_t m;
1201   void *memory = decode_long_double (x, &e, &m);
1202   return scale10_round_decimal_decoded (e, m, memory, n);
1203 }
1204
1205 # endif
1206
1207 # if NEED_PRINTF_DOUBLE
1208
1209 /* Assuming x is finite and >= 0, and n is an integer:
1210    Returns the decimal representation of round (x * 10^n).
1211    Return the allocated memory - containing the decimal digits in low-to-high
1212    order, terminated with a NUL character - in case of success, NULL in case
1213    of memory allocation failure.  */
1214 static char *
1215 scale10_round_decimal_double (double x, int n)
1216 {
1217   int e;
1218   mpn_t m;
1219   void *memory = decode_double (x, &e, &m);
1220   return scale10_round_decimal_decoded (e, m, memory, n);
1221 }
1222
1223 # endif
1224
1225 # if NEED_PRINTF_LONG_DOUBLE
1226
1227 /* Assuming x is finite and > 0:
1228    Return an approximation for n with 10^n <= x < 10^(n+1).
1229    The approximation is usually the right n, but may be off by 1 sometimes.  */
1230 static int
1231 floorlog10l (long double x)
1232 {
1233   int exp;
1234   long double y;
1235   double z;
1236   double l;
1237
1238   /* Split into exponential part and mantissa.  */
1239   y = frexpl (x, &exp);
1240   if (!(y >= 0.0L && y < 1.0L))
1241     abort ();
1242   if (y == 0.0L)
1243     return INT_MIN;
1244   if (y < 0.5L)
1245     {
1246       while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1247         {
1248           y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1249           exp -= GMP_LIMB_BITS;
1250         }
1251       if (y < (1.0L / (1 << 16)))
1252         {
1253           y *= 1.0L * (1 << 16);
1254           exp -= 16;
1255         }
1256       if (y < (1.0L / (1 << 8)))
1257         {
1258           y *= 1.0L * (1 << 8);
1259           exp -= 8;
1260         }
1261       if (y < (1.0L / (1 << 4)))
1262         {
1263           y *= 1.0L * (1 << 4);
1264           exp -= 4;
1265         }
1266       if (y < (1.0L / (1 << 2)))
1267         {
1268           y *= 1.0L * (1 << 2);
1269           exp -= 2;
1270         }
1271       if (y < (1.0L / (1 << 1)))
1272         {
1273           y *= 1.0L * (1 << 1);
1274           exp -= 1;
1275         }
1276     }
1277   if (!(y >= 0.5L && y < 1.0L))
1278     abort ();
1279   /* Compute an approximation for l = log2(x) = exp + log2(y).  */
1280   l = exp;
1281   z = y;
1282   if (z < 0.70710678118654752444)
1283     {
1284       z *= 1.4142135623730950488;
1285       l -= 0.5;
1286     }
1287   if (z < 0.8408964152537145431)
1288     {
1289       z *= 1.1892071150027210667;
1290       l -= 0.25;
1291     }
1292   if (z < 0.91700404320467123175)
1293     {
1294       z *= 1.0905077326652576592;
1295       l -= 0.125;
1296     }
1297   if (z < 0.9576032806985736469)
1298     {
1299       z *= 1.0442737824274138403;
1300       l -= 0.0625;
1301     }
1302   /* Now 0.95 <= z <= 1.01.  */
1303   z = 1 - z;
1304   /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1305      Four terms are enough to get an approximation with error < 10^-7.  */
1306   l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1307   /* Finally multiply with log(2)/log(10), yields an approximation for
1308      log10(x).  */
1309   l *= 0.30102999566398119523;
1310   /* Round down to the next integer.  */
1311   return (int) l + (l < 0 ? -1 : 0);
1312 }
1313
1314 # endif
1315
1316 # if NEED_PRINTF_DOUBLE
1317
1318 /* Assuming x is finite and > 0:
1319    Return an approximation for n with 10^n <= x < 10^(n+1).
1320    The approximation is usually the right n, but may be off by 1 sometimes.  */
1321 static int
1322 floorlog10 (double x)
1323 {
1324   int exp;
1325   double y;
1326   double z;
1327   double l;
1328
1329   /* Split into exponential part and mantissa.  */
1330   y = frexp (x, &exp);
1331   if (!(y >= 0.0 && y < 1.0))
1332     abort ();
1333   if (y == 0.0)
1334     return INT_MIN;
1335   if (y < 0.5)
1336     {
1337       while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1338         {
1339           y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1340           exp -= GMP_LIMB_BITS;
1341         }
1342       if (y < (1.0 / (1 << 16)))
1343         {
1344           y *= 1.0 * (1 << 16);
1345           exp -= 16;
1346         }
1347       if (y < (1.0 / (1 << 8)))
1348         {
1349           y *= 1.0 * (1 << 8);
1350           exp -= 8;
1351         }
1352       if (y < (1.0 / (1 << 4)))
1353         {
1354           y *= 1.0 * (1 << 4);
1355           exp -= 4;
1356         }
1357       if (y < (1.0 / (1 << 2)))
1358         {
1359           y *= 1.0 * (1 << 2);
1360           exp -= 2;
1361         }
1362       if (y < (1.0 / (1 << 1)))
1363         {
1364           y *= 1.0 * (1 << 1);
1365           exp -= 1;
1366         }
1367     }
1368   if (!(y >= 0.5 && y < 1.0))
1369     abort ();
1370   /* Compute an approximation for l = log2(x) = exp + log2(y).  */
1371   l = exp;
1372   z = y;
1373   if (z < 0.70710678118654752444)
1374     {
1375       z *= 1.4142135623730950488;
1376       l -= 0.5;
1377     }
1378   if (z < 0.8408964152537145431)
1379     {
1380       z *= 1.1892071150027210667;
1381       l -= 0.25;
1382     }
1383   if (z < 0.91700404320467123175)
1384     {
1385       z *= 1.0905077326652576592;
1386       l -= 0.125;
1387     }
1388   if (z < 0.9576032806985736469)
1389     {
1390       z *= 1.0442737824274138403;
1391       l -= 0.0625;
1392     }
1393   /* Now 0.95 <= z <= 1.01.  */
1394   z = 1 - z;
1395   /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1396      Four terms are enough to get an approximation with error < 10^-7.  */
1397   l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1398   /* Finally multiply with log(2)/log(10), yields an approximation for
1399      log10(x).  */
1400   l *= 0.30102999566398119523;
1401   /* Round down to the next integer.  */
1402   return (int) l + (l < 0 ? -1 : 0);
1403 }
1404
1405 # endif
1406
1407 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1408    a single '1' digit.  */
1409 static int
1410 is_borderline (const char *digits, size_t precision)
1411 {
1412   for (; precision > 0; precision--, digits++)
1413     if (*digits != '0')
1414       return 0;
1415   if (*digits != '1')
1416     return 0;
1417   digits++;
1418   return *digits == '\0';
1419 }
1420
1421 #endif
1422
1423 DCHAR_T *
1424 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1425             const FCHAR_T *format, va_list args)
1426 {
1427   DIRECTIVES d;
1428   arguments a;
1429
1430   if (PRINTF_PARSE (format, &d, &a) < 0)
1431     /* errno is already set.  */
1432     return NULL;
1433
1434 #define CLEANUP() \
1435   free (d.dir);                                                         \
1436   if (a.arg)                                                            \
1437     free (a.arg);
1438
1439   if (PRINTF_FETCHARGS (args, &a) < 0)
1440     {
1441       CLEANUP ();
1442       errno = EINVAL;
1443       return NULL;
1444     }
1445
1446   {
1447     size_t buf_neededlength;
1448     TCHAR_T *buf;
1449     TCHAR_T *buf_malloced;
1450     const FCHAR_T *cp;
1451     size_t i;
1452     DIRECTIVE *dp;
1453     /* Output string accumulator.  */
1454     DCHAR_T *result;
1455     size_t allocated;
1456     size_t length;
1457
1458     /* Allocate a small buffer that will hold a directive passed to
1459        sprintf or snprintf.  */
1460     buf_neededlength =
1461       xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1462 #if HAVE_ALLOCA
1463     if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1464       {
1465         buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1466         buf_malloced = NULL;
1467       }
1468     else
1469 #endif
1470       {
1471         size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1472         if (size_overflow_p (buf_memsize))
1473           goto out_of_memory_1;
1474         buf = (TCHAR_T *) malloc (buf_memsize);
1475         if (buf == NULL)
1476           goto out_of_memory_1;
1477         buf_malloced = buf;
1478       }
1479
1480     if (resultbuf != NULL)
1481       {
1482         result = resultbuf;
1483         allocated = *lengthp;
1484       }
1485     else
1486       {
1487         result = NULL;
1488         allocated = 0;
1489       }
1490     length = 0;
1491     /* Invariants:
1492        result is either == resultbuf or == NULL or malloc-allocated.
1493        If length > 0, then result != NULL.  */
1494
1495     /* Ensures that allocated >= needed.  Aborts through a jump to
1496        out_of_memory if needed is SIZE_MAX or otherwise too big.  */
1497 #define ENSURE_ALLOCATION(needed) \
1498     if ((needed) > allocated)                                                \
1499       {                                                                      \
1500         size_t memory_size;                                                  \
1501         DCHAR_T *memory;                                                     \
1502                                                                              \
1503         allocated = (allocated > 0 ? xtimes (allocated, 2) : 12);            \
1504         if ((needed) > allocated)                                            \
1505           allocated = (needed);                                              \
1506         memory_size = xtimes (allocated, sizeof (DCHAR_T));                  \
1507         if (size_overflow_p (memory_size))                                   \
1508           goto out_of_memory;                                                \
1509         if (result == resultbuf || result == NULL)                           \
1510           memory = (DCHAR_T *) malloc (memory_size);                         \
1511         else                                                                 \
1512           memory = (DCHAR_T *) realloc (result, memory_size);                \
1513         if (memory == NULL)                                                  \
1514           goto out_of_memory;                                                \
1515         if (result == resultbuf && length > 0)                               \
1516           DCHAR_CPY (memory, result, length);                                \
1517         result = memory;                                                     \
1518       }
1519
1520     for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1521       {
1522         if (cp != dp->dir_start)
1523           {
1524             size_t n = dp->dir_start - cp;
1525             size_t augmented_length = xsum (length, n);
1526
1527             ENSURE_ALLOCATION (augmented_length);
1528             /* This copies a piece of FCHAR_T[] into a DCHAR_T[].  Here we
1529                need that the format string contains only ASCII characters
1530                if FCHAR_T and DCHAR_T are not the same type.  */
1531             if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1532               {
1533                 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1534                 length = augmented_length;
1535               }
1536             else
1537               {
1538                 do
1539                   result[length++] = (unsigned char) *cp++;
1540                 while (--n > 0);
1541               }
1542           }
1543         if (i == d.count)
1544           break;
1545
1546         /* Execute a single directive.  */
1547         if (dp->conversion == '%')
1548           {
1549             size_t augmented_length;
1550
1551             if (!(dp->arg_index == ARG_NONE))
1552               abort ();
1553             augmented_length = xsum (length, 1);
1554             ENSURE_ALLOCATION (augmented_length);
1555             result[length] = '%';
1556             length = augmented_length;
1557           }
1558         else
1559           {
1560             if (!(dp->arg_index != ARG_NONE))
1561               abort ();
1562
1563             if (dp->conversion == 'n')
1564               {
1565                 switch (a.arg[dp->arg_index].type)
1566                   {
1567                   case TYPE_COUNT_SCHAR_POINTER:
1568                     *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1569                     break;
1570                   case TYPE_COUNT_SHORT_POINTER:
1571                     *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1572                     break;
1573                   case TYPE_COUNT_INT_POINTER:
1574                     *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1575                     break;
1576                   case TYPE_COUNT_LONGINT_POINTER:
1577                     *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1578                     break;
1579 #if HAVE_LONG_LONG_INT
1580                   case TYPE_COUNT_LONGLONGINT_POINTER:
1581                     *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1582                     break;
1583 #endif
1584                   default:
1585                     abort ();
1586                   }
1587               }
1588 #if ENABLE_UNISTDIO
1589             /* The unistdio extensions.  */
1590             else if (dp->conversion == 'U')
1591               {
1592                 arg_type type = a.arg[dp->arg_index].type;
1593                 int flags = dp->flags;
1594                 int has_width;
1595                 size_t width;
1596                 int has_precision;
1597                 size_t precision;
1598
1599                 has_width = 0;
1600                 width = 0;
1601                 if (dp->width_start != dp->width_end)
1602                   {
1603                     if (dp->width_arg_index != ARG_NONE)
1604                       {
1605                         int arg;
1606
1607                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1608                           abort ();
1609                         arg = a.arg[dp->width_arg_index].a.a_int;
1610                         if (arg < 0)
1611                           {
1612                             /* "A negative field width is taken as a '-' flag
1613                                 followed by a positive field width."  */
1614                             flags |= FLAG_LEFT;
1615                             width = (unsigned int) (-arg);
1616                           }
1617                         else
1618                           width = arg;
1619                       }
1620                     else
1621                       {
1622                         const FCHAR_T *digitp = dp->width_start;
1623
1624                         do
1625                           width = xsum (xtimes (width, 10), *digitp++ - '0');
1626                         while (digitp != dp->width_end);
1627                       }
1628                     has_width = 1;
1629                   }
1630
1631                 has_precision = 0;
1632                 precision = 0;
1633                 if (dp->precision_start != dp->precision_end)
1634                   {
1635                     if (dp->precision_arg_index != ARG_NONE)
1636                       {
1637                         int arg;
1638
1639                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1640                           abort ();
1641                         arg = a.arg[dp->precision_arg_index].a.a_int;
1642                         /* "A negative precision is taken as if the precision
1643                             were omitted."  */
1644                         if (arg >= 0)
1645                           {
1646                             precision = arg;
1647                             has_precision = 1;
1648                           }
1649                       }
1650                     else
1651                       {
1652                         const FCHAR_T *digitp = dp->precision_start + 1;
1653
1654                         precision = 0;
1655                         while (digitp != dp->precision_end)
1656                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1657                         has_precision = 1;
1658                       }
1659                   }
1660
1661                 switch (type)
1662                   {
1663                   case TYPE_U8_STRING:
1664                     {
1665                       const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1666                       const uint8_t *arg_end;
1667                       size_t characters;
1668
1669                       if (has_precision)
1670                         {
1671                           /* Use only PRECISION characters, from the left.  */
1672                           arg_end = arg;
1673                           characters = 0;
1674                           for (; precision > 0; precision--)
1675                             {
1676                               int count = u8_strmblen (arg_end);
1677                               if (count == 0)
1678                                 break;
1679                               if (count < 0)
1680                                 {
1681                                   if (!(result == resultbuf || result == NULL))
1682                                     free (result);
1683                                   if (buf_malloced != NULL)
1684                                     free (buf_malloced);
1685                                   CLEANUP ();
1686                                   errno = EILSEQ;
1687                                   return NULL;
1688                                 }
1689                               arg_end += count;
1690                               characters++;
1691                             }
1692                         }
1693                       else if (has_width)
1694                         {
1695                           /* Use the entire string, and count the number of
1696                              characters.  */
1697                           arg_end = arg;
1698                           characters = 0;
1699                           for (;;)
1700                             {
1701                               int count = u8_strmblen (arg_end);
1702                               if (count == 0)
1703                                 break;
1704                               if (count < 0)
1705                                 {
1706                                   if (!(result == resultbuf || result == NULL))
1707                                     free (result);
1708                                   if (buf_malloced != NULL)
1709                                     free (buf_malloced);
1710                                   CLEANUP ();
1711                                   errno = EILSEQ;
1712                                   return NULL;
1713                                 }
1714                               arg_end += count;
1715                               characters++;
1716                             }
1717                         }
1718                       else
1719                         {
1720                           /* Use the entire string.  */
1721                           arg_end = arg + u8_strlen (arg);
1722                           /* The number of characters doesn't matter.  */
1723                           characters = 0;
1724                         }
1725
1726                       if (has_width && width > characters
1727                           && !(dp->flags & FLAG_LEFT))
1728                         {
1729                           size_t n = width - characters;
1730                           ENSURE_ALLOCATION (xsum (length, n));
1731                           DCHAR_SET (result + length, ' ', n);
1732                           length += n;
1733                         }
1734
1735 # if DCHAR_IS_UINT8_T
1736                       {
1737                         size_t n = arg_end - arg;
1738                         ENSURE_ALLOCATION (xsum (length, n));
1739                         DCHAR_CPY (result + length, arg, n);
1740                         length += n;
1741                       }
1742 # else
1743                       { /* Convert.  */
1744                         DCHAR_T *converted = result + length;
1745                         size_t converted_len = allocated - length;
1746 #  if DCHAR_IS_TCHAR
1747                         /* Convert from UTF-8 to locale encoding.  */
1748                         if (u8_conv_to_encoding (locale_charset (),
1749                                                  iconveh_question_mark,
1750                                                  arg, arg_end - arg, NULL,
1751                                                  &converted, &converted_len)
1752                             < 0)
1753 #  else
1754                         /* Convert from UTF-8 to UTF-16/UTF-32.  */
1755                         converted =
1756                           U8_TO_DCHAR (arg, arg_end - arg,
1757                                        converted, &converted_len);
1758                         if (converted == NULL)
1759 #  endif
1760                           {
1761                             int saved_errno = errno;
1762                             if (!(result == resultbuf || result == NULL))
1763                               free (result);
1764                             if (buf_malloced != NULL)
1765                               free (buf_malloced);
1766                             CLEANUP ();
1767                             errno = saved_errno;
1768                             return NULL;
1769                           }
1770                         if (converted != result + length)
1771                           {
1772                             ENSURE_ALLOCATION (xsum (length, converted_len));
1773                             DCHAR_CPY (result + length, converted, converted_len);
1774                             free (converted);
1775                           }
1776                         length += converted_len;
1777                       }
1778 # endif
1779
1780                       if (has_width && width > characters
1781                           && (dp->flags & FLAG_LEFT))
1782                         {
1783                           size_t n = width - characters;
1784                           ENSURE_ALLOCATION (xsum (length, n));
1785                           DCHAR_SET (result + length, ' ', n);
1786                           length += n;
1787                         }
1788                     }
1789                     break;
1790
1791                   case TYPE_U16_STRING:
1792                     {
1793                       const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1794                       const uint16_t *arg_end;
1795                       size_t characters;
1796
1797                       if (has_precision)
1798                         {
1799                           /* Use only PRECISION characters, from the left.  */
1800                           arg_end = arg;
1801                           characters = 0;
1802                           for (; precision > 0; precision--)
1803                             {
1804                               int count = u16_strmblen (arg_end);
1805                               if (count == 0)
1806                                 break;
1807                               if (count < 0)
1808                                 {
1809                                   if (!(result == resultbuf || result == NULL))
1810                                     free (result);
1811                                   if (buf_malloced != NULL)
1812                                     free (buf_malloced);
1813                                   CLEANUP ();
1814                                   errno = EILSEQ;
1815                                   return NULL;
1816                                 }
1817                               arg_end += count;
1818                               characters++;
1819                             }
1820                         }
1821                       else if (has_width)
1822                         {
1823                           /* Use the entire string, and count the number of
1824                              characters.  */
1825                           arg_end = arg;
1826                           characters = 0;
1827                           for (;;)
1828                             {
1829                               int count = u16_strmblen (arg_end);
1830                               if (count == 0)
1831                                 break;
1832                               if (count < 0)
1833                                 {
1834                                   if (!(result == resultbuf || result == NULL))
1835                                     free (result);
1836                                   if (buf_malloced != NULL)
1837                                     free (buf_malloced);
1838                                   CLEANUP ();
1839                                   errno = EILSEQ;
1840                                   return NULL;
1841                                 }
1842                               arg_end += count;
1843                               characters++;
1844                             }
1845                         }
1846                       else
1847                         {
1848                           /* Use the entire string.  */
1849                           arg_end = arg + u16_strlen (arg);
1850                           /* The number of characters doesn't matter.  */
1851                           characters = 0;
1852                         }
1853
1854                       if (has_width && width > characters
1855                           && !(dp->flags & FLAG_LEFT))
1856                         {
1857                           size_t n = width - characters;
1858                           ENSURE_ALLOCATION (xsum (length, n));
1859                           DCHAR_SET (result + length, ' ', n);
1860                           length += n;
1861                         }
1862
1863 # if DCHAR_IS_UINT16_T
1864                       {
1865                         size_t n = arg_end - arg;
1866                         ENSURE_ALLOCATION (xsum (length, n));
1867                         DCHAR_CPY (result + length, arg, n);
1868                         length += n;
1869                       }
1870 # else
1871                       { /* Convert.  */
1872                         DCHAR_T *converted = result + length;
1873                         size_t converted_len = allocated - length;
1874 #  if DCHAR_IS_TCHAR
1875                         /* Convert from UTF-16 to locale encoding.  */
1876                         if (u16_conv_to_encoding (locale_charset (),
1877                                                   iconveh_question_mark,
1878                                                   arg, arg_end - arg, NULL,
1879                                                   &converted, &converted_len)
1880                             < 0)
1881 #  else
1882                         /* Convert from UTF-16 to UTF-8/UTF-32.  */
1883                         converted =
1884                           U16_TO_DCHAR (arg, arg_end - arg,
1885                                         converted, &converted_len);
1886                         if (converted == NULL)
1887 #  endif
1888                           {
1889                             int saved_errno = errno;
1890                             if (!(result == resultbuf || result == NULL))
1891                               free (result);
1892                             if (buf_malloced != NULL)
1893                               free (buf_malloced);
1894                             CLEANUP ();
1895                             errno = saved_errno;
1896                             return NULL;
1897                           }
1898                         if (converted != result + length)
1899                           {
1900                             ENSURE_ALLOCATION (xsum (length, converted_len));
1901                             DCHAR_CPY (result + length, converted, converted_len);
1902                             free (converted);
1903                           }
1904                         length += converted_len;
1905                       }
1906 # endif
1907
1908                       if (has_width && width > characters
1909                           && (dp->flags & FLAG_LEFT))
1910                         {
1911                           size_t n = width - characters;
1912                           ENSURE_ALLOCATION (xsum (length, n));
1913                           DCHAR_SET (result + length, ' ', n);
1914                           length += n;
1915                         }
1916                     }
1917                     break;
1918
1919                   case TYPE_U32_STRING:
1920                     {
1921                       const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1922                       const uint32_t *arg_end;
1923                       size_t characters;
1924
1925                       if (has_precision)
1926                         {
1927                           /* Use only PRECISION characters, from the left.  */
1928                           arg_end = arg;
1929                           characters = 0;
1930                           for (; precision > 0; precision--)
1931                             {
1932                               int count = u32_strmblen (arg_end);
1933                               if (count == 0)
1934                                 break;
1935                               if (count < 0)
1936                                 {
1937                                   if (!(result == resultbuf || result == NULL))
1938                                     free (result);
1939                                   if (buf_malloced != NULL)
1940                                     free (buf_malloced);
1941                                   CLEANUP ();
1942                                   errno = EILSEQ;
1943                                   return NULL;
1944                                 }
1945                               arg_end += count;
1946                               characters++;
1947                             }
1948                         }
1949                       else if (has_width)
1950                         {
1951                           /* Use the entire string, and count the number of
1952                              characters.  */
1953                           arg_end = arg;
1954                           characters = 0;
1955                           for (;;)
1956                             {
1957                               int count = u32_strmblen (arg_end);
1958                               if (count == 0)
1959                                 break;
1960                               if (count < 0)
1961                                 {
1962                                   if (!(result == resultbuf || result == NULL))
1963                                     free (result);
1964                                   if (buf_malloced != NULL)
1965                                     free (buf_malloced);
1966                                   CLEANUP ();
1967                                   errno = EILSEQ;
1968                                   return NULL;
1969                                 }
1970                               arg_end += count;
1971                               characters++;
1972                             }
1973                         }
1974                       else
1975                         {
1976                           /* Use the entire string.  */
1977                           arg_end = arg + u32_strlen (arg);
1978                           /* The number of characters doesn't matter.  */
1979                           characters = 0;
1980                         }
1981
1982                       if (has_width && width > characters
1983                           && !(dp->flags & FLAG_LEFT))
1984                         {
1985                           size_t n = width - characters;
1986                           ENSURE_ALLOCATION (xsum (length, n));
1987                           DCHAR_SET (result + length, ' ', n);
1988                           length += n;
1989                         }
1990
1991 # if DCHAR_IS_UINT32_T
1992                       {
1993                         size_t n = arg_end - arg;
1994                         ENSURE_ALLOCATION (xsum (length, n));
1995                         DCHAR_CPY (result + length, arg, n);
1996                         length += n;
1997                       }
1998 # else
1999                       { /* Convert.  */
2000                         DCHAR_T *converted = result + length;
2001                         size_t converted_len = allocated - length;
2002 #  if DCHAR_IS_TCHAR
2003                         /* Convert from UTF-32 to locale encoding.  */
2004                         if (u32_conv_to_encoding (locale_charset (),
2005                                                   iconveh_question_mark,
2006                                                   arg, arg_end - arg, NULL,
2007                                                   &converted, &converted_len)
2008                             < 0)
2009 #  else
2010                         /* Convert from UTF-32 to UTF-8/UTF-16.  */
2011                         converted =
2012                           U32_TO_DCHAR (arg, arg_end - arg,
2013                                         converted, &converted_len);
2014                         if (converted == NULL)
2015 #  endif
2016                           {
2017                             int saved_errno = errno;
2018                             if (!(result == resultbuf || result == NULL))
2019                               free (result);
2020                             if (buf_malloced != NULL)
2021                               free (buf_malloced);
2022                             CLEANUP ();
2023                             errno = saved_errno;
2024                             return NULL;
2025                           }
2026                         if (converted != result + length)
2027                           {
2028                             ENSURE_ALLOCATION (xsum (length, converted_len));
2029                             DCHAR_CPY (result + length, converted, converted_len);
2030                             free (converted);
2031                           }
2032                         length += converted_len;
2033                       }
2034 # endif
2035
2036                       if (has_width && width > characters
2037                           && (dp->flags & FLAG_LEFT))
2038                         {
2039                           size_t n = width - characters;
2040                           ENSURE_ALLOCATION (xsum (length, n));
2041                           DCHAR_SET (result + length, ' ', n);
2042                           length += n;
2043                         }
2044                     }
2045                     break;
2046
2047                   default:
2048                     abort ();
2049                   }
2050               }
2051 #endif
2052 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2053             else if ((dp->conversion == 'a' || dp->conversion == 'A')
2054 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2055                      && (0
2056 #  if NEED_PRINTF_DOUBLE
2057                          || a.arg[dp->arg_index].type == TYPE_DOUBLE
2058 #  endif
2059 #  if NEED_PRINTF_LONG_DOUBLE
2060                          || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2061 #  endif
2062                         )
2063 # endif
2064                     )
2065               {
2066                 arg_type type = a.arg[dp->arg_index].type;
2067                 int flags = dp->flags;
2068                 int has_width;
2069                 size_t width;
2070                 int has_precision;
2071                 size_t precision;
2072                 size_t tmp_length;
2073                 DCHAR_T tmpbuf[700];
2074                 DCHAR_T *tmp;
2075                 DCHAR_T *pad_ptr;
2076                 DCHAR_T *p;
2077
2078                 has_width = 0;
2079                 width = 0;
2080                 if (dp->width_start != dp->width_end)
2081                   {
2082                     if (dp->width_arg_index != ARG_NONE)
2083                       {
2084                         int arg;
2085
2086                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2087                           abort ();
2088                         arg = a.arg[dp->width_arg_index].a.a_int;
2089                         if (arg < 0)
2090                           {
2091                             /* "A negative field width is taken as a '-' flag
2092                                 followed by a positive field width."  */
2093                             flags |= FLAG_LEFT;
2094                             width = (unsigned int) (-arg);
2095                           }
2096                         else
2097                           width = arg;
2098                       }
2099                     else
2100                       {
2101                         const FCHAR_T *digitp = dp->width_start;
2102
2103                         do
2104                           width = xsum (xtimes (width, 10), *digitp++ - '0');
2105                         while (digitp != dp->width_end);
2106                       }
2107                     has_width = 1;
2108                   }
2109
2110                 has_precision = 0;
2111                 precision = 0;
2112                 if (dp->precision_start != dp->precision_end)
2113                   {
2114                     if (dp->precision_arg_index != ARG_NONE)
2115                       {
2116                         int arg;
2117
2118                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2119                           abort ();
2120                         arg = a.arg[dp->precision_arg_index].a.a_int;
2121                         /* "A negative precision is taken as if the precision
2122                             were omitted."  */
2123                         if (arg >= 0)
2124                           {
2125                             precision = arg;
2126                             has_precision = 1;
2127                           }
2128                       }
2129                     else
2130                       {
2131                         const FCHAR_T *digitp = dp->precision_start + 1;
2132
2133                         precision = 0;
2134                         while (digitp != dp->precision_end)
2135                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2136                         has_precision = 1;
2137                       }
2138                   }
2139
2140                 /* Allocate a temporary buffer of sufficient size.  */
2141                 if (type == TYPE_LONGDOUBLE)
2142                   tmp_length =
2143                     (unsigned int) ((LDBL_DIG + 1)
2144                                     * 0.831 /* decimal -> hexadecimal */
2145                                    )
2146                     + 1; /* turn floor into ceil */
2147                 else
2148                   tmp_length =
2149                     (unsigned int) ((DBL_DIG + 1)
2150                                     * 0.831 /* decimal -> hexadecimal */
2151                                    )
2152                     + 1; /* turn floor into ceil */
2153                 if (tmp_length < precision)
2154                   tmp_length = precision;
2155                 /* Account for sign, decimal point etc. */
2156                 tmp_length = xsum (tmp_length, 12);
2157
2158                 if (tmp_length < width)
2159                   tmp_length = width;
2160
2161                 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2162
2163                 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2164                   tmp = tmpbuf;
2165                 else
2166                   {
2167                     size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2168
2169                     if (size_overflow_p (tmp_memsize))
2170                       /* Overflow, would lead to out of memory.  */
2171                       goto out_of_memory;
2172                     tmp = (DCHAR_T *) malloc (tmp_memsize);
2173                     if (tmp == NULL)
2174                       /* Out of memory.  */
2175                       goto out_of_memory;
2176                   }
2177
2178                 pad_ptr = NULL;
2179                 p = tmp;
2180                 if (type == TYPE_LONGDOUBLE)
2181                   {
2182 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2183                     long double arg = a.arg[dp->arg_index].a.a_longdouble;
2184
2185                     if (isnanl (arg))
2186                       {
2187                         if (dp->conversion == 'A')
2188                           {
2189                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2190                           }
2191                         else
2192                           {
2193                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2194                           }
2195                       }
2196                     else
2197                       {
2198                         int sign = 0;
2199                         DECL_LONG_DOUBLE_ROUNDING
2200
2201                         BEGIN_LONG_DOUBLE_ROUNDING ();
2202
2203                         if (signbit (arg)) /* arg < 0.0L or negative zero */
2204                           {
2205                             sign = -1;
2206                             arg = -arg;
2207                           }
2208
2209                         if (sign < 0)
2210                           *p++ = '-';
2211                         else if (flags & FLAG_SHOWSIGN)
2212                           *p++ = '+';
2213                         else if (flags & FLAG_SPACE)
2214                           *p++ = ' ';
2215
2216                         if (arg > 0.0L && arg + arg == arg)
2217                           {
2218                             if (dp->conversion == 'A')
2219                               {
2220                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2221                               }
2222                             else
2223                               {
2224                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2225                               }
2226                           }
2227                         else
2228                           {
2229                             int exponent;
2230                             long double mantissa;
2231
2232                             if (arg > 0.0L)
2233                               mantissa = printf_frexpl (arg, &exponent);
2234                             else
2235                               {
2236                                 exponent = 0;
2237                                 mantissa = 0.0L;
2238                               }
2239
2240                             if (has_precision
2241                                 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2242                               {
2243                                 /* Round the mantissa.  */
2244                                 long double tail = mantissa;
2245                                 size_t q;
2246
2247                                 for (q = precision; ; q--)
2248                                   {
2249                                     int digit = (int) tail;
2250                                     tail -= digit;
2251                                     if (q == 0)
2252                                       {
2253                                         if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2254                                           tail = 1 - tail;
2255                                         else
2256                                           tail = - tail;
2257                                         break;
2258                                       }
2259                                     tail *= 16.0L;
2260                                   }
2261                                 if (tail != 0.0L)
2262                                   for (q = precision; q > 0; q--)
2263                                     tail *= 0.0625L;
2264                                 mantissa += tail;
2265                               }
2266
2267                             *p++ = '0';
2268                             *p++ = dp->conversion - 'A' + 'X';
2269                             pad_ptr = p;
2270                             {
2271                               int digit;
2272
2273                               digit = (int) mantissa;
2274                               mantissa -= digit;
2275                               *p++ = '0' + digit;
2276                               if ((flags & FLAG_ALT)
2277                                   || mantissa > 0.0L || precision > 0)
2278                                 {
2279                                   *p++ = decimal_point_char ();
2280                                   /* This loop terminates because we assume
2281                                      that FLT_RADIX is a power of 2.  */
2282                                   while (mantissa > 0.0L)
2283                                     {
2284                                       mantissa *= 16.0L;
2285                                       digit = (int) mantissa;
2286                                       mantissa -= digit;
2287                                       *p++ = digit
2288                                              + (digit < 10
2289                                                 ? '0'
2290                                                 : dp->conversion - 10);
2291                                       if (precision > 0)
2292                                         precision--;
2293                                     }
2294                                   while (precision > 0)
2295                                     {
2296                                       *p++ = '0';
2297                                       precision--;
2298                                     }
2299                                 }
2300                               }
2301                               *p++ = dp->conversion - 'A' + 'P';
2302 #  if WIDE_CHAR_VERSION
2303                               {
2304                                 static const wchar_t decimal_format[] =
2305                                   { '%', '+', 'd', '\0' };
2306                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2307                               }
2308                               while (*p != '\0')
2309                                 p++;
2310 #  else
2311                               if (sizeof (DCHAR_T) == 1)
2312                                 {
2313                                   sprintf ((char *) p, "%+d", exponent);
2314                                   while (*p != '\0')
2315                                     p++;
2316                                 }
2317                               else
2318                                 {
2319                                   char expbuf[6 + 1];
2320                                   const char *ep;
2321                                   sprintf (expbuf, "%+d", exponent);
2322                                   for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2323                                     p++;
2324                                 }
2325 #  endif
2326                           }
2327
2328                         END_LONG_DOUBLE_ROUNDING ();
2329                       }
2330 # else
2331                     abort ();
2332 # endif
2333                   }
2334                 else
2335                   {
2336 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2337                     double arg = a.arg[dp->arg_index].a.a_double;
2338
2339                     if (isnand (arg))
2340                       {
2341                         if (dp->conversion == 'A')
2342                           {
2343                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2344                           }
2345                         else
2346                           {
2347                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2348                           }
2349                       }
2350                     else
2351                       {
2352                         int sign = 0;
2353
2354                         if (signbit (arg)) /* arg < 0.0 or negative zero */
2355                           {
2356                             sign = -1;
2357                             arg = -arg;
2358                           }
2359
2360                         if (sign < 0)
2361                           *p++ = '-';
2362                         else if (flags & FLAG_SHOWSIGN)
2363                           *p++ = '+';
2364                         else if (flags & FLAG_SPACE)
2365                           *p++ = ' ';
2366
2367                         if (arg > 0.0 && arg + arg == arg)
2368                           {
2369                             if (dp->conversion == 'A')
2370                               {
2371                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2372                               }
2373                             else
2374                               {
2375                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2376                               }
2377                           }
2378                         else
2379                           {
2380                             int exponent;
2381                             double mantissa;
2382
2383                             if (arg > 0.0)
2384                               mantissa = printf_frexp (arg, &exponent);
2385                             else
2386                               {
2387                                 exponent = 0;
2388                                 mantissa = 0.0;
2389                               }
2390
2391                             if (has_precision
2392                                 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2393                               {
2394                                 /* Round the mantissa.  */
2395                                 double tail = mantissa;
2396                                 size_t q;
2397
2398                                 for (q = precision; ; q--)
2399                                   {
2400                                     int digit = (int) tail;
2401                                     tail -= digit;
2402                                     if (q == 0)
2403                                       {
2404                                         if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2405                                           tail = 1 - tail;
2406                                         else
2407                                           tail = - tail;
2408                                         break;
2409                                       }
2410                                     tail *= 16.0;
2411                                   }
2412                                 if (tail != 0.0)
2413                                   for (q = precision; q > 0; q--)
2414                                     tail *= 0.0625;
2415                                 mantissa += tail;
2416                               }
2417
2418                             *p++ = '0';
2419                             *p++ = dp->conversion - 'A' + 'X';
2420                             pad_ptr = p;
2421                             {
2422                               int digit;
2423
2424                               digit = (int) mantissa;
2425                               mantissa -= digit;
2426                               *p++ = '0' + digit;
2427                               if ((flags & FLAG_ALT)
2428                                   || mantissa > 0.0 || precision > 0)
2429                                 {
2430                                   *p++ = decimal_point_char ();
2431                                   /* This loop terminates because we assume
2432                                      that FLT_RADIX is a power of 2.  */
2433                                   while (mantissa > 0.0)
2434                                     {
2435                                       mantissa *= 16.0;
2436                                       digit = (int) mantissa;
2437                                       mantissa -= digit;
2438                                       *p++ = digit
2439                                              + (digit < 10
2440                                                 ? '0'
2441                                                 : dp->conversion - 10);
2442                                       if (precision > 0)
2443                                         precision--;
2444                                     }
2445                                   while (precision > 0)
2446                                     {
2447                                       *p++ = '0';
2448                                       precision--;
2449                                     }
2450                                 }
2451                               }
2452                               *p++ = dp->conversion - 'A' + 'P';
2453 #  if WIDE_CHAR_VERSION
2454                               {
2455                                 static const wchar_t decimal_format[] =
2456                                   { '%', '+', 'd', '\0' };
2457                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2458                               }
2459                               while (*p != '\0')
2460                                 p++;
2461 #  else
2462                               if (sizeof (DCHAR_T) == 1)
2463                                 {
2464                                   sprintf ((char *) p, "%+d", exponent);
2465                                   while (*p != '\0')
2466                                     p++;
2467                                 }
2468                               else
2469                                 {
2470                                   char expbuf[6 + 1];
2471                                   const char *ep;
2472                                   sprintf (expbuf, "%+d", exponent);
2473                                   for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2474                                     p++;
2475                                 }
2476 #  endif
2477                           }
2478                       }
2479 # else
2480                     abort ();
2481 # endif
2482                   }
2483                 /* The generated string now extends from tmp to p, with the
2484                    zero padding insertion point being at pad_ptr.  */
2485                 if (has_width && p - tmp < width)
2486                   {
2487                     size_t pad = width - (p - tmp);
2488                     DCHAR_T *end = p + pad;
2489
2490                     if (flags & FLAG_LEFT)
2491                       {
2492                         /* Pad with spaces on the right.  */
2493                         for (; pad > 0; pad--)
2494                           *p++ = ' ';
2495                       }
2496                     else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2497                       {
2498                         /* Pad with zeroes.  */
2499                         DCHAR_T *q = end;
2500
2501                         while (p > pad_ptr)
2502                           *--q = *--p;
2503                         for (; pad > 0; pad--)
2504                           *p++ = '0';
2505                       }
2506                     else
2507                       {
2508                         /* Pad with spaces on the left.  */
2509                         DCHAR_T *q = end;
2510
2511                         while (p > tmp)
2512                           *--q = *--p;
2513                         for (; pad > 0; pad--)
2514                           *p++ = ' ';
2515                       }
2516
2517                     p = end;
2518                   }
2519
2520                 {
2521                   size_t count = p - tmp;
2522
2523                   if (count >= tmp_length)
2524                     /* tmp_length was incorrectly calculated - fix the
2525                        code above!  */
2526                     abort ();
2527
2528                   /* Make room for the result.  */
2529                   if (count >= allocated - length)
2530                     {
2531                       size_t n = xsum (length, count);
2532
2533                       ENSURE_ALLOCATION (n);
2534                     }
2535
2536                   /* Append the result.  */
2537                   memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2538                   if (tmp != tmpbuf)
2539                     free (tmp);
2540                   length += count;
2541                 }
2542               }
2543 #endif
2544 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2545             else if ((dp->conversion == 'f' || dp->conversion == 'F'
2546                       || dp->conversion == 'e' || dp->conversion == 'E'
2547                       || dp->conversion == 'g' || dp->conversion == 'G'
2548                       || dp->conversion == 'a' || dp->conversion == 'A')
2549                      && (0
2550 # if NEED_PRINTF_DOUBLE
2551                          || a.arg[dp->arg_index].type == TYPE_DOUBLE
2552 # elif NEED_PRINTF_INFINITE_DOUBLE
2553                          || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2554                              /* The systems (mingw) which produce wrong output
2555                                 for Inf, -Inf, and NaN also do so for -0.0.
2556                                 Therefore we treat this case here as well.  */
2557                              && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2558 # endif
2559 # if NEED_PRINTF_LONG_DOUBLE
2560                          || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2561 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2562                          || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2563                              /* Some systems produce wrong output for Inf,
2564                                 -Inf, and NaN.  */
2565                              && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
2566 # endif
2567                         ))
2568               {
2569 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2570                 arg_type type = a.arg[dp->arg_index].type;
2571 # endif
2572                 int flags = dp->flags;
2573                 int has_width;
2574                 size_t width;
2575                 int has_precision;
2576                 size_t precision;
2577                 size_t tmp_length;
2578                 DCHAR_T tmpbuf[700];
2579                 DCHAR_T *tmp;
2580                 DCHAR_T *pad_ptr;
2581                 DCHAR_T *p;
2582
2583                 has_width = 0;
2584                 width = 0;
2585                 if (dp->width_start != dp->width_end)
2586                   {
2587                     if (dp->width_arg_index != ARG_NONE)
2588                       {
2589                         int arg;
2590
2591                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2592                           abort ();
2593                         arg = a.arg[dp->width_arg_index].a.a_int;
2594                         if (arg < 0)
2595                           {
2596                             /* "A negative field width is taken as a '-' flag
2597                                 followed by a positive field width."  */
2598                             flags |= FLAG_LEFT;
2599                             width = (unsigned int) (-arg);
2600                           }
2601                         else
2602                           width = arg;
2603                       }
2604                     else
2605                       {
2606                         const FCHAR_T *digitp = dp->width_start;
2607
2608                         do
2609                           width = xsum (xtimes (width, 10), *digitp++ - '0');
2610                         while (digitp != dp->width_end);
2611                       }
2612                     has_width = 1;
2613                   }
2614
2615                 has_precision = 0;
2616                 precision = 0;
2617                 if (dp->precision_start != dp->precision_end)
2618                   {
2619                     if (dp->precision_arg_index != ARG_NONE)
2620                       {
2621                         int arg;
2622
2623                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2624                           abort ();
2625                         arg = a.arg[dp->precision_arg_index].a.a_int;
2626                         /* "A negative precision is taken as if the precision
2627                             were omitted."  */
2628                         if (arg >= 0)
2629                           {
2630                             precision = arg;
2631                             has_precision = 1;
2632                           }
2633                       }
2634                     else
2635                       {
2636                         const FCHAR_T *digitp = dp->precision_start + 1;
2637
2638                         precision = 0;
2639                         while (digitp != dp->precision_end)
2640                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2641                         has_precision = 1;
2642                       }
2643                   }
2644
2645                 /* POSIX specifies the default precision to be 6 for %f, %F,
2646                    %e, %E, but not for %g, %G.  Implementations appear to use
2647                    the same default precision also for %g, %G.  */
2648                 if (!has_precision)
2649                   precision = 6;
2650
2651                 /* Allocate a temporary buffer of sufficient size.  */
2652 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2653                 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
2654 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2655                 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2656 # elif NEED_PRINTF_LONG_DOUBLE
2657                 tmp_length = LDBL_DIG + 1;
2658 # elif NEED_PRINTF_DOUBLE
2659                 tmp_length = DBL_DIG + 1;
2660 # else
2661                 tmp_length = 0;
2662 # endif
2663                 if (tmp_length < precision)
2664                   tmp_length = precision;
2665 # if NEED_PRINTF_LONG_DOUBLE
2666 #  if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2667                 if (type == TYPE_LONGDOUBLE)
2668 #  endif
2669                   if (dp->conversion == 'f' || dp->conversion == 'F')
2670                     {
2671                       long double arg = a.arg[dp->arg_index].a.a_longdouble;
2672                       if (!(isnanl (arg) || arg + arg == arg))
2673                         {
2674                           /* arg is finite and nonzero.  */
2675                           int exponent = floorlog10l (arg < 0 ? -arg : arg);
2676                           if (exponent >= 0 && tmp_length < exponent + precision)
2677                             tmp_length = exponent + precision;
2678                         }
2679                     }
2680 # endif
2681 # if NEED_PRINTF_DOUBLE
2682 #  if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2683                 if (type == TYPE_DOUBLE)
2684 #  endif
2685                   if (dp->conversion == 'f' || dp->conversion == 'F')
2686                     {
2687                       double arg = a.arg[dp->arg_index].a.a_double;
2688                       if (!(isnand (arg) || arg + arg == arg))
2689                         {
2690                           /* arg is finite and nonzero.  */
2691                           int exponent = floorlog10 (arg < 0 ? -arg : arg);
2692                           if (exponent >= 0 && tmp_length < exponent + precision)
2693                             tmp_length = exponent + precision;
2694                         }
2695                     }
2696 # endif
2697                 /* Account for sign, decimal point etc. */
2698                 tmp_length = xsum (tmp_length, 12);
2699
2700                 if (tmp_length < width)
2701                   tmp_length = width;
2702
2703                 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2704
2705                 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2706                   tmp = tmpbuf;
2707                 else
2708                   {
2709                     size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2710
2711                     if (size_overflow_p (tmp_memsize))
2712                       /* Overflow, would lead to out of memory.  */
2713                       goto out_of_memory;
2714                     tmp = (DCHAR_T *) malloc (tmp_memsize);
2715                     if (tmp == NULL)
2716                       /* Out of memory.  */
2717                       goto out_of_memory;
2718                   }
2719
2720                 pad_ptr = NULL;
2721                 p = tmp;
2722
2723 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2724 #  if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2725                 if (type == TYPE_LONGDOUBLE)
2726 #  endif
2727                   {
2728                     long double arg = a.arg[dp->arg_index].a.a_longdouble;
2729
2730                     if (isnanl (arg))
2731                       {
2732                         if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2733                           {
2734                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2735                           }
2736                         else
2737                           {
2738                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2739                           }
2740                       }
2741                     else
2742                       {
2743                         int sign = 0;
2744                         DECL_LONG_DOUBLE_ROUNDING
2745
2746                         BEGIN_LONG_DOUBLE_ROUNDING ();
2747
2748                         if (signbit (arg)) /* arg < 0.0L or negative zero */
2749                           {
2750                             sign = -1;
2751                             arg = -arg;
2752                           }
2753
2754                         if (sign < 0)
2755                           *p++ = '-';
2756                         else if (flags & FLAG_SHOWSIGN)
2757                           *p++ = '+';
2758                         else if (flags & FLAG_SPACE)
2759                           *p++ = ' ';
2760
2761                         if (arg > 0.0L && arg + arg == arg)
2762                           {
2763                             if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2764                               {
2765                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2766                               }
2767                             else
2768                               {
2769                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2770                               }
2771                           }
2772                         else
2773                           {
2774 #  if NEED_PRINTF_LONG_DOUBLE
2775                             pad_ptr = p;
2776
2777                             if (dp->conversion == 'f' || dp->conversion == 'F')
2778                               {
2779                                 char *digits;
2780                                 size_t ndigits;
2781
2782                                 digits =
2783                                   scale10_round_decimal_long_double (arg, precision);
2784                                 if (digits == NULL)
2785                                   {
2786                                     END_LONG_DOUBLE_ROUNDING ();
2787                                     goto out_of_memory;
2788                                   }
2789                                 ndigits = strlen (digits);
2790
2791                                 if (ndigits > precision)
2792                                   do
2793                                     {
2794                                       --ndigits;
2795                                       *p++ = digits[ndigits];
2796                                     }
2797                                   while (ndigits > precision);
2798                                 else
2799                                   *p++ = '0';
2800                                 /* Here ndigits <= precision.  */
2801                                 if ((flags & FLAG_ALT) || precision > 0)
2802                                   {
2803                                     *p++ = decimal_point_char ();
2804                                     for (; precision > ndigits; precision--)
2805                                       *p++ = '0';
2806                                     while (ndigits > 0)
2807                                       {
2808                                         --ndigits;
2809                                         *p++ = digits[ndigits];
2810                                       }
2811                                   }
2812
2813                                 free (digits);
2814                               }
2815                             else if (dp->conversion == 'e' || dp->conversion == 'E')
2816                               {
2817                                 int exponent;
2818
2819                                 if (arg == 0.0L)
2820                                   {
2821                                     exponent = 0;
2822                                     *p++ = '0';
2823                                     if ((flags & FLAG_ALT) || precision > 0)
2824                                       {
2825                                         *p++ = decimal_point_char ();
2826                                         for (; precision > 0; precision--)
2827                                           *p++ = '0';
2828                                       }
2829                                   }
2830                                 else
2831                                   {
2832                                     /* arg > 0.0L.  */
2833                                     int adjusted;
2834                                     char *digits;
2835                                     size_t ndigits;
2836
2837                                     exponent = floorlog10l (arg);
2838                                     adjusted = 0;
2839                                     for (;;)
2840                                       {
2841                                         digits =
2842                                           scale10_round_decimal_long_double (arg,
2843                                                                              (int)precision - exponent);
2844                                         if (digits == NULL)
2845                                           {
2846                                             END_LONG_DOUBLE_ROUNDING ();
2847                                             goto out_of_memory;
2848                                           }
2849                                         ndigits = strlen (digits);
2850
2851                                         if (ndigits == precision + 1)
2852                                           break;
2853                                         if (ndigits < precision
2854                                             || ndigits > precision + 2)
2855                                           /* The exponent was not guessed
2856                                              precisely enough.  */
2857                                           abort ();
2858                                         if (adjusted)
2859                                           /* None of two values of exponent is
2860                                              the right one.  Prevent an endless
2861                                              loop.  */
2862                                           abort ();
2863                                         free (digits);
2864                                         if (ndigits == precision)
2865                                           exponent -= 1;
2866                                         else
2867                                           exponent += 1;
2868                                         adjusted = 1;
2869                                       }
2870                                     /* Here ndigits = precision+1.  */
2871                                     if (is_borderline (digits, precision))
2872                                       {
2873                                         /* Maybe the exponent guess was too high
2874                                            and a smaller exponent can be reached
2875                                            by turning a 10...0 into 9...9x.  */
2876                                         char *digits2 =
2877                                           scale10_round_decimal_long_double (arg,
2878                                                                              (int)precision - exponent + 1);
2879                                         if (digits2 == NULL)
2880                                           {
2881                                             free (digits);
2882                                             END_LONG_DOUBLE_ROUNDING ();
2883                                             goto out_of_memory;
2884                                           }
2885                                         if (strlen (digits2) == precision + 1)
2886                                           {
2887                                             free (digits);
2888                                             digits = digits2;
2889                                             exponent -= 1;
2890                                           }
2891                                         else
2892                                           free (digits2);
2893                                       }
2894                                     /* Here ndigits = precision+1.  */
2895
2896                                     *p++ = digits[--ndigits];
2897                                     if ((flags & FLAG_ALT) || precision > 0)
2898                                       {
2899                                         *p++ = decimal_point_char ();
2900                                         while (ndigits > 0)
2901                                           {
2902                                             --ndigits;
2903                                             *p++ = digits[ndigits];
2904                                           }
2905                                       }
2906
2907                                     free (digits);
2908                                   }
2909
2910                                 *p++ = dp->conversion; /* 'e' or 'E' */
2911 #   if WIDE_CHAR_VERSION
2912                                 {
2913                                   static const wchar_t decimal_format[] =
2914                                     { '%', '+', '.', '2', 'd', '\0' };
2915                                   SNPRINTF (p, 6 + 1, decimal_format, exponent);
2916                                 }
2917                                 while (*p != '\0')
2918                                   p++;
2919 #   else
2920                                 if (sizeof (DCHAR_T) == 1)
2921                                   {
2922                                     sprintf ((char *) p, "%+.2d", exponent);
2923                                     while (*p != '\0')
2924                                       p++;
2925                                   }
2926                                 else
2927                                   {
2928                                     char expbuf[6 + 1];
2929                                     const char *ep;
2930                                     sprintf (expbuf, "%+.2d", exponent);
2931                                     for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2932                                       p++;
2933                                   }
2934 #   endif
2935                               }
2936                             else if (dp->conversion == 'g' || dp->conversion == 'G')
2937                               {
2938                                 if (precision == 0)
2939                                   precision = 1;
2940                                 /* precision >= 1.  */
2941
2942                                 if (arg == 0.0L)
2943                                   /* The exponent is 0, >= -4, < precision.
2944                                      Use fixed-point notation.  */
2945                                   {
2946                                     size_t ndigits = precision;
2947                                     /* Number of trailing zeroes that have to be
2948                                        dropped.  */
2949                                     size_t nzeroes =
2950                                       (flags & FLAG_ALT ? 0 : precision - 1);
2951
2952                                     --ndigits;
2953                                     *p++ = '0';
2954                                     if ((flags & FLAG_ALT) || ndigits > nzeroes)
2955                                       {
2956                                         *p++ = decimal_point_char ();
2957                                         while (ndigits > nzeroes)
2958                                           {
2959                                             --ndigits;
2960                                             *p++ = '0';
2961                                           }
2962                                       }
2963                                   }
2964                                 else
2965                                   {
2966                                     /* arg > 0.0L.  */
2967                                     int exponent;
2968                                     int adjusted;
2969                                     char *digits;
2970                                     size_t ndigits;
2971                                     size_t nzeroes;
2972
2973                                     exponent = floorlog10l (arg);
2974                                     adjusted = 0;
2975                                     for (;;)
2976                                       {
2977                                         digits =
2978                                           scale10_round_decimal_long_double (arg,
2979                                                                              (int)(precision - 1) - exponent);
2980                                         if (digits == NULL)
2981                                           {
2982                                             END_LONG_DOUBLE_ROUNDING ();
2983                                             goto out_of_memory;
2984                                           }
2985                                         ndigits = strlen (digits);
2986
2987                                         if (ndigits == precision)
2988                                           break;
2989                                         if (ndigits < precision - 1
2990                                             || ndigits > precision + 1)
2991                                           /* The exponent was not guessed
2992                                              precisely enough.  */
2993                                           abort ();
2994                                         if (adjusted)
2995                                           /* None of two values of exponent is
2996                                              the right one.  Prevent an endless
2997                                              loop.  */
2998                                           abort ();
2999                                         free (digits);
3000                                         if (ndigits < precision)
3001                                           exponent -= 1;
3002                                         else
3003                                           exponent += 1;
3004                                         adjusted = 1;
3005                                       }
3006                                     /* Here ndigits = precision.  */
3007                                     if (is_borderline (digits, precision - 1))
3008                                       {
3009                                         /* Maybe the exponent guess was too high
3010                                            and a smaller exponent can be reached
3011                                            by turning a 10...0 into 9...9x.  */
3012                                         char *digits2 =
3013                                           scale10_round_decimal_long_double (arg,
3014                                                                              (int)(precision - 1) - exponent + 1);
3015                                         if (digits2 == NULL)
3016                                           {
3017                                             free (digits);
3018                                             END_LONG_DOUBLE_ROUNDING ();
3019                                             goto out_of_memory;
3020                                           }
3021                                         if (strlen (digits2) == precision)
3022                                           {
3023                                             free (digits);
3024                                             digits = digits2;
3025                                             exponent -= 1;
3026                                           }
3027                                         else
3028                                           free (digits2);
3029                                       }
3030                                     /* Here ndigits = precision.  */
3031
3032                                     /* Determine the number of trailing zeroes
3033                                        that have to be dropped.  */
3034                                     nzeroes = 0;
3035                                     if ((flags & FLAG_ALT) == 0)
3036                                       while (nzeroes < ndigits
3037                                              && digits[nzeroes] == '0')
3038                                         nzeroes++;
3039
3040                                     /* The exponent is now determined.  */
3041                                     if (exponent >= -4
3042                                         && exponent < (long)precision)
3043                                       {
3044                                         /* Fixed-point notation:
3045                                            max(exponent,0)+1 digits, then the
3046                                            decimal point, then the remaining
3047                                            digits without trailing zeroes.  */
3048                                         if (exponent >= 0)
3049                                           {
3050                                             size_t count = exponent + 1;
3051                                             /* Note: count <= precision = ndigits.  */
3052                                             for (; count > 0; count--)
3053                                               *p++ = digits[--ndigits];
3054                                             if ((flags & FLAG_ALT) || ndigits > nzeroes)
3055                                               {
3056                                                 *p++ = decimal_point_char ();
3057                                                 while (ndigits > nzeroes)
3058                                                   {
3059                                                     --ndigits;
3060                                                     *p++ = digits[ndigits];
3061                                                   }
3062                                               }
3063                                           }
3064                                         else
3065                                           {
3066                                             size_t count = -exponent - 1;
3067                                             *p++ = '0';
3068                                             *p++ = decimal_point_char ();
3069                                             for (; count > 0; count--)
3070                                               *p++ = '0';
3071                                             while (ndigits > nzeroes)
3072                                               {
3073                                                 --ndigits;
3074                                                 *p++ = digits[ndigits];
3075                                               }
3076                                           }
3077                                       }
3078                                     else
3079                                       {
3080                                         /* Exponential notation.  */
3081                                         *p++ = digits[--ndigits];
3082                                         if ((flags & FLAG_ALT) || ndigits > nzeroes)
3083                                           {
3084                                             *p++ = decimal_point_char ();
3085                                             while (ndigits > nzeroes)
3086                                               {
3087                                                 --ndigits;
3088                                                 *p++ = digits[ndigits];
3089                                               }
3090                                           }
3091                                         *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3092 #   if WIDE_CHAR_VERSION
3093                                         {
3094                                           static const wchar_t decimal_format[] =
3095                                             { '%', '+', '.', '2', 'd', '\0' };
3096                                           SNPRINTF (p, 6 + 1, decimal_format, exponent);
3097                                         }
3098                                         while (*p != '\0')
3099                                           p++;
3100 #   else
3101                                         if (sizeof (DCHAR_T) == 1)
3102                                           {
3103                                             sprintf ((char *) p, "%+.2d", exponent);
3104                                             while (*p != '\0')
3105                                               p++;
3106                                           }
3107                                         else
3108                                           {
3109                                             char expbuf[6 + 1];
3110                                             const char *ep;
3111                                             sprintf (expbuf, "%+.2d", exponent);
3112                                             for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3113                                               p++;
3114                                           }
3115 #   endif
3116                                       }
3117
3118                                     free (digits);
3119                                   }
3120                               }
3121                             else
3122                               abort ();
3123 #  else
3124                             /* arg is finite.  */
3125                             abort ();
3126 #  endif
3127                           }
3128
3129                         END_LONG_DOUBLE_ROUNDING ();
3130                       }
3131                   }
3132 #  if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3133                 else
3134 #  endif
3135 # endif
3136 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3137                   {
3138                     double arg = a.arg[dp->arg_index].a.a_double;
3139
3140                     if (isnand (arg))
3141                       {
3142                         if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3143                           {
3144                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3145                           }
3146                         else
3147                           {
3148                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3149                           }
3150                       }
3151                     else
3152                       {
3153                         int sign = 0;
3154
3155                         if (signbit (arg)) /* arg < 0.0 or negative zero */
3156                           {
3157                             sign = -1;
3158                             arg = -arg;
3159                           }
3160
3161                         if (sign < 0)
3162                           *p++ = '-';
3163                         else if (flags & FLAG_SHOWSIGN)
3164                           *p++ = '+';
3165                         else if (flags & FLAG_SPACE)
3166                           *p++ = ' ';
3167
3168                         if (arg > 0.0 && arg + arg == arg)
3169                           {
3170                             if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3171                               {
3172                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3173                               }
3174                             else
3175                               {
3176                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3177                               }
3178                           }
3179                         else
3180                           {
3181 #  if NEED_PRINTF_DOUBLE
3182                             pad_ptr = p;
3183
3184                             if (dp->conversion == 'f' || dp->conversion == 'F')
3185                               {
3186                                 char *digits;
3187                                 size_t ndigits;
3188
3189                                 digits =
3190                                   scale10_round_decimal_double (arg, precision);
3191                                 if (digits == NULL)
3192                                   goto out_of_memory;
3193                                 ndigits = strlen (digits);
3194
3195                                 if (ndigits > precision)
3196                                   do
3197                                     {
3198                                       --ndigits;
3199                                       *p++ = digits[ndigits];
3200                                     }
3201                                   while (ndigits > precision);
3202                                 else
3203                                   *p++ = '0';
3204                                 /* Here ndigits <= precision.  */
3205                                 if ((flags & FLAG_ALT) || precision > 0)
3206                                   {
3207                                     *p++ = decimal_point_char ();
3208                                     for (; precision > ndigits; precision--)
3209                                       *p++ = '0';
3210                                     while (ndigits > 0)
3211                                       {
3212                                         --ndigits;
3213                                         *p++ = digits[ndigits];
3214                                       }
3215                                   }
3216
3217                                 free (digits);
3218                               }
3219                             else if (dp->conversion == 'e' || dp->conversion == 'E')
3220                               {
3221                                 int exponent;
3222
3223                                 if (arg == 0.0)
3224                                   {
3225                                     exponent = 0;
3226                                     *p++ = '0';
3227                                     if ((flags & FLAG_ALT) || precision > 0)
3228                                       {
3229                                         *p++ = decimal_point_char ();
3230                                         for (; precision > 0; precision--)
3231                                           *p++ = '0';
3232                                       }
3233                                   }
3234                                 else
3235                                   {
3236                                     /* arg > 0.0.  */
3237                                     int adjusted;
3238                                     char *digits;
3239                                     size_t ndigits;
3240
3241                                     exponent = floorlog10 (arg);
3242                                     adjusted = 0;
3243                                     for (;;)
3244                                       {
3245                                         digits =
3246                                           scale10_round_decimal_double (arg,
3247                                                                         (int)precision - exponent);
3248                                         if (digits == NULL)
3249                                           goto out_of_memory;
3250                                         ndigits = strlen (digits);
3251
3252                                         if (ndigits == precision + 1)
3253                                           break;
3254                                         if (ndigits < precision
3255                                             || ndigits > precision + 2)
3256                                           /* The exponent was not guessed
3257                                              precisely enough.  */
3258                                           abort ();
3259                                         if (adjusted)
3260                                           /* None of two values of exponent is
3261                                              the right one.  Prevent an endless
3262                                              loop.  */
3263                                           abort ();
3264                                         free (digits);
3265                                         if (ndigits == precision)
3266                                           exponent -= 1;
3267                                         else
3268                                           exponent += 1;
3269                                         adjusted = 1;
3270                                       }
3271                                     /* Here ndigits = precision+1.  */
3272                                     if (is_borderline (digits, precision))
3273                                       {
3274                                         /* Maybe the exponent guess was too high
3275                                            and a smaller exponent can be reached
3276                                            by turning a 10...0 into 9...9x.  */
3277                                         char *digits2 =
3278                                           scale10_round_decimal_double (arg,
3279                                                                         (int)precision - exponent + 1);
3280                                         if (digits2 == NULL)
3281                                           {
3282                                             free (digits);
3283                                             goto out_of_memory;
3284                                           }
3285                                         if (strlen (digits2) == precision + 1)
3286                                           {
3287                                             free (digits);
3288                                             digits = digits2;
3289                                             exponent -= 1;
3290                                           }
3291                                         else
3292                                           free (digits2);
3293                                       }
3294                                     /* Here ndigits = precision+1.  */
3295
3296                                     *p++ = digits[--ndigits];
3297                                     if ((flags & FLAG_ALT) || precision > 0)
3298                                       {
3299                                         *p++ = decimal_point_char ();
3300                                         while (ndigits > 0)
3301                                           {
3302                                             --ndigits;
3303                                             *p++ = digits[ndigits];
3304                                           }
3305                                       }
3306
3307                                     free (digits);
3308                                   }
3309
3310                                 *p++ = dp->conversion; /* 'e' or 'E' */
3311 #   if WIDE_CHAR_VERSION
3312                                 {
3313                                   static const wchar_t decimal_format[] =
3314                                     /* Produce the same number of exponent digits
3315                                        as the native printf implementation.  */
3316 #    if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3317                                     { '%', '+', '.', '3', 'd', '\0' };
3318 #    else
3319                                     { '%', '+', '.', '2', 'd', '\0' };
3320 #    endif
3321                                   SNPRINTF (p, 6 + 1, decimal_format, exponent);
3322                                 }
3323                                 while (*p != '\0')
3324                                   p++;
3325 #   else
3326                                 {
3327                                   static const char decimal_format[] =
3328                                     /* Produce the same number of exponent digits
3329                                        as the native printf implementation.  */
3330 #    if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3331                                     "%+.3d";
3332 #    else
3333                                     "%+.2d";
3334 #    endif
3335                                   if (sizeof (DCHAR_T) == 1)
3336                                     {
3337                                       sprintf ((char *) p, decimal_format, exponent);
3338                                       while (*p != '\0')
3339                                         p++;
3340                                     }
3341                                   else
3342                                     {
3343                                       char expbuf[6 + 1];
3344                                       const char *ep;
3345                                       sprintf (expbuf, decimal_format, exponent);
3346                                       for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3347                                         p++;
3348                                     }
3349                                 }
3350 #   endif
3351                               }
3352                             else if (dp->conversion == 'g' || dp->conversion == 'G')
3353                               {
3354                                 if (precision == 0)
3355                                   precision = 1;
3356                                 /* precision >= 1.  */
3357
3358                                 if (arg == 0.0)
3359                                   /* The exponent is 0, >= -4, < precision.
3360                                      Use fixed-point notation.  */
3361                                   {
3362                                     size_t ndigits = precision;
3363                                     /* Number of trailing zeroes that have to be
3364                                        dropped.  */
3365                                     size_t nzeroes =
3366                                       (flags & FLAG_ALT ? 0 : precision - 1);
3367
3368                                     --ndigits;
3369                                     *p++ = '0';
3370                                     if ((flags & FLAG_ALT) || ndigits > nzeroes)
3371                                       {
3372                                         *p++ = decimal_point_char ();
3373                                         while (ndigits > nzeroes)
3374                                           {
3375                                             --ndigits;
3376                                             *p++ = '0';
3377                                           }
3378                                       }
3379                                   }
3380                                 else
3381                                   {
3382                                     /* arg > 0.0.  */
3383                                     int exponent;
3384                                     int adjusted;
3385                                     char *digits;
3386                                     size_t ndigits;
3387                                     size_t nzeroes;
3388
3389                                     exponent = floorlog10 (arg);
3390                                     adjusted = 0;
3391                                     for (;;)
3392                                       {
3393                                         digits =
3394                                           scale10_round_decimal_double (arg,
3395                                                                         (int)(precision - 1) - exponent);
3396                                         if (digits == NULL)
3397                                           goto out_of_memory;
3398                                         ndigits = strlen (digits);
3399
3400                                         if (ndigits == precision)
3401                                           break;
3402                                         if (ndigits < precision - 1
3403                                             || ndigits > precision + 1)
3404                                           /* The exponent was not guessed
3405                                              precisely enough.  */
3406                                           abort ();
3407                                         if (adjusted)
3408                                           /* None of two values of exponent is
3409                                              the right one.  Prevent an endless
3410                                              loop.  */
3411                                           abort ();
3412                                         free (digits);
3413                                         if (ndigits < precision)
3414                                           exponent -= 1;
3415                                         else
3416                                           exponent += 1;
3417                                         adjusted = 1;
3418                                       }
3419                                     /* Here ndigits = precision.  */
3420                                     if (is_borderline (digits, precision - 1))
3421                                       {
3422                                         /* Maybe the exponent guess was too high
3423                                            and a smaller exponent can be reached
3424                                            by turning a 10...0 into 9...9x.  */
3425                                         char *digits2 =
3426                                           scale10_round_decimal_double (arg,
3427                                                                         (int)(precision - 1) - exponent + 1);
3428                                         if (digits2 == NULL)
3429                                           {
3430                                             free (digits);
3431                                             goto out_of_memory;
3432                                           }
3433                                         if (strlen (digits2) == precision)
3434                                           {
3435                                             free (digits);
3436                                             digits = digits2;
3437                                             exponent -= 1;
3438                                           }
3439                                         else
3440                                           free (digits2);
3441                                       }
3442                                     /* Here ndigits = precision.  */
3443
3444                                     /* Determine the number of trailing zeroes
3445                                        that have to be dropped.  */
3446                                     nzeroes = 0;
3447                                     if ((flags & FLAG_ALT) == 0)
3448                                       while (nzeroes < ndigits
3449                                              && digits[nzeroes] == '0')
3450                                         nzeroes++;
3451
3452                                     /* The exponent is now determined.  */
3453                                     if (exponent >= -4
3454                                         && exponent < (long)precision)
3455                                       {
3456                                         /* Fixed-point notation:
3457                                            max(exponent,0)+1 digits, then the
3458                                            decimal point, then the remaining
3459                                            digits without trailing zeroes.  */
3460                                         if (exponent >= 0)
3461                                           {
3462                                             size_t count = exponent + 1;
3463                                             /* Note: count <= precision = ndigits.  */
3464                                             for (; count > 0; count--)
3465                                               *p++ = digits[--ndigits];
3466                                             if ((flags & FLAG_ALT) || ndigits > nzeroes)
3467                                               {
3468                                                 *p++ = decimal_point_char ();
3469                                                 while (ndigits > nzeroes)
3470                                                   {
3471                                                     --ndigits;
3472                                                     *p++ = digits[ndigits];
3473                                                   }
3474                                               }
3475                                           }
3476                                         else
3477                                           {
3478                                             size_t count = -exponent - 1;
3479                                             *p++ = '0';
3480                                             *p++ = decimal_point_char ();
3481                                             for (; count > 0; count--)
3482                                               *p++ = '0';
3483                                             while (ndigits > nzeroes)
3484                                               {
3485                                                 --ndigits;
3486                                                 *p++ = digits[ndigits];
3487                                               }
3488                                           }
3489                                       }
3490                                     else
3491                                       {
3492                                         /* Exponential notation.  */
3493                                         *p++ = digits[--ndigits];
3494                                         if ((flags & FLAG_ALT) || ndigits > nzeroes)
3495                                           {
3496                                             *p++ = decimal_point_char ();
3497                                             while (ndigits > nzeroes)
3498                                               {
3499                                                 --ndigits;
3500                                                 *p++ = digits[ndigits];
3501                                               }
3502                                           }
3503                                         *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3504 #   if WIDE_CHAR_VERSION
3505                                         {
3506                                           static const wchar_t decimal_format[] =
3507                                             /* Produce the same number of exponent digits
3508                                                as the native printf implementation.  */
3509 #    if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3510                                             { '%', '+', '.', '3', 'd', '\0' };
3511 #    else
3512                                             { '%', '+', '.', '2', 'd', '\0' };
3513 #    endif
3514                                           SNPRINTF (p, 6 + 1, decimal_format, exponent);
3515                                         }
3516                                         while (*p != '\0')
3517                                           p++;
3518 #   else
3519                                         {
3520                                           static const char decimal_format[] =
3521                                             /* Produce the same number of exponent digits
3522                                                as the native printf implementation.  */
3523 #    if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3524                                             "%+.3d";
3525 #    else
3526                                             "%+.2d";
3527 #    endif
3528                                           if (sizeof (DCHAR_T) == 1)
3529                                             {
3530                                               sprintf ((char *) p, decimal_format, exponent);
3531                                               while (*p != '\0')
3532                                                 p++;
3533                                             }
3534                                           else
3535                                             {
3536                                               char expbuf[6 + 1];
3537                                               const char *ep;
3538                                               sprintf (expbuf, decimal_format, exponent);
3539                                               for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3540                                                 p++;
3541                                             }
3542                                         }
3543 #   endif
3544                                       }
3545
3546                                     free (digits);
3547                                   }
3548                               }
3549                             else
3550                               abort ();
3551 #  else
3552                             /* arg is finite.  */
3553                             if (!(arg == 0.0))
3554                               abort ();
3555
3556                             pad_ptr = p;
3557
3558                             if (dp->conversion == 'f' || dp->conversion == 'F')
3559                               {
3560                                 *p++ = '0';
3561                                 if ((flags & FLAG_ALT) || precision > 0)
3562                                   {
3563                                     *p++ = decimal_point_char ();
3564                                     for (; precision > 0; precision--)
3565                                       *p++ = '0';
3566                                   }
3567                               }
3568                             else if (dp->conversion == 'e' || dp->conversion == 'E')
3569                               {
3570                                 *p++ = '0';
3571                                 if ((flags & FLAG_ALT) || precision > 0)
3572                                   {
3573                                     *p++ = decimal_point_char ();
3574                                     for (; precision > 0; precision--)
3575                                       *p++ = '0';
3576                                   }
3577                                 *p++ = dp->conversion; /* 'e' or 'E' */
3578                                 *p++ = '+';
3579                                 /* Produce the same number of exponent digits as
3580                                    the native printf implementation.  */
3581 #   if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3582                                 *p++ = '0';
3583 #   endif
3584                                 *p++ = '0';
3585                                 *p++ = '0';
3586                               }
3587                             else if (dp->conversion == 'g' || dp->conversion == 'G')
3588                               {
3589                                 *p++ = '0';
3590                                 if (flags & FLAG_ALT)
3591                                   {
3592                                     size_t ndigits =
3593                                       (precision > 0 ? precision - 1 : 0);
3594                                     *p++ = decimal_point_char ();
3595                                     for (; ndigits > 0; --ndigits)
3596                                       *p++ = '0';
3597                                   }
3598                               }
3599                             else
3600                               abort ();
3601 #  endif
3602                           }
3603                       }
3604                   }
3605 # endif
3606
3607                 /* The generated string now extends from tmp to p, with the
3608                    zero padding insertion point being at pad_ptr.  */
3609                 if (has_width && p - tmp < width)
3610                   {
3611                     size_t pad = width - (p - tmp);
3612                     DCHAR_T *end = p + pad;
3613
3614                     if (flags & FLAG_LEFT)
3615                       {
3616                         /* Pad with spaces on the right.  */
3617                         for (; pad > 0; pad--)
3618                           *p++ = ' ';
3619                       }
3620                     else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3621                       {
3622                         /* Pad with zeroes.  */
3623                         DCHAR_T *q = end;
3624
3625                         while (p > pad_ptr)
3626                           *--q = *--p;
3627                         for (; pad > 0; pad--)
3628                           *p++ = '0';
3629                       }
3630                     else
3631                       {
3632                         /* Pad with spaces on the left.  */
3633                         DCHAR_T *q = end;
3634
3635                         while (p > tmp)
3636                           *--q = *--p;
3637                         for (; pad > 0; pad--)
3638                           *p++ = ' ';
3639                       }
3640
3641                     p = end;
3642                   }
3643
3644                 {
3645                   size_t count = p - tmp;
3646
3647                   if (count >= tmp_length)
3648                     /* tmp_length was incorrectly calculated - fix the
3649                        code above!  */
3650                     abort ();
3651
3652                   /* Make room for the result.  */
3653                   if (count >= allocated - length)
3654                     {
3655                       size_t n = xsum (length, count);
3656
3657                       ENSURE_ALLOCATION (n);
3658                     }
3659
3660                   /* Append the result.  */
3661                   memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3662                   if (tmp != tmpbuf)
3663                     free (tmp);
3664                   length += count;
3665                 }
3666               }
3667 #endif
3668             else
3669               {
3670                 arg_type type = a.arg[dp->arg_index].type;
3671                 int flags = dp->flags;
3672 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3673                 int has_width;
3674                 size_t width;
3675 #endif
3676 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3677                 int has_precision;
3678                 size_t precision;
3679 #endif
3680 #if NEED_PRINTF_UNBOUNDED_PRECISION
3681                 int prec_ourselves;
3682 #else
3683 #               define prec_ourselves 0
3684 #endif
3685 #if NEED_PRINTF_FLAG_LEFTADJUST
3686 #               define pad_ourselves 1
3687 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3688                 int pad_ourselves;
3689 #else
3690 #               define pad_ourselves 0
3691 #endif
3692                 TCHAR_T *fbp;
3693                 unsigned int prefix_count;
3694                 int prefixes[2];
3695 #if !USE_SNPRINTF
3696                 size_t tmp_length;
3697                 TCHAR_T tmpbuf[700];
3698                 TCHAR_T *tmp;
3699 #endif
3700
3701 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3702                 has_width = 0;
3703                 width = 0;
3704                 if (dp->width_start != dp->width_end)
3705                   {
3706                     if (dp->width_arg_index != ARG_NONE)
3707                       {
3708                         int arg;
3709
3710                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3711                           abort ();
3712                         arg = a.arg[dp->width_arg_index].a.a_int;
3713                         if (arg < 0)
3714                           {
3715                             /* "A negative field width is taken as a '-' flag
3716                                 followed by a positive field width."  */
3717                             flags |= FLAG_LEFT;
3718                             width = (unsigned int) (-arg);
3719                           }
3720                         else
3721                           width = arg;
3722                       }
3723                     else
3724                       {
3725                         const FCHAR_T *digitp = dp->width_start;
3726
3727                         do
3728                           width = xsum (xtimes (width, 10), *digitp++ - '0');
3729                         while (digitp != dp->width_end);
3730                       }
3731                     has_width = 1;
3732                   }
3733 #endif
3734
3735 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3736                 has_precision = 0;
3737                 precision = 6;
3738                 if (dp->precision_start != dp->precision_end)
3739                   {
3740                     if (dp->precision_arg_index != ARG_NONE)
3741                       {
3742                         int arg;
3743
3744                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3745                           abort ();
3746                         arg = a.arg[dp->precision_arg_index].a.a_int;
3747                         /* "A negative precision is taken as if the precision
3748                             were omitted."  */
3749                         if (arg >= 0)
3750                           {
3751                             precision = arg;
3752                             has_precision = 1;
3753                           }
3754                       }
3755                     else
3756                       {
3757                         const FCHAR_T *digitp = dp->precision_start + 1;
3758
3759                         precision = 0;
3760                         while (digitp != dp->precision_end)
3761                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3762                         has_precision = 1;
3763                       }
3764                   }
3765 #endif
3766
3767                 /* Decide whether to handle the precision ourselves.  */
3768 #if NEED_PRINTF_UNBOUNDED_PRECISION
3769                 switch (dp->conversion)
3770                   {
3771                   case 'd': case 'i': case 'u':
3772                   case 'o':
3773                   case 'x': case 'X': case 'p':
3774                     prec_ourselves = has_precision && (precision > 0);
3775                     break;
3776                   default:
3777                     prec_ourselves = 0;
3778                     break;
3779                   }
3780 #endif
3781
3782                 /* Decide whether to perform the padding ourselves.  */
3783 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
3784                 switch (dp->conversion)
3785                   {
3786 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
3787                   /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
3788                      to perform the padding after this conversion.  Functions
3789                      with unistdio extensions perform the padding based on
3790                      character count rather than element count.  */
3791                   case 'c': case 's':
3792 # endif
3793 # if NEED_PRINTF_FLAG_ZERO
3794                   case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
3795                   case 'a': case 'A':
3796 # endif
3797                     pad_ourselves = 1;
3798                     break;
3799                   default:
3800                     pad_ourselves = prec_ourselves;
3801                     break;
3802                   }
3803 #endif
3804
3805 #if !USE_SNPRINTF
3806                 /* Allocate a temporary buffer of sufficient size for calling
3807                    sprintf.  */
3808                 {
3809                   switch (dp->conversion)
3810                     {
3811
3812                     case 'd': case 'i': case 'u':
3813 # if HAVE_LONG_LONG_INT
3814                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3815                         tmp_length =
3816                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3817                                           * 0.30103 /* binary -> decimal */
3818                                          )
3819                           + 1; /* turn floor into ceil */
3820                       else
3821 # endif
3822                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3823                         tmp_length =
3824                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3825                                           * 0.30103 /* binary -> decimal */
3826                                          )
3827                           + 1; /* turn floor into ceil */
3828                       else
3829                         tmp_length =
3830                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3831                                           * 0.30103 /* binary -> decimal */
3832                                          )
3833                           + 1; /* turn floor into ceil */
3834                       if (tmp_length < precision)
3835                         tmp_length = precision;
3836                       /* Multiply by 2, as an estimate for FLAG_GROUP.  */
3837                       tmp_length = xsum (tmp_length, tmp_length);
3838                       /* Add 1, to account for a leading sign.  */
3839                       tmp_length = xsum (tmp_length, 1);
3840                       break;
3841
3842                     case 'o':
3843 # if HAVE_LONG_LONG_INT
3844                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3845                         tmp_length =
3846                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3847                                           * 0.333334 /* binary -> octal */
3848                                          )
3849                           + 1; /* turn floor into ceil */
3850                       else
3851 # endif
3852                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3853                         tmp_length =
3854                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3855                                           * 0.333334 /* binary -> octal */
3856                                          )
3857                           + 1; /* turn floor into ceil */
3858                       else
3859                         tmp_length =
3860                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3861                                           * 0.333334 /* binary -> octal */
3862                                          )
3863                           + 1; /* turn floor into ceil */
3864                       if (tmp_length < precision)
3865                         tmp_length = precision;
3866                       /* Add 1, to account for a leading sign.  */
3867                       tmp_length = xsum (tmp_length, 1);
3868                       break;
3869
3870                     case 'x': case 'X':
3871 # if HAVE_LONG_LONG_INT
3872                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3873                         tmp_length =
3874                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3875                                           * 0.25 /* binary -> hexadecimal */
3876                                          )
3877                           + 1; /* turn floor into ceil */
3878                       else
3879 # endif
3880                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3881                         tmp_length =
3882                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3883                                           * 0.25 /* binary -> hexadecimal */
3884                                          )
3885                           + 1; /* turn floor into ceil */
3886                       else
3887                         tmp_length =
3888                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3889                                           * 0.25 /* binary -> hexadecimal */
3890                                          )
3891                           + 1; /* turn floor into ceil */
3892                       if (tmp_length < precision)
3893                         tmp_length = precision;
3894                       /* Add 2, to account for a leading sign or alternate form.  */
3895                       tmp_length = xsum (tmp_length, 2);
3896                       break;
3897
3898                     case 'f': case 'F':
3899                       if (type == TYPE_LONGDOUBLE)
3900                         tmp_length =
3901                           (unsigned int) (LDBL_MAX_EXP
3902                                           * 0.30103 /* binary -> decimal */
3903                                           * 2 /* estimate for FLAG_GROUP */
3904                                          )
3905                           + 1 /* turn floor into ceil */
3906                           + 10; /* sign, decimal point etc. */
3907                       else
3908                         tmp_length =
3909                           (unsigned int) (DBL_MAX_EXP
3910                                           * 0.30103 /* binary -> decimal */
3911                                           * 2 /* estimate for FLAG_GROUP */
3912                                          )
3913                           + 1 /* turn floor into ceil */
3914                           + 10; /* sign, decimal point etc. */
3915                       tmp_length = xsum (tmp_length, precision);
3916                       break;
3917
3918                     case 'e': case 'E': case 'g': case 'G':
3919                       tmp_length =
3920                         12; /* sign, decimal point, exponent etc. */
3921                       tmp_length = xsum (tmp_length, precision);
3922                       break;
3923
3924                     case 'a': case 'A':
3925                       if (type == TYPE_LONGDOUBLE)
3926                         tmp_length =
3927                           (unsigned int) (LDBL_DIG
3928                                           * 0.831 /* decimal -> hexadecimal */
3929                                          )
3930                           + 1; /* turn floor into ceil */
3931                       else
3932                         tmp_length =
3933                           (unsigned int) (DBL_DIG
3934                                           * 0.831 /* decimal -> hexadecimal */
3935                                          )
3936                           + 1; /* turn floor into ceil */
3937                       if (tmp_length < precision)
3938                         tmp_length = precision;
3939                       /* Account for sign, decimal point etc. */
3940                       tmp_length = xsum (tmp_length, 12);
3941                       break;
3942
3943                     case 'c':
3944 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
3945                       if (type == TYPE_WIDE_CHAR)
3946                         tmp_length = MB_CUR_MAX;
3947                       else
3948 # endif
3949                         tmp_length = 1;
3950                       break;
3951
3952                     case 's':
3953 # if HAVE_WCHAR_T
3954                       if (type == TYPE_WIDE_STRING)
3955                         {
3956                           tmp_length =
3957                             local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
3958
3959 #  if !WIDE_CHAR_VERSION
3960                           tmp_length = xtimes (tmp_length, MB_CUR_MAX);
3961 #  endif
3962                         }
3963                       else
3964 # endif
3965                         tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
3966                       break;
3967
3968                     case 'p':
3969                       tmp_length =
3970                         (unsigned int) (sizeof (void *) * CHAR_BIT
3971                                         * 0.25 /* binary -> hexadecimal */
3972                                        )
3973                           + 1 /* turn floor into ceil */
3974                           + 2; /* account for leading 0x */
3975                       break;
3976
3977                     default:
3978                       abort ();
3979                     }
3980
3981                   if (!pad_ourselves)
3982                     {
3983 # if ENABLE_UNISTDIO
3984                       /* Padding considers the number of characters, therefore
3985                          the number of elements after padding may be
3986                            > max (tmp_length, width)
3987                          but is certainly
3988                            <= tmp_length + width.  */
3989                       tmp_length = xsum (tmp_length, width);
3990 # else
3991                       /* Padding considers the number of elements,
3992                          says POSIX.  */
3993                       if (tmp_length < width)
3994                         tmp_length = width;
3995 # endif
3996                     }
3997
3998                   tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3999                 }
4000
4001                 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4002                   tmp = tmpbuf;
4003                 else
4004                   {
4005                     size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4006
4007                     if (size_overflow_p (tmp_memsize))
4008                       /* Overflow, would lead to out of memory.  */
4009                       goto out_of_memory;
4010                     tmp = (TCHAR_T *) malloc (tmp_memsize);
4011                     if (tmp == NULL)
4012                       /* Out of memory.  */
4013                       goto out_of_memory;
4014                   }
4015 #endif
4016
4017                 /* Construct the format string for calling snprintf or
4018                    sprintf.  */
4019                 fbp = buf;
4020                 *fbp++ = '%';
4021 #if NEED_PRINTF_FLAG_GROUPING
4022                 /* The underlying implementation doesn't support the ' flag.
4023                    Produce no grouping characters in this case; this is
4024                    acceptable because the grouping is locale dependent.  */
4025 #else
4026                 if (flags & FLAG_GROUP)
4027                   *fbp++ = '\'';
4028 #endif
4029                 if (flags & FLAG_LEFT)
4030                   *fbp++ = '-';
4031                 if (flags & FLAG_SHOWSIGN)
4032                   *fbp++ = '+';
4033                 if (flags & FLAG_SPACE)
4034                   *fbp++ = ' ';
4035                 if (flags & FLAG_ALT)
4036                   *fbp++ = '#';
4037                 if (!pad_ourselves)
4038                   {
4039                     if (flags & FLAG_ZERO)
4040                       *fbp++ = '0';
4041                     if (dp->width_start != dp->width_end)
4042                       {
4043                         size_t n = dp->width_end - dp->width_start;
4044                         /* The width specification is known to consist only
4045                            of standard ASCII characters.  */
4046                         if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4047                           {
4048                             memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
4049                             fbp += n;
4050                           }
4051                         else
4052                           {
4053                             const FCHAR_T *mp = dp->width_start;
4054                             do
4055                               *fbp++ = (unsigned char) *mp++;
4056                             while (--n > 0);
4057                           }
4058                       }
4059                   }
4060                 if (!prec_ourselves)
4061                   {
4062                     if (dp->precision_start != dp->precision_end)
4063                       {
4064                         size_t n = dp->precision_end - dp->precision_start;
4065                         /* The precision specification is known to consist only
4066                            of standard ASCII characters.  */
4067                         if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
4068                           {
4069                             memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
4070                             fbp += n;
4071                           }
4072                         else
4073                           {
4074                             const FCHAR_T *mp = dp->precision_start;
4075                             do
4076                               *fbp++ = (unsigned char) *mp++;
4077                             while (--n > 0);
4078                           }
4079                       }
4080                   }
4081
4082                 switch (type)
4083                   {
4084 #if HAVE_LONG_LONG_INT
4085                   case TYPE_LONGLONGINT:
4086                   case TYPE_ULONGLONGINT:
4087 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
4088                     *fbp++ = 'I';
4089                     *fbp++ = '6';
4090                     *fbp++ = '4';
4091                     break;
4092 # else
4093                     *fbp++ = 'l';
4094                     /*FALLTHROUGH*/
4095 # endif
4096 #endif
4097                   case TYPE_LONGINT:
4098                   case TYPE_ULONGINT:
4099 #if HAVE_WINT_T
4100                   case TYPE_WIDE_CHAR:
4101 #endif
4102 #if HAVE_WCHAR_T
4103                   case TYPE_WIDE_STRING:
4104 #endif
4105                     *fbp++ = 'l';
4106                     break;
4107                   case TYPE_LONGDOUBLE:
4108                     *fbp++ = 'L';
4109                     break;
4110                   default:
4111                     break;
4112                   }
4113 #if NEED_PRINTF_DIRECTIVE_F
4114                 if (dp->conversion == 'F')
4115                   *fbp = 'f';
4116                 else
4117 #endif
4118                   *fbp = dp->conversion;
4119 #if USE_SNPRINTF
4120 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4121                 fbp[1] = '%';
4122                 fbp[2] = 'n';
4123                 fbp[3] = '\0';
4124 # else
4125                 /* On glibc2 systems from glibc >= 2.3 - probably also older
4126                    ones - we know that snprintf's returns value conforms to
4127                    ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4128                    Therefore we can avoid using %n in this situation.
4129                    On glibc2 systems from 2004-10-18 or newer, the use of %n
4130                    in format strings in writable memory may crash the program
4131                    (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4132                    in this situation.  */
4133                 /* On native Win32 systems (such as mingw), we can avoid using
4134                    %n because:
4135                      - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4136                        snprintf does not write more than the specified number
4137                        of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4138                        '4', '5', '6' into buf, not '4', '5', '\0'.)
4139                      - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4140                        allows us to recognize the case of an insufficient
4141                        buffer size: it returns -1 in this case.
4142                    On native Win32 systems (such as mingw) where the OS is
4143                    Windows Vista, the use of %n in format strings by default
4144                    crashes the program. See
4145                      <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4146                      <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4147                    So we should avoid %n in this situation.  */
4148                 fbp[1] = '\0';
4149 # endif
4150 #else
4151                 fbp[1] = '\0';
4152 #endif
4153
4154                 /* Construct the arguments for calling snprintf or sprintf.  */
4155                 prefix_count = 0;
4156                 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4157                   {
4158                     if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4159                       abort ();
4160                     prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4161                   }
4162                 if (dp->precision_arg_index != ARG_NONE)
4163                   {
4164                     if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4165                       abort ();
4166                     prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4167                   }
4168
4169 #if USE_SNPRINTF
4170                 /* The SNPRINTF result is appended after result[0..length].
4171                    The latter is an array of DCHAR_T; SNPRINTF appends an
4172                    array of TCHAR_T to it.  This is possible because
4173                    sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4174                    alignof (TCHAR_T) <= alignof (DCHAR_T).  */
4175 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4176                 /* Ensure that maxlen below will be >= 2.  Needed on BeOS,
4177                    where an snprintf() with maxlen==1 acts like sprintf().  */
4178                 ENSURE_ALLOCATION (xsum (length,
4179                                          (2 + TCHARS_PER_DCHAR - 1)
4180                                          / TCHARS_PER_DCHAR));
4181                 /* Prepare checking whether snprintf returns the count
4182                    via %n.  */
4183                 *(TCHAR_T *) (result + length) = '\0';
4184 #endif
4185
4186                 for (;;)
4187                   {
4188                     int count = -1;
4189
4190 #if USE_SNPRINTF
4191                     int retcount = 0;
4192                     size_t maxlen = allocated - length;
4193                     /* SNPRINTF can fail if its second argument is
4194                        > INT_MAX.  */
4195                     if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4196                       maxlen = INT_MAX / TCHARS_PER_DCHAR;
4197                     maxlen = maxlen * TCHARS_PER_DCHAR;
4198 # define SNPRINTF_BUF(arg) \
4199                     switch (prefix_count)                                   \
4200                       {                                                     \
4201                       case 0:                                               \
4202                         retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4203                                              maxlen, buf,                   \
4204                                              arg, &count);                  \
4205                         break;                                              \
4206                       case 1:                                               \
4207                         retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4208                                              maxlen, buf,                   \
4209                                              prefixes[0], arg, &count);     \
4210                         break;                                              \
4211                       case 2:                                               \
4212                         retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4213                                              maxlen, buf,                   \
4214                                              prefixes[0], prefixes[1], arg, \
4215                                              &count);                       \
4216                         break;                                              \
4217                       default:                                              \
4218                         abort ();                                           \
4219                       }
4220 #else
4221 # define SNPRINTF_BUF(arg) \
4222                     switch (prefix_count)                                   \
4223                       {                                                     \
4224                       case 0:                                               \
4225                         count = sprintf (tmp, buf, arg);                    \
4226                         break;                                              \
4227                       case 1:                                               \
4228                         count = sprintf (tmp, buf, prefixes[0], arg);       \
4229                         break;                                              \
4230                       case 2:                                               \
4231                         count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4232                                          arg);                              \
4233                         break;                                              \
4234                       default:                                              \
4235                         abort ();                                           \
4236                       }
4237 #endif
4238
4239                     switch (type)
4240                       {
4241                       case TYPE_SCHAR:
4242                         {
4243                           int arg = a.arg[dp->arg_index].a.a_schar;
4244                           SNPRINTF_BUF (arg);
4245                         }
4246                         break;
4247                       case TYPE_UCHAR:
4248                         {
4249                           unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4250                           SNPRINTF_BUF (arg);
4251                         }
4252                         break;
4253                       case TYPE_SHORT:
4254                         {
4255                           int arg = a.arg[dp->arg_index].a.a_short;
4256                           SNPRINTF_BUF (arg);
4257                         }
4258                         break;
4259                       case TYPE_USHORT:
4260                         {
4261                           unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4262                           SNPRINTF_BUF (arg);
4263                         }
4264                         break;
4265                       case TYPE_INT:
4266                         {
4267                           int arg = a.arg[dp->arg_index].a.a_int;
4268                           SNPRINTF_BUF (arg);
4269                         }
4270                         break;
4271                       case TYPE_UINT:
4272                         {
4273                           unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4274                           SNPRINTF_BUF (arg);
4275                         }
4276                         break;
4277                       case TYPE_LONGINT:
4278                         {
4279                           long int arg = a.arg[dp->arg_index].a.a_longint;
4280                           SNPRINTF_BUF (arg);
4281                         }
4282                         break;
4283                       case TYPE_ULONGINT:
4284                         {
4285                           unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4286                           SNPRINTF_BUF (arg);
4287                         }
4288                         break;
4289 #if HAVE_LONG_LONG_INT
4290                       case TYPE_LONGLONGINT:
4291                         {
4292                           long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4293                           SNPRINTF_BUF (arg);
4294                         }
4295                         break;
4296                       case TYPE_ULONGLONGINT:
4297                         {
4298                           unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4299                           SNPRINTF_BUF (arg);
4300                         }
4301                         break;
4302 #endif
4303                       case TYPE_DOUBLE:
4304                         {
4305                           double arg = a.arg[dp->arg_index].a.a_double;
4306                           SNPRINTF_BUF (arg);
4307                         }
4308                         break;
4309                       case TYPE_LONGDOUBLE:
4310                         {
4311                           long double arg = a.arg[dp->arg_index].a.a_longdouble;
4312                           SNPRINTF_BUF (arg);
4313                         }
4314                         break;
4315                       case TYPE_CHAR:
4316                         {
4317                           int arg = a.arg[dp->arg_index].a.a_char;
4318                           SNPRINTF_BUF (arg);
4319                         }
4320                         break;
4321 #if HAVE_WINT_T
4322                       case TYPE_WIDE_CHAR:
4323                         {
4324                           wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
4325                           SNPRINTF_BUF (arg);
4326                         }
4327                         break;
4328 #endif
4329                       case TYPE_STRING:
4330                         {
4331                           const char *arg = a.arg[dp->arg_index].a.a_string;
4332                           SNPRINTF_BUF (arg);
4333                         }
4334                         break;
4335 #if HAVE_WCHAR_T
4336                       case TYPE_WIDE_STRING:
4337                         {
4338                           const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
4339                           SNPRINTF_BUF (arg);
4340                         }
4341                         break;
4342 #endif
4343                       case TYPE_POINTER:
4344                         {
4345                           void *arg = a.arg[dp->arg_index].a.a_pointer;
4346                           SNPRINTF_BUF (arg);
4347                         }
4348                         break;
4349                       default:
4350                         abort ();
4351                       }
4352
4353 #if USE_SNPRINTF
4354                     /* Portability: Not all implementations of snprintf()
4355                        are ISO C 99 compliant.  Determine the number of
4356                        bytes that snprintf() has produced or would have
4357                        produced.  */
4358                     if (count >= 0)
4359                       {
4360                         /* Verify that snprintf() has NUL-terminated its
4361                            result.  */
4362                         if (count < maxlen
4363                             && ((TCHAR_T *) (result + length)) [count] != '\0')
4364                           abort ();
4365                         /* Portability hack.  */
4366                         if (retcount > count)
4367                           count = retcount;
4368                       }
4369                     else
4370                       {
4371                         /* snprintf() doesn't understand the '%n'
4372                            directive.  */
4373                         if (fbp[1] != '\0')
4374                           {
4375                             /* Don't use the '%n' directive; instead, look
4376                                at the snprintf() return value.  */
4377                             fbp[1] = '\0';
4378                             continue;
4379                           }
4380                         else
4381                           {
4382                             /* Look at the snprintf() return value.  */
4383                             if (retcount < 0)
4384                               {
4385                                 /* HP-UX 10.20 snprintf() is doubly deficient:
4386                                    It doesn't understand the '%n' directive,
4387                                    *and* it returns -1 (rather than the length
4388                                    that would have been required) when the
4389                                    buffer is too small.  */
4390                                 size_t bigger_need =
4391                                   xsum (xtimes (allocated, 2), 12);
4392                                 ENSURE_ALLOCATION (bigger_need);
4393                                 continue;
4394                               }
4395                             else
4396                               count = retcount;
4397                           }
4398                       }
4399 #endif
4400
4401                     /* Attempt to handle failure.  */
4402                     if (count < 0)
4403                       {
4404                         if (!(result == resultbuf || result == NULL))
4405                           free (result);
4406                         if (buf_malloced != NULL)
4407                           free (buf_malloced);
4408                         CLEANUP ();
4409                         errno = EINVAL;
4410                         return NULL;
4411                       }
4412
4413 #if USE_SNPRINTF
4414                     /* Handle overflow of the allocated buffer.
4415                        If such an overflow occurs, a C99 compliant snprintf()
4416                        returns a count >= maxlen.  However, a non-compliant
4417                        snprintf() function returns only count = maxlen - 1.  To
4418                        cover both cases, test whether count >= maxlen - 1.  */
4419                     if ((unsigned int) count + 1 >= maxlen)
4420                       {
4421                         /* If maxlen already has attained its allowed maximum,
4422                            allocating more memory will not increase maxlen.
4423                            Instead of looping, bail out.  */
4424                         if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
4425                           goto overflow;
4426                         else
4427                           {
4428                             /* Need at least (count + 1) * sizeof (TCHAR_T)
4429                                bytes.  (The +1 is for the trailing NUL.)
4430                                But ask for (count + 2) * sizeof (TCHAR_T)
4431                                bytes, so that in the next round, we likely get
4432                                  maxlen > (unsigned int) count + 1
4433                                and so we don't get here again.
4434                                And allocate proportionally, to avoid looping
4435                                eternally if snprintf() reports a too small
4436                                count.  */
4437                             size_t n =
4438                               xmax (xsum (length,
4439                                           ((unsigned int) count + 2
4440                                            + TCHARS_PER_DCHAR - 1)
4441                                           / TCHARS_PER_DCHAR),
4442                                     xtimes (allocated, 2));
4443
4444                             ENSURE_ALLOCATION (n);
4445                             continue;
4446                           }
4447                       }
4448 #endif
4449
4450 #if NEED_PRINTF_UNBOUNDED_PRECISION
4451                     if (prec_ourselves)
4452                       {
4453                         /* Handle the precision.  */
4454                         TCHAR_T *prec_ptr =
4455 # if USE_SNPRINTF
4456                           (TCHAR_T *) (result + length);
4457 # else
4458                           tmp;
4459 # endif
4460                         size_t prefix_count;
4461                         size_t move;
4462
4463                         prefix_count = 0;
4464                         /* Put the additional zeroes after the sign.  */
4465                         if (count >= 1
4466                             && (*prec_ptr == '-' || *prec_ptr == '+'
4467                                 || *prec_ptr == ' '))
4468                           prefix_count = 1;
4469                         /* Put the additional zeroes after the 0x prefix if
4470                            (flags & FLAG_ALT) || (dp->conversion == 'p').  */
4471                         else if (count >= 2
4472                                  && prec_ptr[0] == '0'
4473                                  && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
4474                           prefix_count = 2;
4475
4476                         move = count - prefix_count;
4477                         if (precision > move)
4478                           {
4479                             /* Insert zeroes.  */
4480                             size_t insert = precision - move;
4481                             TCHAR_T *prec_end;
4482
4483 # if USE_SNPRINTF
4484                             size_t n =
4485                               xsum (length,
4486                                     (count + insert + TCHARS_PER_DCHAR - 1)
4487                                     / TCHARS_PER_DCHAR);
4488                             length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4489                             ENSURE_ALLOCATION (n);
4490                             length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4491                             prec_ptr = (TCHAR_T *) (result + length);
4492 # endif
4493
4494                             prec_end = prec_ptr + count;
4495                             prec_ptr += prefix_count;
4496
4497                             while (prec_end > prec_ptr)
4498                               {
4499                                 prec_end--;
4500                                 prec_end[insert] = prec_end[0];
4501                               }
4502
4503                             prec_end += insert;
4504                             do
4505                               *--prec_end = '0';
4506                             while (prec_end > prec_ptr);
4507
4508                             count += insert;
4509                           }
4510                       }
4511 #endif
4512
4513 #if !USE_SNPRINTF
4514                     if (count >= tmp_length)
4515                       /* tmp_length was incorrectly calculated - fix the
4516                          code above!  */
4517                       abort ();
4518 #endif
4519
4520 #if !DCHAR_IS_TCHAR
4521                     /* Convert from TCHAR_T[] to DCHAR_T[].  */
4522                     if (dp->conversion == 'c' || dp->conversion == 's')
4523                       {
4524                         /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
4525                            TYPE_WIDE_STRING.
4526                            The result string is not certainly ASCII.  */
4527                         const TCHAR_T *tmpsrc;
4528                         DCHAR_T *tmpdst;
4529                         size_t tmpdst_len;
4530                         /* This code assumes that TCHAR_T is 'char'.  */
4531                         typedef int TCHAR_T_verify
4532                                     [2 * (sizeof (TCHAR_T) == 1) - 1];
4533 # if USE_SNPRINTF
4534                         tmpsrc = (TCHAR_T *) (result + length);
4535 # else
4536                         tmpsrc = tmp;
4537 # endif
4538                         tmpdst = NULL;
4539                         tmpdst_len = 0;
4540                         if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
4541                                                       iconveh_question_mark,
4542                                                       tmpsrc, count,
4543                                                       NULL,
4544                                                       &tmpdst, &tmpdst_len)
4545                             < 0)
4546                           {
4547                             int saved_errno = errno;
4548                             if (!(result == resultbuf || result == NULL))
4549                               free (result);
4550                             if (buf_malloced != NULL)
4551                               free (buf_malloced);
4552                             CLEANUP ();
4553                             errno = saved_errno;
4554                             return NULL;
4555                           }
4556                         ENSURE_ALLOCATION (xsum (length, tmpdst_len));
4557                         DCHAR_CPY (result + length, tmpdst, tmpdst_len);
4558                         free (tmpdst);
4559                         count = tmpdst_len;
4560                       }
4561                     else
4562                       {
4563                         /* The result string is ASCII.
4564                            Simple 1:1 conversion.  */
4565 # if USE_SNPRINTF
4566                         /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
4567                            no-op conversion, in-place on the array starting
4568                            at (result + length).  */
4569                         if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
4570 # endif
4571                           {
4572                             const TCHAR_T *tmpsrc;
4573                             DCHAR_T *tmpdst;
4574                             size_t n;
4575
4576 # if USE_SNPRINTF
4577                             if (result == resultbuf)
4578                               {
4579                                 tmpsrc = (TCHAR_T *) (result + length);
4580                                 /* ENSURE_ALLOCATION will not move tmpsrc
4581                                    (because it's part of resultbuf).  */
4582                                 ENSURE_ALLOCATION (xsum (length, count));
4583                               }
4584                             else
4585                               {
4586                                 /* ENSURE_ALLOCATION will move the array
4587                                    (because it uses realloc().  */
4588                                 ENSURE_ALLOCATION (xsum (length, count));
4589                                 tmpsrc = (TCHAR_T *) (result + length);
4590                               }
4591 # else
4592                             tmpsrc = tmp;
4593                             ENSURE_ALLOCATION (xsum (length, count));
4594 # endif
4595                             tmpdst = result + length;
4596                             /* Copy backwards, because of overlapping.  */
4597                             tmpsrc += count;
4598                             tmpdst += count;
4599                             for (n = count; n > 0; n--)
4600                               *--tmpdst = (unsigned char) *--tmpsrc;
4601                           }
4602                       }
4603 #endif
4604
4605 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4606                     /* Make room for the result.  */
4607                     if (count > allocated - length)
4608                       {
4609                         /* Need at least count elements.  But allocate
4610                            proportionally.  */
4611                         size_t n =
4612                           xmax (xsum (length, count), xtimes (allocated, 2));
4613
4614                         ENSURE_ALLOCATION (n);
4615                       }
4616 #endif
4617
4618                     /* Here count <= allocated - length.  */
4619
4620                     /* Perform padding.  */
4621 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4622                     if (pad_ourselves && has_width)
4623                       {
4624                         size_t w;
4625 # if ENABLE_UNISTDIO
4626                         /* Outside POSIX, it's preferrable to compare the width
4627                            against the number of _characters_ of the converted
4628                            value.  */
4629                         w = DCHAR_MBSNLEN (result + length, count);
4630 # else
4631                         /* The width is compared against the number of _bytes_
4632                            of the converted value, says POSIX.  */
4633                         w = count;
4634 # endif
4635                         if (w < width)
4636                           {
4637                             size_t pad = width - w;
4638
4639                             /* Make room for the result.  */
4640                             if (xsum (count, pad) > allocated - length)
4641                               {
4642                                 /* Need at least count + pad elements.  But
4643                                    allocate proportionally.  */
4644                                 size_t n =
4645                                   xmax (xsum3 (length, count, pad),
4646                                         xtimes (allocated, 2));
4647
4648 # if USE_SNPRINTF
4649                                 length += count;
4650                                 ENSURE_ALLOCATION (n);
4651                                 length -= count;
4652 # else
4653                                 ENSURE_ALLOCATION (n);
4654 # endif
4655                               }
4656                             /* Here count + pad <= allocated - length.  */
4657
4658                             {
4659 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
4660                               DCHAR_T * const rp = result + length;
4661 # else
4662                               DCHAR_T * const rp = tmp;
4663 # endif
4664                               DCHAR_T *p = rp + count;
4665                               DCHAR_T *end = p + pad;
4666                               DCHAR_T *pad_ptr;
4667 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4668                               if (dp->conversion == 'c'
4669                                   || dp->conversion == 's')
4670                                 /* No zero-padding for string directives.  */
4671                                 pad_ptr = NULL;
4672                               else
4673 # endif
4674                                 {
4675                                   pad_ptr = (*rp == '-' ? rp + 1 : rp);
4676                                   /* No zero-padding of "inf" and "nan".  */
4677                                   if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
4678                                       || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
4679                                     pad_ptr = NULL;
4680                                 }
4681                               /* The generated string now extends from rp to p,
4682                                  with the zero padding insertion point being at
4683                                  pad_ptr.  */
4684
4685                               count = count + pad; /* = end - rp */
4686
4687                               if (flags & FLAG_LEFT)
4688                                 {
4689                                   /* Pad with spaces on the right.  */
4690                                   for (; pad > 0; pad--)
4691                                     *p++ = ' ';
4692                                 }
4693                               else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4694                                 {
4695                                   /* Pad with zeroes.  */
4696                                   DCHAR_T *q = end;
4697
4698                                   while (p > pad_ptr)
4699                                     *--q = *--p;
4700                                   for (; pad > 0; pad--)
4701                                     *p++ = '0';
4702                                 }
4703                               else
4704                                 {
4705                                   /* Pad with spaces on the left.  */
4706                                   DCHAR_T *q = end;
4707
4708                                   while (p > rp)
4709                                     *--q = *--p;
4710                                   for (; pad > 0; pad--)
4711                                     *p++ = ' ';
4712                                 }
4713                             }
4714                           }
4715                       }
4716 #endif
4717
4718                     /* Here still count <= allocated - length.  */
4719
4720 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
4721                     /* The snprintf() result did fit.  */
4722 #else
4723                     /* Append the sprintf() result.  */
4724                     memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4725 #endif
4726 #if !USE_SNPRINTF
4727                     if (tmp != tmpbuf)
4728                       free (tmp);
4729 #endif
4730
4731 #if NEED_PRINTF_DIRECTIVE_F
4732                     if (dp->conversion == 'F')
4733                       {
4734                         /* Convert the %f result to upper case for %F.  */
4735                         DCHAR_T *rp = result + length;
4736                         size_t rc;
4737                         for (rc = count; rc > 0; rc--, rp++)
4738                           if (*rp >= 'a' && *rp <= 'z')
4739                             *rp = *rp - 'a' + 'A';
4740                       }
4741 #endif
4742
4743                     length += count;
4744                     break;
4745                   }
4746               }
4747           }
4748       }
4749
4750     /* Add the final NUL.  */
4751     ENSURE_ALLOCATION (xsum (length, 1));
4752     result[length] = '\0';
4753
4754     if (result != resultbuf && length + 1 < allocated)
4755       {
4756         /* Shrink the allocated memory if possible.  */
4757         DCHAR_T *memory;
4758
4759         memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
4760         if (memory != NULL)
4761           result = memory;
4762       }
4763
4764     if (buf_malloced != NULL)
4765       free (buf_malloced);
4766     CLEANUP ();
4767     *lengthp = length;
4768     /* Note that we can produce a big string of a length > INT_MAX.  POSIX
4769        says that snprintf() fails with errno = EOVERFLOW in this case, but
4770        that's only because snprintf() returns an 'int'.  This function does
4771        not have this limitation.  */
4772     return result;
4773
4774 #if USE_SNPRINTF
4775   overflow:
4776     if (!(result == resultbuf || result == NULL))
4777       free (result);
4778     if (buf_malloced != NULL)
4779       free (buf_malloced);
4780     CLEANUP ();
4781     errno = EOVERFLOW;
4782     return NULL;
4783 #endif
4784
4785   out_of_memory:
4786     if (!(result == resultbuf || result == NULL))
4787       free (result);
4788     if (buf_malloced != NULL)
4789       free (buf_malloced);
4790   out_of_memory_1:
4791     CLEANUP ();
4792     errno = ENOMEM;
4793     return NULL;
4794   }
4795 }
4796
4797 #undef TCHARS_PER_DCHAR
4798 #undef SNPRINTF
4799 #undef USE_SNPRINTF
4800 #undef DCHAR_CPY
4801 #undef PRINTF_PARSE
4802 #undef DIRECTIVES
4803 #undef DIRECTIVE
4804 #undef DCHAR_IS_TCHAR
4805 #undef TCHAR_T
4806 #undef DCHAR_T
4807 #undef FCHAR_T
4808 #undef VASNPRINTF