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

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [rtos/] [ecos-3.0/] [packages/] [language/] [c/] [libc/] [stdio/] [current/] [src/] [output/] [vfnprintf.cxx] - Blame information for rev 786

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

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