1 //===========================================================================
5 // I/O routines for vfnprintf() for use with ANSI C library
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.
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.
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
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.
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.
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.
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####
43 // Author(s): jlarmour
50 //####DESCRIPTIONEND####
52 //===========================================================================
54 // This code is based on original code with the following copyright:
57 * Copyright (c) 1990 The Regents of the University of California.
58 * All rights reserved.
60 * This code is derived from software contributed to Berkeley by
63 * Redistribution and use in source and binary forms, with or without
64 * modification, are permitted provided that the following conditions
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.
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
91 #include <pkgconf/libc_stdio.h> // Configuration header
92 #include <pkgconf/libc_i18n.h> // Configuration header for mb support
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
102 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
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
108 # define MAXFRACT DBL_DIG
109 # define MAXEXP DBL_MAX_10_EXP
111 # define BUF (MAXEXP+MAXFRACT+1) /* + decimal point */
115 cvt( double, int, int, char *, int, char *, char * );
117 #else // ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
121 #endif // ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
124 * Actual printf innards.
126 * This code is large and complicated...
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();
135 * Macros for converting digits to letters and vice versa
137 #define to_digit(c) ((c) - '0')
138 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
139 #define to_char(n) ((n) + '0')
142 * Flags used during conversion.
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 */
156 vfnprintf ( FILE *stream, size_t n, const char *format, va_list arg) __THROW
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 */
164 #ifdef CYGINT_LIBC_I18N_MB_REQUIRED
165 int state = 0; /* state for mbtowc conversion */
166 mbtowc_fn_type mbtowc_fn;
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) */
175 #define quad_t long long
176 #define u_quad_t unsigned long long
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 */
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] */
195 * Choose PADSIZE to trade efficiency vs. size. If larger printf
196 * fields occur frequently, increase PADSIZE and make the initialisers
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'};
205 #define MIN(a, b) ((a) < (b) ? (a) : (b))
208 * BEWARE, these `goto error' on error, and PAD uses `n'.
210 #define PRINT(ptr, len) \
212 cyg_ucount32 length = MIN( (cyg_ucount32) len, n - ret - 1); \
213 if (((Cyg_StdioStream *)stream)->write( (const cyg_uint8 *)ptr, \
216 if (length < (cyg_ucount32)len) { \
223 #define PAD(howmany, with) \
225 if ((x = (howmany)) > 0) { \
226 while (x > PADSIZE) { \
227 PRINT(with, PADSIZE); \
235 * To extend shorts properly, we need both signed and unsigned
236 * argument extraction methods.
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))
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))
253 xdigs = NULL; // stop compiler whinging
254 fmt = (char *)format;
256 #ifdef CYGINT_LIBC_I18N_MB_REQUIRED
257 mbtowc_fn = __get_current_locale_mbtowc_fn();
261 * Scan the format for conversions (`%' character).
265 #ifndef CYGINT_LIBC_I18N_MB_REQUIRED
266 while ((x = ((wc = *fmt) != 0))) {
268 while ((x = mbtowc_fn (&wc, fmt, MB_CUR_MAX, &state)) > 0) {
276 if ((y = fmt - cp) != 0) {
280 if ((x <= 0) || (ret >= (int)n)) // @@@ this check with n isn't good enough
282 fmt++; /* skip over '%' */
286 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
294 reswitch: switch (ch) {
297 * ``If the space and + flags both appear, the space
298 * flag will be ignored.''
309 * ``A negative field width argument is taken as a
310 * - flag followed by a positive field width.''
312 * They don't exclude field widths read from args.
314 if ((width = va_arg(arg, int)) >= 0)
325 if ((ch = *fmt++) == '*') {
326 x = va_arg(arg, int);
327 prec = x < 0 ? -1 : x;
331 while (is_digit(ch)) {
332 x = 10 * x + to_digit(ch);
335 prec = x < 0 ? -1 : x;
339 * ``Note that 0 is taken as a flag, not as the
340 * beginning of a field width.''
345 case '1': case '2': case '3': case '4':
346 case '5': case '6': case '7': case '8': case '9':
349 x = 10 * x + to_digit(ch);
351 } while (is_digit(ch));
354 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
374 *(cp = buf) = va_arg(arg, int);
385 if ((quad_t)_uquad < 0)
387 if ((long) _uquad < 0)
397 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
403 _double = va_arg(arg, double);
405 * don't do unrealistic precision; just pad it with
406 * zeroes later, so buffer size stays rational.
408 if (prec > MAXFRACT) {
409 if ((ch != 'g' && ch != 'G') || (flags&ALT))
410 fpprec = prec - MAXFRACT;
412 } else if (prec == -1)
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.
423 size = cvt(_double, prec, flags, &softsign, ch,
424 cp, buf + sizeof(buf));
436 // Output nothing at all
437 (void) va_arg(arg, double); // take off arg anyway
444 #endif // ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
449 *va_arg(arg, quad_t *) = ret;
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;
459 *va_arg(arg, int *) = ret;
460 continue; /* no output */
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-
477 _uquad = (unsigned long)va_arg(arg, void *);
479 xdigs = "0123456789abcdef";
484 if ((cp = va_arg(arg, char *)) == NULL)
488 * can't use strlen; can only look for the
489 * NUL in the first `prec' characters, and
490 * strlen() will go further.
492 char *p = (char *)memchr(cp, 0, prec);
512 xdigs = "0123456789ABCDEF";
515 xdigs = "0123456789abcdef";
516 hex: _uquad = UARG();
518 /* leading 0x/X only if non-zero */
519 if (flags & ALT && _uquad != 0)
522 /* unsigned conversions */
525 * ``... diouXx conversions ... if a precision is
526 * specified, the 0 flag will be ignored.''
529 number: if ((dprec = prec) >= 0)
533 * ``The result of converting a zero value with an
534 * explicit precision of zero is no characters.''
538 if (_uquad != 0 || prec != 0) {
540 * Unsigned mod is hard, and unsigned mod
541 * by a constant is easier than that by
542 * a variable; hence this switch.
547 *--cp = to_char(_uquad & 7);
550 /* handle octal leading 0 */
551 if (flags & ALT && *cp != '0')
556 /* many numbers are 1 digit */
557 while (_uquad >= 10) {
558 *--cp = to_char(_uquad % 10);
561 *--cp = to_char(_uquad);
566 *--cp = xdigs[_uquad & 15];
572 cp = "bug in vfprintf: bad base";
577 size = buf + BUF - cp;
583 default: /* "%?" prints ?, unless ? is NUL */
586 /* pretend it was %c with argument ch */
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.
605 * Compute actual size, so we know how much to pad.
606 * fieldsz excludes decimal prec; realsz includes it.
608 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
609 fieldsz = size + fpprec;
615 else if (flags & HEXPREFIX)
617 realsz = dprec > fieldsz ? dprec : fieldsz;
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;
631 } else if (flags & HEXPREFIX) {
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;
646 if (dprec - fieldsz > 0) {
647 /* leading zeroes from decimal precision */
648 PAD(dprec - fieldsz, zeroes);
649 ret += dprec - fieldsz;
652 /* the string or number proper */
656 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
657 /* trailing f.p. zeroes */
662 /* left-adjusting padding (always blank) */
663 if (flags & LADJUST) {
664 if (width - realsz > 0) {
665 PAD(width - realsz, blanks);
666 ret += width - realsz;
673 return (((Cyg_StdioStream *) stream)->get_error() ? EOF : ret);
678 #ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT
681 round(double fract, int *exp, char *start, char *end, char ch, char *signp)
686 (void)modf(fract * 10, &tmp);
697 if (exp) { /* e/E; increment exponent */
701 else { /* f; add extra digit */
708 /* ``"%.3f", (double)-0.0004'' gives you a negative 0. */
709 else if (*signp == '-')
723 exponent(char *p, int exp, int fmtch)
738 *--t = to_char(exp % 10);
739 } while ((exp /= 10) > 9);
741 for (; t < expbuf + MAXEXP; *p++ = *t++);
752 cvt(double number, int prec, int flags, char *signp, int fmtch, char *startp,
755 Cyg_libm_ieee_double_shape_type ieeefp;
758 ieeefp.value = number;
760 if ( ieeefp.number.sign ){ // this checks for <0.0 and -0.0
765 if (finite(number)) {
768 int dotrim, expcnt, gformat;
771 dotrim = expcnt = gformat = 0;
772 fract = modf(number, &integer);
774 /* get an extra slot for rounding. */
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...
781 for (p = endp - 1; integer; ++expcnt) {
782 tmp = modf(integer / 10, &integer);
783 *p-- = to_char((int)((tmp + .01) * 10));
787 /* reverse integer into beginning of buffer */
789 for (; ++p < endp; *t++ = *p);
793 * if precision required or alternate flag set, add in a
796 if (prec || flags&ALT)
798 /* if requires more precision and some fraction left */
802 fract = modf(fract * 10, &tmp);
803 *t++ = to_char((int)tmp);
804 } while (--prec && fract);
806 startp = round(fract, (int *)NULL, startp,
807 t - 1, (char)0, signp);
809 for (; prec--; *t++ = '0');
813 eformat: if (expcnt) {
815 if (prec || flags&ALT)
817 /* if requires more precision and some integer left */
818 for (; prec && ++p < endp; --prec)
821 * if done precision and more of the integer component,
822 * round using it; adjust fract so we don't re-round
825 if (!prec && ++p < endp) {
827 startp = round((double)0, &expcnt, startp,
830 /* adjust expcnt for digit in front of decimal */
833 /* until first fractional digit, decrement exponent */
835 /* adjust expcnt for digit in front of decimal */
836 for (expcnt = -1;; --expcnt) {
837 fract = modf(fract * 10, &tmp);
841 *t++ = to_char((int)tmp);
842 if (prec || flags&ALT)
847 if (prec || flags&ALT)
850 /* if requires more precision and some fraction left */
854 fract = modf(fract * 10, &tmp);
855 *t++ = to_char((int)tmp);
856 } while (--prec && fract);
858 startp = round(fract, &expcnt, startp,
859 t - 1, (char)0, signp);
861 /* if requires more precision */
862 for (; prec--; *t++ = '0');
864 /* unless alternate flag, trim any g/G format trailing 0's */
865 if (gformat && !(flags&ALT)) {
866 while (t > startp && *--t == '0');
871 t = exponent(t, expcnt, fmtch);
875 /* a precision of 0 is treated as a precision of 1. */
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.''
884 if (expcnt > prec || (!expcnt && fract && fract < .0001)) {
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.
893 fmtch -= 2; /* G->E, g->e */
898 * reverse integer into beginning of buffer,
899 * note, decrement precision
902 for (; ++p < endp; *t++ = *p, --prec);
906 * if precision required or alternate flag set, add in a
907 * decimal point. If no digits yet, add in leading 0.
909 if (prec || flags&ALT) {
915 /* if requires more precision and some fraction left */
919 fract = modf(fract * 10, &tmp);
920 *t++ = to_char((int)tmp);
922 while (--prec && fract) {
923 fract = modf(fract * 10, &tmp);
924 *t++ = to_char((int)tmp);
928 startp = round(fract, (int *)NULL, startp,
929 t - 1, (char)0, signp);
931 /* alternate format, adds 0's for precision, else trim 0's */
933 for (; prec--; *t++ = '0');
935 while (t > startp && *--t == '0');
946 case_adj = 'a' - 'A';
952 *t++ = 'N' + case_adj;
953 *t++ = 'A' + case_adj;
954 *t++ = 'N' + case_adj;
956 *t++ = 'I' + case_adj;
957 *t++ = 'N' + case_adj;
958 *t++ = 'F' + case_adj;
964 #endif // ifdef CYGSEM_LIBC_STDIO_PRINTF_FLOATING_POINT