OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [rtos/] [ecos-2.0/] [packages/] [language/] [c/] [libc/] [stdio/] [v2_0/] [src/] [output/] [vfnprintf.cxx] - Blame information for rev 672

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 27 unneback
//===========================================================================
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)
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_StdioStream *)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 ? 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 = "0123456789abcdef";
480
                        flags |= HEXPREFIX;
481
                        ch = 'x';
482
                        goto nosign;
483
                case 's':
484
                        if ((cp = va_arg(arg, char *)) == NULL)
485
                                cp = "(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 = "0123456789ABCDEF";
513
                        goto hex;
514
                case 'x':
515
                        xdigs = "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
                                        /* many numbers are 1 digit */
557
                                        while (_uquad >= 10) {
558
                                                *--cp = to_char(_uquad % 10);
559
                                                _uquad /= 10;
560
                                        }
561
                                        *--cp = to_char(_uquad);
562
                                        break;
563
 
564
                                case HEX:
565
                                        do {
566
                                                *--cp = xdigs[_uquad & 15];
567
                                                _uquad >>= 4;
568
                                        } while (_uquad);
569
                                        break;
570
 
571
                                default:
572
                                        cp = "bug in vfprintf: bad base";
573
                                        size = strlen(cp);
574
                                        goto skipsize;
575
                                }
576
                        }
577
                        size = buf + BUF - cp;
578
                skipsize:
579
                        break;
580
                case 'z':
581
                        flags |= SIZET;
582
                        goto rflag;
583
                default:        /* "%?" prints ?, unless ? is NUL */
584
                        if (ch == '\0')
585
                                goto done;
586
                        /* pretend it was %c with argument ch */
587
                        cp = buf;
588
                        *cp = ch;
589
                        size = 1;
590
                        sign = '\0';
591
                        break;
592
                }
593
 
594
                /*
595
                 * All reasonable formats wind up here.  At this point, `cp'
596
                 * points to a string which (if not flags&LADJUST) should be
597
                 * padded out to `width' places.  If flags&ZEROPAD, it should
598
                 * first be prefixed by any sign or other prefix; otherwise,
599
                 * it should be blank padded before the prefix is emitted.
600
                 * After any left-hand padding and prefixing, emit zeroes
601
                 * required by a decimal [diouxX] precision, then print the
602
                 * string proper, then emit zeroes required by any leftover
603
                 * floating precision; finally, if LADJUST, pad with blanks.
604
                 *
605
                 * Compute actual size, so we know how much to pad.
606
                 * fieldsz excludes decimal prec; realsz includes it.
607
                 */
608
#ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
609
                fieldsz = size + fpprec;
610
#else
611
                fieldsz = size;
612
#endif
613
                if (sign)
614
                        fieldsz++;
615
                else if (flags & HEXPREFIX)
616
                        fieldsz+= 2;
617
                realsz = dprec > fieldsz ? dprec : fieldsz;
618
 
619
                /* right-adjusting blank padding */
620
                if ((flags & (LADJUST|ZEROPAD)) == 0) {
621
                    if (width - realsz > 0) {
622
                        PAD(width - realsz, blanks);
623
                        ret += width - realsz;
624
                    }
625
                }
626
 
627
                /* prefix */
628
                if (sign) {
629
                        PRINT(&sign, 1);
630
                        ret++;
631
                } else if (flags & HEXPREFIX) {
632
                        ox[0] = '0';
633
                        ox[1] = ch;
634
                        PRINT(ox, 2);
635
                        ret += 2;
636
                }
637
 
638
                /* right-adjusting zero padding */
639
                if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
640
                    if (width - realsz > 0) {
641
                        PAD(width - realsz, zeroes);
642
                        ret += width - realsz;
643
                    }
644
                }
645
 
646
                if (dprec - fieldsz > 0) {
647
                    /* leading zeroes from decimal precision */
648
                    PAD(dprec - fieldsz, zeroes);
649
                    ret += dprec - fieldsz;
650
                }
651
 
652
                /* the string or number proper */
653
                PRINT(cp, size);
654
                ret += size;
655
 
656
#ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
657
                /* trailing f.p. zeroes */
658
                PAD(fpprec, zeroes);
659
                ret += fpprec;
660
#endif
661
 
662
                /* left-adjusting padding (always blank) */
663
                if (flags & LADJUST) {
664
                    if (width - realsz > 0) {
665
                        PAD(width - realsz, blanks);
666
                        ret += width - realsz;
667
                    }
668
                }
669
 
670
        }
671
done:
672
error:
673
        return (((Cyg_StdioStream *) stream)->get_error() ? EOF : ret);
674
        /* NOTREACHED */
675
}
676
 
677
 
678
#ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
679
 
