]> git.kernelconcepts.de Git - karo-tx-redboot.git/blob - packages/language/c/libc/stdio/v2_0/src/output/vfnprintf.cxx
unified MX27, MX25, MX37 trees
[karo-tx-redboot.git] / packages / language / c / libc / stdio / v2_0 / src / output / vfnprintf.cxx
1 //===========================================================================
2 //
3 //      vfnprintf.c
4 //
5 //      I/O routines for vfnprintf() for use with ANSI C library
6 //
7 //===========================================================================
8 //####ECOSGPLCOPYRIGHTBEGIN####
9 // -------------------------------------------
10 // This file is part of eCos, the Embedded Configurable Operating System.
11 // Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
12 //
13 // eCos is free software; you can redistribute it and/or modify it under
14 // the terms of the GNU General Public License as published by the Free
15 // Software Foundation; either version 2 or (at your option) any later version.
16 //
17 // eCos is distributed in the hope that it will be useful, but WITHOUT ANY
18 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 // FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20 // for more details.
21 //
22 // You should have received a copy of the GNU General Public License along
23 // with eCos; if not, write to the Free Software Foundation, Inc.,
24 // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
25 //
26 // As a special exception, if other files instantiate templates or use macros
27 // or inline functions from this file, or you compile this file and link it
28 // with other works to produce a work based on this file, this file does not
29 // by itself cause the resulting work to be covered by the GNU General Public
30 // License. However the source code for this file must still be made available
31 // in accordance with section (3) of the GNU General Public License.
32 //
33 // This exception does not invalidate any other reasons why a work based on
34 // this file might be covered by the GNU General Public License.
35 //
36 // Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
37 // at http://sources.redhat.com/ecos/ecos-license/
38 // -------------------------------------------
39 //####ECOSGPLCOPYRIGHTEND####
40 //===========================================================================
41 //#####DESCRIPTIONBEGIN####
42 //
43 // Author(s):    jlarmour
44 // Contributors: 
45 // Date:         2000-04-20
46 // Purpose:     
47 // Description: 
48 // Usage:       
49 //
50 //####DESCRIPTIONEND####
51 //
52 //===========================================================================
53 //
54 // This code is based on original code with the following copyright:
55 //
56 /*-
57  * Copyright (c) 1990 The Regents of the University of California.
58  * All rights reserved.
59  *
60  * This code is derived from software contributed to Berkeley by
61  * Chris Torek.
62  *
63  * Redistribution and use in source and binary forms, with or without
64  * modification, are permitted provided that the following conditions
65  * are met:
66  * 1. Redistributions of source code must retain the above copyright
67  *    notice, this list of conditions and the following disclaimer.
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in the
70  *    documentation and/or other materials provided with the distribution.
71  * 3. Neither the name of the University nor the names of its contributors
72  *    may be used to endorse or promote products derived from this software
73  *    without specific prior written permission.
74  *
75  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
76  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
77  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
78  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
79  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
80  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
81  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
82  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
83  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
84  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
85  * SUCH DAMAGE.
86  */
87
88
89 // CONFIGURATION
90
91 #include <pkgconf/libc_stdio.h>   // Configuration header
92 #include <pkgconf/libc_i18n.h>    // Configuration header for mb support
93
94 // INCLUDES
95
96 #include <cyg/infra/cyg_type.h>   // Common type definitions and support
97 #include <stdarg.h>               // Variable argument definitions
98 #include <stdio.h>                // Standard header for all stdio files
99 #include <string.h>               // memchr() and strlen() functions
100 #include <cyg/libc/stdio/stream.hxx> // C library streams
101
102 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
103
104 # include <float.h>      // for DBL_DIG etc. below
105 # include <math.h>       // for modf()
106 # include <sys/ieeefp.h> // Cyg_libm_ieee_double_shape_type
107
108 # define MAXFRACT  DBL_DIG
109 # define MAXEXP    DBL_MAX_10_EXP
110
111 # define BUF             (MAXEXP+MAXFRACT+1)     /* + decimal point */
112 # define DEFPREC         6
113
114 static int
115 cvt( double, int, int, char *, int, char *, char * );
116
117 #else // ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
118
119 # define BUF            40
120
121 #endif // ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
122
123 /*
124  * Actual printf innards.
125  *
126  * This code is large and complicated...
127  */
128
129 #ifdef CYGINT_LIBC_I18N_MB_REQUIRED
130 typedef int (*mbtowc_fn_type)(wchar_t *, const char *, size_t, int *);
131 externC mbtowc_fn_type __get_current_locale_mbtowc_fn();
132 #endif
133
134 /*
135  * Macros for converting digits to letters and vice versa
136  */
137 #define to_digit(c)     ((c) - '0')
138 #define is_digit(c)     ((unsigned)to_digit(c) <= 9)
139 #define to_char(n)      ((n) + '0')
140
141 /*
142  * Flags used during conversion.
143  */
144 #define ALT             0x001           /* alternate form */
145 #define HEXPREFIX       0x002           /* add 0x or 0X prefix */
146 #define LADJUST         0x004           /* left adjustment */
147 #define LONGDBL         0x008           /* long double; unimplemented */
148 #define LONGINT         0x010           /* long integer */
149 #define QUADINT         0x020           /* quad integer */
150 #define SHORTINT        0x040           /* short integer */
151 #define ZEROPAD         0x080           /* zero (as opposed to blank) pad */
152 #define FPT             0x100           /* Floating point number */
153 #define SIZET           0x200           /* size_t */
154
155 externC int 
156 vfnprintf ( FILE *stream, size_t n, const char *format, va_list arg) __THROW
157 {
158         char *fmt;     /* format string */
159         int ch;        /* character from fmt */
160         int x, y;      /* handy integers (short term usage) */
161         char *cp;      /* handy char pointer (short term usage) */
162         int flags;     /* flags as above */
163
164 #ifdef CYGINT_LIBC_I18N_MB_REQUIRED
165         int state = 0; /* state for mbtowc conversion */
166         mbtowc_fn_type mbtowc_fn;
167 #endif
168
169         int ret;                /* return value accumulator */
170         int width;              /* width from format (%8d), or 0 */
171         int prec;               /* precision from format (%.3d), or -1 */
172         char sign;              /* sign prefix (' ', '+', '-', or \0) */
173         wchar_t wc;
174
175 #define quad_t    long long
176 #define u_quad_t  unsigned long long
177
178         u_quad_t _uquad;        /* integer arguments %[diouxX] */
179         enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
180         int dprec;              /* a copy of prec if [diouxX], 0 otherwise */
181         int fieldsz;            /* field size expanded by sign, etc */
182         int realsz;             /* field size expanded by dprec */
183         int size;               /* size of converted field or string */
184         char *xdigs;            /* digits for [xX] conversion */
185 #define NIOV 8
186         char buf[BUF];          /* space for %c, %[diouxX], %[eEfgG] */
187         char ox[2];             /* space for 0x hex-prefix */
188 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
189         char softsign;          /* temporary negative sign for floats */
190         double _double;         /* double precision arguments %[eEfgG] */
191         int fpprec;             /* `extra' floating precision in [eEfgG] */
192 #endif
193
194         /*
195          * Choose PADSIZE to trade efficiency vs. size.  If larger printf
196          * fields occur frequently, increase PADSIZE and make the initialisers
197          * below longer.
198          */
199 #define PADSIZE 16              /* pad chunk size */
200         static char blanks[PADSIZE] =
201          {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
202         static char zeroes[PADSIZE] =
203          {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
204
205 #define MIN(a, b) ((a) < (b) ? (a) : (b))
206
207         /*
208          * BEWARE, these `goto error' on error, and PAD uses `n'.
209          */
210 #define PRINT(ptr, len)                                                      \
211 CYG_MACRO_START                                                              \
212     cyg_ucount32 length = MIN( (cyg_ucount32) len, n - ret - 1);             \
213     if (((Cyg_OutputStream *)stream)->write( (const cyg_uint8 *)ptr,         \
214                                             length, &length ))               \
215         goto error;                                                          \
216     if (length < (cyg_ucount32)len) {                                        \
217         ret += length;                                                       \
218         goto done;                                                           \
219     }                                                                        \
220 CYG_MACRO_END
221
222
223 #define PAD(howmany, with)                                                   \
224 CYG_MACRO_START                                                              \
225     if ((x = (howmany)) > 0) {                                               \
226         while (x > PADSIZE) {                                                \
227             PRINT(with, PADSIZE);                                            \
228             x -= PADSIZE;                                                    \
229         }                                                                    \
230         PRINT(with, x);                                                      \
231     }                                                                        \
232 CYG_MACRO_END
233
234         /*
235          * To extend shorts properly, we need both signed and unsigned
236          * argument extraction methods.
237          */
238
239 #define SARG() \
240         (flags&QUADINT ? va_arg(arg, cyg_int64) : \
241             flags&LONGINT ? va_arg(arg, long) : \
242             flags&SHORTINT ? (long)(short)va_arg(arg, int) : \
243             flags&SIZET ? (long)va_arg(arg, size_t) : \
244             (long)va_arg(arg, int))
245 #define UARG() \
246         (flags&QUADINT ? va_arg(arg, cyg_uint64) : \
247             flags&LONGINT ? va_arg(arg, unsigned long) : \
248             flags&SHORTINT ? (unsigned long)(unsigned short)va_arg(arg, int) : \
249             flags&SIZET ? va_arg(arg, size_t) : \
250             (unsigned long)va_arg(arg, unsigned int))
251
252
253         xdigs = NULL;  // stop compiler whinging
254         fmt = (char *)format;
255         ret = 0;
256 #ifdef CYGINT_LIBC_I18N_MB_REQUIRED
257         mbtowc_fn = __get_current_locale_mbtowc_fn();
258 #endif
259
260         /*
261          * Scan the format for conversions (`%' character).
262          */
263         for (;;) {
264                 cp = (char *)fmt;
265 #ifndef CYGINT_LIBC_I18N_MB_REQUIRED
266                 while ((x = ((wc = *fmt) != 0))) {
267 #else
268                 while ((x = mbtowc_fn (&wc, fmt, MB_CUR_MAX, &state)) > 0) {
269 #endif
270                         fmt += x;
271                         if (wc == '%') {
272                                 fmt--;
273                                 break;
274                         }
275                 }
276                 if ((y = fmt - cp) != 0) {
277                         PRINT(cp, y);
278                         ret += y;
279                 }
280                 if ((x <= 0) || (ret >= (int)n))  // @@@ this check with n isn't good enough
281                         goto done;
282                 fmt++;          /* skip over '%' */
283
284                 flags = 0;
285                 dprec = 0;
286 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
287                 fpprec = 0;
288 #endif
289                 width = 0;
290                 prec = -1;
291                 sign = '\0';
292
293 rflag:          ch = *fmt++;
294 reswitch:       switch (ch) {
295                 case ' ':
296                         /*
297                          * ``If the space and + flags both appear, the space
298                          * flag will be ignored.''
299                          *      -- ANSI X3J11
300                          */
301                         if (!sign)
302                                 sign = ' ';
303                         goto rflag;
304                 case '#':
305                         flags |= ALT;
306                         goto rflag;
307                 case '*':
308                         /*
309                          * ``A negative field width argument is taken as a
310                          * - flag followed by a positive field width.''
311                          *      -- ANSI X3J11
312                          * They don't exclude field widths read from args.
313                          */
314                         if ((width = va_arg(arg, int)) >= 0)
315                                 goto rflag;
316                         width = -width;
317                         /* FALLTHROUGH */
318                 case '-':
319                         flags |= LADJUST;
320                         goto rflag;
321                 case '+':
322                         sign = '+';
323                         goto rflag;
324                 case '.':
325                         if ((ch = *fmt++) == '*') {
326                                 x = va_arg(arg, int);
327                                 prec = x < 0 ? -1 : x;
328                                 goto rflag;
329                         }
330                         x = 0;
331                         while (is_digit(ch)) {
332                                 x = 10 * x + to_digit(ch);
333                                 ch = *fmt++;
334                         }
335                         prec = x < 0 ? -1 : x;
336                         goto reswitch;
337                 case '0':
338                         /*
339                          * ``Note that 0 is taken as a flag, not as the
340                          * beginning of a field width.''
341                          *      -- ANSI X3J11
342                          */
343                         flags |= ZEROPAD;
344                         goto rflag;
345                 case '1': case '2': case '3': case '4':
346                 case '5': case '6': case '7': case '8': case '9':
347                         x = 0;
348                         do {
349                                 x = 10 * x + to_digit(ch);
350                                 ch = *fmt++;
351                         } while (is_digit(ch));
352                         width = x;
353                         goto reswitch;
354 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
355                 case 'L':
356                         flags |= LONGDBL;
357                         goto rflag;
358 #endif
359                 case 'h':
360                         flags |= SHORTINT;
361                         goto rflag;
362                 case 'l':
363                         if (*fmt == 'l') {
364                                 fmt++;
365                                 flags |= QUADINT;
366                         } else {
367                                 flags |= LONGINT;
368                         }
369                         goto rflag;
370                 case 'q':
371                         flags |= QUADINT;
372                         goto rflag;
373                 case 'c':
374                         *(cp = buf) = va_arg(arg, int);
375                         size = 1;
376                         sign = '\0';
377                         break;
378                 case 'D':
379                         flags |= LONGINT;
380                         /*FALLTHROUGH*/
381                 case 'd':
382                 case 'i':
383                         _uquad = SARG();
384 #ifndef _NO_LONGLONG
385                         if ((quad_t)_uquad < 0)
386 #else
387                         if ((long) _uquad < 0)
388 #endif
389                         {
390
391                                 _uquad = -_uquad;
392                                 sign = '-';
393                         }
394                         base = DEC;
395                         goto number;
396
397 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
398                 case 'e':
399                 case 'E':
400                 case 'f':
401                 case 'g':
402                 case 'G':
403                         _double = va_arg(arg, double);
404                         /*
405                          * don't do unrealistic precision; just pad it with
406                          * zeroes later, so buffer size stays rational.
407                          */
408                         if (prec > MAXFRACT) {
409                                 if ((ch != 'g' && ch != 'G') || (flags&ALT))
410                                         fpprec = prec - MAXFRACT;
411                                 prec = MAXFRACT;
412                         } else if (prec == -1)
413                                 prec = DEFPREC;
414                         /*
415                          * cvt may have to round up before the "start" of
416                          * its buffer, i.e. ``intf("%.2f", (double)9.999);'';
417                          * if the first character is still NUL, it did.
418                          * softsign avoids negative 0 if _double < 0 but
419                          * no significant digits will be shown.
420                          */
421                         cp = buf;
422                         *cp = '\0';
423                         size = cvt(_double, prec, flags, &softsign, ch,
424                             cp, buf + sizeof(buf));
425                         if (softsign)
426                                 sign = '-';
427                         if (*cp == '\0')
428                                 cp++;
429                         break;
430 #else
431                 case 'e':
432                 case 'E':
433                 case 'f':
434                 case 'g':
435                 case 'G':
436                         // Output nothing at all
437                         (void) va_arg(arg, double); // take off arg anyway
438                         cp = "";
439                         size = 0;
440                         sign = '\0';
441                         break;
442                         
443                          
444 #endif // ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
445
446                 case 'n':
447 #ifndef _NO_LONGLONG
448                         if (flags & QUADINT)
449                                 *va_arg(arg, quad_t *) = ret;
450                         else 
451 #endif
452                         if (flags & LONGINT)
453                                 *va_arg(arg, long *) = ret;
454                         else if (flags & SHORTINT)
455                                 *va_arg(arg, short *) = ret;
456                         else if (flags & SIZET)
457                                 *va_arg(arg, size_t *) = ret;
458                         else
459                                 *va_arg(arg, int *) = ret;
460                         continue;       /* no output */
461                 case 'O':
462                         flags |= LONGINT;
463                         /*FALLTHROUGH*/
464                 case 'o':
465                         _uquad = UARG();
466                         base = OCT;
467                         goto nosign;
468                 case 'p':
469                         /*
470                          * ``The argument shall be a pointer to void.  The
471                          * value of the pointer is converted to a sequence
472                          * of printable characters, in an implementation-
473                          * defined manner.''
474                          *      -- ANSI X3J11
475                          */
476                         /* NOSTRICT */
477                         _uquad = (unsigned long)va_arg(arg, void *);
478                         base = HEX;
479                         xdigs = (char *)"0123456789abcdef";
480                         flags |= HEXPREFIX;
481                         ch = 'x';
482                         goto nosign;
483                 case 's':
484                         if ((cp = va_arg(arg, char *)) == NULL)
485                                 cp = (char *)"(null)";
486                         if (prec >= 0) {
487                                 /*
488                                  * can't use strlen; can only look for the
489                                  * NUL in the first `prec' characters, and
490                                  * strlen() will go further.
491                                  */
492                                 char *p = (char *)memchr(cp, 0, prec);
493
494                                 if (p != NULL) {
495                                         size = p - cp;
496                                         if (size > prec)
497                                                 size = prec;
498                                 } else
499                                         size = prec;
500                         } else
501                                 size = strlen(cp);
502                         sign = '\0';
503                         break;
504                 case 'U':
505                         flags |= LONGINT;
506                         /*FALLTHROUGH*/
507                 case 'u':
508                         _uquad = UARG();
509                         base = DEC;
510                         goto nosign;
511                 case 'X':
512                         xdigs = (char *)"0123456789ABCDEF";
513                         goto hex;
514                 case 'x':
515                         xdigs = (char *)"0123456789abcdef";
516 hex:                    _uquad = UARG();
517                         base = HEX;
518                         /* leading 0x/X only if non-zero */
519                         if (flags & ALT && _uquad != 0)
520                                 flags |= HEXPREFIX;
521
522                         /* unsigned conversions */
523 nosign:                 sign = '\0';
524                         /*
525                          * ``... diouXx conversions ... if a precision is
526                          * specified, the 0 flag will be ignored.''
527                          *      -- ANSI X3J11
528                          */
529 number:                 if ((dprec = prec) >= 0)
530                                 flags &= ~ZEROPAD;
531
532                         /*
533                          * ``The result of converting a zero value with an
534                          * explicit precision of zero is no characters.''
535                          *      -- ANSI X3J11
536                          */
537                         cp = buf + BUF;
538                         if (_uquad != 0 || prec != 0) {
539                                 /*
540                                  * Unsigned mod is hard, and unsigned mod
541                                  * by a constant is easier than that by
542                                  * a variable; hence this switch.
543                                  */
544                                 switch (base) {
545                                 case OCT:
546                                         do {
547                                                 *--cp = to_char(_uquad & 7);
548                                                 _uquad >>= 3;
549                                         } while (_uquad);
550                                         /* handle octal leading 0 */
551                                         if (flags & ALT && *cp != '0')
552                                                 *--cp = '0';
553                                         break;
554
555                                 case DEC:
556                                         if (!(flags & QUADINT)) {
557                                                 /* many numbers are 1 digit */
558                                                 unsigned long v = (unsigned long)_uquad;
559                                                 while (v >= 10) {
560                                                         /* The following is usually faster than using a modulo */
561                                                         unsigned long next = v / 10;
562                                                         *--cp = to_char(v - (next * 10));
563                                                         v = next;
564                                                 }
565                                                 *--cp = to_char(v);
566                                         }
567                                         else {
568                                                 while (_uquad >= 10) {
569                                                         /* The following is usually faster than using a modulo */
570                                                         u_quad_t next = _uquad / 10;
571                                                         *--cp = to_char(_uquad - (next * 10));
572                                                         _uquad = next;
573                                                 }
574                                                 *--cp = to_char(_uquad);
575                                         }
576                                         break;
577
578                                 case HEX:
579                                         do {
580                                                 *--cp = xdigs[_uquad & 15];
581                                                 _uquad >>= 4;
582                                         } while (_uquad);
583                                         break;
584
585                                 default:
586                                         cp = (char *)"bug in vfprintf: bad base";
587                                         size = strlen(cp);
588                                         goto skipsize;
589                                 }
590                         }
591                         size = buf + BUF - cp;
592                 skipsize:
593                         break;
594                 case 'z':
595                         flags |= SIZET;
596                         goto rflag;
597                 default:        /* "%?" prints ?, unless ? is NUL */
598                         if (ch == '\0')
599                                 goto done;
600                         /* pretend it was %c with argument ch */
601                         cp = buf;
602                         *cp = ch;
603                         size = 1;
604                         sign = '\0';
605                         break;
606                 }
607
608                 /*
609                  * All reasonable formats wind up here.  At this point, `cp'
610                  * points to a string which (if not flags&LADJUST) should be
611                  * padded out to `width' places.  If flags&ZEROPAD, it should
612                  * first be prefixed by any sign or other prefix; otherwise,
613                  * it should be blank padded before the prefix is emitted.
614                  * After any left-hand padding and prefixing, emit zeroes
615                  * required by a decimal [diouxX] precision, then print the
616                  * string proper, then emit zeroes required by any leftover
617                  * floating precision; finally, if LADJUST, pad with blanks.
618                  *
619                  * Compute actual size, so we know how much to pad.
620                  * fieldsz excludes decimal prec; realsz includes it.
621                  */
622 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
623                 fieldsz = size + fpprec;
624 #else
625                 fieldsz = size;
626 #endif
627                 if (sign)
628                         fieldsz++;
629                 else if (flags & HEXPREFIX)
630                         fieldsz+= 2;
631                 realsz = dprec > fieldsz ? dprec : fieldsz;
632
633                 /* right-adjusting blank padding */
634                 if ((flags & (LADJUST|ZEROPAD)) == 0) {
635                     if (width - realsz > 0) {
636                         PAD(width - realsz, blanks);
637                         ret += width - realsz;
638                     }
639                 }
640
641                 /* prefix */
642                 if (sign) {
643                         PRINT(&sign, 1);
644                         ret++;
645                 } else if (flags & HEXPREFIX) {
646                         ox[0] = '0';
647                         ox[1] = ch;
648                         PRINT(ox, 2);
649                         ret += 2;
650                 }
651
652                 /* right-adjusting zero padding */
653                 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
654                     if (width - realsz > 0) {
655                         PAD(width - realsz, zeroes);
656                         ret += width - realsz;
657                     }
658                 }
659
660                 if (dprec - fieldsz > 0) {
661                     /* leading zeroes from decimal precision */
662                     PAD(dprec - fieldsz, zeroes);
663                     ret += dprec - fieldsz;
664                 }
665
666                 /* the string or number proper */
667                 PRINT(cp, size);
668                 ret += size;
669
670 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
671                 /* trailing f.p. zeroes */
672                 PAD(fpprec, zeroes);
673                 ret += fpprec;
674 #endif
675
676                 /* left-adjusting padding (always blank) */
677                 if (flags & LADJUST) {
678                     if (width - realsz > 0) {
679                         PAD(width - realsz, blanks);
680                         ret += width - realsz;
681                     }
682                 }
683
684         }
685 done:
686 error:
687         return (((Cyg_OutputStream *) stream)->get_error() ? EOF : ret);
688         /* NOTREACHED */
689 }
690
691
692 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
693
694 static char *
695 round(double fract, int *exp, char *start, char *end, char ch, char *signp)
696 {
697         double tmp;
698
699         if (fract)
700         (void)modf(fract * 10, &tmp);
701         else
702                 tmp = to_digit(ch);
703         if (tmp > 4)
704                 for (;; --end) {
705                         if (*end == '.')
706                                 --end;
707                         if (++*end <= '9')
708                                 break;
709                         *end = '0';
710                         if (end == start) {
711                                 if (exp) {      /* e/E; increment exponent */
712                                         *end = '1';
713                                         ++*exp;
714                                 }
715                                 else {          /* f; add extra digit */
716                                 *--end = '1';
717                                 --start;
718                                 }
719                                 break;
720                         }
721                 }
722         /* ``"%.3f", (double)-0.0004'' gives you a negative 0. */
723         else if (*signp == '-')
724                 for (;; --end) {
725                         if (*end == '.')
726                                 --end;
727                         if (*end != '0')
728                                 break;
729                         if (end == start)
730                                 *signp = 0;
731                 }
732         return (start);
733 } // round()
734
735
736 static char *
737 exponent(char *p, int exp, int fmtch)
738 {
739         char *t;
740         char expbuf[MAXEXP];
741
742         *p++ = fmtch;
743         if (exp < 0) {
744                 exp = -exp;
745                 *p++ = '-';
746         }
747         else
748                 *p++ = '+';
749         t = expbuf + MAXEXP;
750         if (exp > 9) {
751                 do {
752                         *--t = to_char(exp % 10);
753                 } while ((exp /= 10) > 9);
754                 *--t = to_char(exp);
755                 for (; t < expbuf + MAXEXP; *p++ = *t++);
756         }
757         else {
758                 *p++ = '0';
759                 *p++ = to_char(exp);
760         }
761         return (p);
762 } // exponent()
763
764
765 static int
766 cvt(double number, int prec, int flags, char *signp, int fmtch, char *startp,
767     char *endp)
768 {
769     Cyg_libm_ieee_double_shape_type ieeefp;
770     char *t = startp;
771
772     ieeefp.value = number;
773     *signp = 0;
774     if ( ieeefp.number.sign ){  // this checks for <0.0 and -0.0
775         number = -number;
776         *signp = '-';
777     }
778
779     if (finite(number)) {
780         char *p;
781         double fract;
782         int dotrim, expcnt, gformat;
783         double integer, tmp;
784
785         dotrim = expcnt = gformat = 0;
786         fract = modf(number, &integer);
787
788         /* get an extra slot for rounding. */
789         t = ++startp;
790
791         /*
792          * get integer portion of number; put into the end of the buffer; the
793          * .01 is added for modf(356.0 / 10, &integer) returning .59999999...
794          */
795         for (p = endp - 1; integer; ++expcnt) {
796                 tmp = modf(integer / 10, &integer);
797                 *p-- = to_char((int)((tmp + .01) * 10));
798         }
799         switch (fmtch) {
800         case 'f':
801                 /* reverse integer into beginning of buffer */
802                 if (expcnt)
803                         for (; ++p < endp; *t++ = *p);
804                 else
805                         *t++ = '0';
806                 /*
807                  * if precision required or alternate flag set, add in a
808                  * decimal point.
809                  */
810                 if (prec || flags&ALT)
811                         *t++ = '.';
812                 /* if requires more precision and some fraction left */
813                 if (fract) {
814                         if (prec)
815                                 do {
816                                         fract = modf(fract * 10, &tmp);
817                                         *t++ = to_char((int)tmp);
818                                 } while (--prec && fract);
819                         if (fract)
820                                 startp = round(fract, (int *)NULL, startp,
821                                     t - 1, (char)0, signp);
822                 }
823                 for (; prec--; *t++ = '0');
824                 break;
825         case 'e':
826         case 'E':
827 eformat:        if (expcnt) {
828                         *t++ = *++p;
829                         if (prec || flags&ALT)
830                                 *t++ = '.';
831                         /* if requires more precision and some integer left */
832                         for (; prec && ++p < endp; --prec)
833                                 *t++ = *p;
834                         /*
835                          * if done precision and more of the integer component,
836                          * round using it; adjust fract so we don't re-round
837                          * later.
838                          */
839                         if (!prec && ++p < endp) {
840                                 fract = 0;
841                                 startp = round((double)0, &expcnt, startp,
842                                     t - 1, *p, signp);
843                         }
844                         /* adjust expcnt for digit in front of decimal */
845                         --expcnt;
846                 }
847                 /* until first fractional digit, decrement exponent */
848                 else if (fract) {
849                         /* adjust expcnt for digit in front of decimal */
850                         for (expcnt = -1;; --expcnt) {
851                                 fract = modf(fract * 10, &tmp);
852                                 if (tmp)
853                                         break;
854                         }
855                         *t++ = to_char((int)tmp);
856                         if (prec || flags&ALT)
857                                 *t++ = '.';
858                 }
859                 else {
860                         *t++ = '0';
861                         if (prec || flags&ALT)
862                                 *t++ = '.';
863                 }
864                 /* if requires more precision and some fraction left */
865                 if (fract) {
866                         if (prec)
867                                 do {
868                                         fract = modf(fract * 10, &tmp);
869                                         *t++ = to_char((int)tmp);
870                                 } while (--prec && fract);
871                         if (fract)
872                                 startp = round(fract, &expcnt, startp,
873                                     t - 1, (char)0, signp);
874                 }
875                 /* if requires more precision */
876                 for (; prec--; *t++ = '0');
877
878                 /* unless alternate flag, trim any g/G format trailing 0's */
879                 if (gformat && !(flags&ALT)) {
880                         while (t > startp && *--t == '0');
881                         if (*t == '.')
882                                 --t;
883                         ++t;
884                 }
885                 t = exponent(t, expcnt, fmtch);
886                 break;
887         case 'g':
888         case 'G':
889                 /* a precision of 0 is treated as a precision of 1. */
890                 if (!prec)
891                         ++prec;
892                 /*
893                  * ``The style used depends on the value converted; style e
894                  * will be used only if the exponent resulting from the
895                  * conversion is less than -4 or greater than the precision.''
896                  *      -- ANSI X3J11
897                  */
898                 if (expcnt > prec || (!expcnt && fract && fract < .0001)) {
899                         /*
900                          * g/G format counts "significant digits, not digits of
901                          * precision; for the e/E format, this just causes an
902                          * off-by-one problem, i.e. g/G considers the digit
903                          * before the decimal point significant and e/E doesn't
904                          * count it as precision.
905                          */
906                         --prec;
907                         fmtch -= 2;             /* G->E, g->e */
908                         gformat = 1;
909                         goto eformat;
910                 }
911                 /*
912                  * reverse integer into beginning of buffer,
913                  * note, decrement precision
914                  */
915                 if (expcnt)
916                         for (; ++p < endp; *t++ = *p, --prec);
917                 else
918                         *t++ = '0';
919                 /*
920                  * if precision required or alternate flag set, add in a
921                  * decimal point.  If no digits yet, add in leading 0.
922                  */
923                 if (prec || flags&ALT) {
924                         dotrim = 1;
925                         *t++ = '.';
926                 }
927                 else
928                         dotrim = 0;
929                 /* if requires more precision and some fraction left */
930                 if (fract) {
931                         if (prec) {
932                                 do {
933                                         fract = modf(fract * 10, &tmp);
934                                         *t++ = to_char((int)tmp);
935                                 } while(!tmp);
936                                 while (--prec && fract) {
937                                         fract = modf(fract * 10, &tmp);
938                                         *t++ = to_char((int)tmp);
939                                 }
940                         }
941                         if (fract)
942                                 startp = round(fract, (int *)NULL, startp,
943                                     t - 1, (char)0, signp);
944                 }
945                 /* alternate format, adds 0's for precision, else trim 0's */
946                 if (flags&ALT)
947                         for (; prec--; *t++ = '0');
948                 else if (dotrim) {
949                         while (t > startp && *--t == '0');
950                         if (*t != '.')
951                                 ++t;
952                 }
953         }
954     } else {
955         unsigned case_adj;
956         switch (fmtch) {
957         case 'f':
958         case 'g':
959         case 'e':
960             case_adj = 'a' - 'A';
961             break;
962         default:
963             case_adj = 0;
964         }
965         if (isnan(number)) {
966             *t++ = 'N' + case_adj;
967             *t++ = 'A' + case_adj;
968             *t++ = 'N' + case_adj;
969         } else { // infinite
970             *t++ = 'I' + case_adj;
971             *t++ = 'N' + case_adj;
972             *t++ = 'F' + case_adj;
973         }
974     }
975     return (t - startp);
976 } // cvt()
977
978 #endif // ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
979
980 // EOF vfnprintf.cxx