680
static char *
681
round(double fract, int *exp, char *start, char *end, char ch, char *signp)
682
{
683
        double tmp;
684
 
685
        if (fract)
686
        (void)modf(fract * 10, &tmp);
687
        else
688
                tmp = to_digit(ch);
689
        if (tmp > 4)
690
                for (;; --end) {
691
                        if (*end == '.')
692
                                --end;
693
                        if (++*end <= '9')
694
                                break;
695
                        *end = '0';
696
                        if (end == start) {
697
                                if (exp) {      /* e/E; increment exponent */
698
                                        *end = '1';
699
                                        ++*exp;
700
                                }
701
                                else {          /* f; add extra digit */
702
                                *--end = '1';
703
                                --start;
704
                                }
705
                                break;
706
                        }
707
                }
708
        /* ``"%.3f", (double)-0.0004'' gives you a negative 0. */
709
        else if (*signp == '-')
710
                for (;; --end) {
711
                        if (*end == '.')
712
                                --end;
713
                        if (*end != '0')
714
                                break;
715
                        if (end == start)
716
                                *signp = 0;
717
                }
718
        return (start);
719
} // round()
720
 
721
 
722
static char *
723
exponent(char *p, int exp, int fmtch)
724
{
725
        char *t;
726
        char expbuf[MAXEXP];
727
 
728
        *p++ = fmtch;
729
        if (exp < 0) {
730
                exp = -exp;
731
                *p++ = '-';
732
        }
733
        else
734
                *p++ = '+';
735
        t = expbuf + MAXEXP;
736
        if (exp > 9) {
737
                do {
738
                        *--t = to_char(exp % 10);
739
                } while ((exp /= 10) > 9);
740
                *--t = to_char(exp);
741
                for (; t < expbuf + MAXEXP; *p++ = *t++);
742
        }
743
        else {
744
                *p++ = '0';
745
                *p++ = to_char(exp);
746
        }
747
        return (p);
748
} // exponent()
749
 
750
 
751
static int
752
cvt(double number, int prec, int flags, char *signp, int fmtch, char *startp,
753
    char *endp)
754
{
755
    Cyg_libm_ieee_double_shape_type ieeefp;
756
    char *t = startp;
757
 
758
    ieeefp.value = number;
759
    *signp = 0;
760
    if ( ieeefp.number.sign ){  // this checks for <0.0 and -0.0
761
        number = -number;
762
        *signp = '-';
763
    }
764
 
765
    if (finite(number)) {
766
        char *p;
767
        double fract;
768
        int dotrim, expcnt, gformat;
769
        double integer, tmp;
770
 
771
        dotrim = expcnt = gformat = 0;
772
        fract = modf(number, &integer);
773
 
774
        /* get an extra slot for rounding. */
775
        t = ++startp;
776
 
777
        /*
778
         * get integer portion of number; put into the end of the buffer; the
779
         * .01 is added for modf(356.0 / 10, &integer) returning .59999999...
780
         */
781
        for (p = endp - 1; integer; ++expcnt) {
782
                tmp = modf(integer / 10, &integer);
783
                *p-- = to_char((int)((tmp + .01) * 10));
784
        }
785
        switch (fmtch) {
786
        case 'f':
787
                /* reverse integer into beginning of buffer */
788
                if (expcnt)
789
                        for (; ++p < endp; *t++ = *p);
790
                else
791
                        *t++ = '0';
792
                /*
793
                 * if precision required or alternate flag set, add in a
794
                 * decimal point.
795
                 */
796
                if (prec || flags&ALT)
797
                        *t++ = '.';
798
                /* if requires more precision and some fraction left */
799
                if (fract) {
800
                        if (prec)
801
                                do {
802
                                        fract = modf(fract * 10, &tmp);
803
                                        *t++ = to_char((int)tmp);
804
                                } while (--prec && fract);
805
                        if (fract)
806
                                startp = round(fract, (int *)NULL, startp,
807
                                    t - 1, (char)0, signp);
808
                }
809
                for (; prec--; *t++ = '0');
810
                break;
811
        case 'e':
812
        case 'E':
813
eformat:        if (expcnt) {
814
                        *t++ = *++p;
815
                        if (prec || flags&ALT)
816
                                *t++ = '.';
817
                        /* if requires more precision and some integer left */
818
                        for (; prec && ++p < endp; --prec)
819
                                *t++ = *p;
820
                        /*
821
                         * if done precision and more of the integer component,
822
                         * round using it; adjust fract so we don't re-round
823
                         * later.
824
                         */
825
                        if (!prec && ++p < endp) {
826
                                fract = 0;
827
                                startp = round((double)0, &expcnt, startp,
828
                                    t - 1, *p, signp);
829
                        }
830
                        /* adjust expcnt for digit in front of decimal */
831
                        --expcnt;
832
                }
833
                /* until first fractional digit, decrement exponent */
834
                else if (fract) {
835
                        /* adjust expcnt for digit in front of decimal */
836
                        for (expcnt = -1;; --expcnt) {
837
                                fract = modf(fract * 10, &tmp);
838
                                if (tmp)
839
                                        break;
840
                        }
841
                        *t++ = to_char((int)tmp);
842
                        if (prec || flags&ALT)
843
                                *t++ = '.';
844
                }
845
                else {
846
                        *t++ = '0';
847
                        if (prec || flags&ALT)
848
                                *t++ = '.';
849
                }
850
                /* if requires more precision and some fraction left */
851
                if (fract) {
852
                        if (prec)
853
                                do {
854
                                        fract = modf(fract * 10, &tmp);
855
                                        *t++ = to_char((int)tmp);
856
                                } while (--prec && fract);
857
                        if (fract)
858
                                startp = round(fract, &expcnt, startp,
859
                                    t - 1, (char)0, signp);
860
                }
861
                /* if requires more precision */
862
                for (; prec--; *t++ = '0');
863
 
864
                /* unless alternate flag, trim any g/G format trailing 0's */
865
                if (gformat && !(flags&ALT)) {
866
                        while (t > startp && *--t == '0');
867
                        if (*t == '.')
868
                                --t;
869
                        ++t;
870
                }
871
                t = exponent(t, expcnt, fmtch);
872
                break;
873
        case 'g':
874
        case 'G':
875
                /* a precision of 0 is treated as a precision of 1. */
876
                if (!prec)
877
                        ++prec;
878
                /*
879
                 * ``The style used depends on the value converted; style e
880
                 * will be used only if the exponent resulting from the
881
                 * conversion is less than -4 or greater than the precision.''
882
                 *      -- ANSI X3J11
883
                 */
884
                if (expcnt > prec || (!expcnt && fract && fract < .0001)) {
885
                        /*
886
                         * g/G format counts "significant digits, not digits of
887
                         * precision; for the e/E format, this just causes an
888
                         * off-by-one problem, i.e. g/G considers the digit
889
                         * before the decimal point significant and e/E doesn't
890
                         * count it as precision.
891
                         */
892
                        --prec;
893
                        fmtch -= 2;             /* G->E, g->e */
894
                        gformat = 1;
895
                        goto eformat;
896
                }
897
                /*
898
                 * reverse integer into beginning of buffer,
899
                 * note, decrement precision
900
                 */
901
                if (expcnt)
902
                        for (; ++p < endp; *t++ = *p, --prec);
903
                else
904
                        *t++ = '0';
905
                /*
906
                 * if precision required or alternate flag set, add in a
907
                 * decimal point.  If no digits yet, add in leading 0.
908
                 */
909
                if (prec || flags&ALT) {
910
                        dotrim = 1;
911
                        *t++ = '.';
912
                }
913
                else
914
                        dotrim = 0;
915
                /* if requires more precision and some fraction left */
916
                if (fract) {
917
                        if (prec) {
918
                                do {
919
                                        fract = modf(fract * 10, &tmp);
920
                                        *t++ = to_char((int)tmp);
921
                                } while(!tmp);
922
                                while (--prec && fract) {
923
                                        fract = modf(fract * 10, &tmp);
924
                                        *t++ = to_char((int)tmp);
925
                                }
926
                        }
927
                        if (fract)
928
                                startp = round(fract, (int *)NULL, startp,
929
                                    t - 1, (char)0, signp);
930
                }
931
                /* alternate format, adds 0's for precision, else trim 0's */
932
                if (flags&ALT)
933
                        for (; prec--; *t++ = '0');
934
                else if (dotrim) {
935
                        while (t > startp && *--t == '0');
936
                        if (*t != '.')
937
                                ++t;
938
                }
939
        }
940
    } else {
941
        unsigned case_adj;
942
        switch (fmtch) {
943
        case 'f':
944
        case 'g':
945
        case 'e':
946
            case_adj = 'a' - 'A';
947
            break;
948
        default:
949
            case_adj = 0;
950
        }
951
        if (isnan(number)) {
952
            *t++ = 'N' + case_adj;
953
            *t++ = 'A' + case_adj;
954
            *t++ = 'N' + case_adj;
955
        } else { // infinite
956
            *t++ = 'I' + case_adj;
957
            *t++ = 'N' + case_adj;
958
            *t++ = 'F' + case_adj;
959
        }
960
    }
961
    return (t - startp);
962
} // cvt()
963
 
964
#endif // ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
965
 
966
// EOF vfnprintf.cxx

powered by: WebSVN 2.1.0

© copyright 1999-2025 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.