Rework the floating point code in printf(). Significant changes:

- We used to round long double arguments to double.  Now we print
  them properly.

- Bugs involving '%F', corner cases of '#' and 'g' format
  specifiers, and the '.*' precision specifier have been
  fixed.

- Added support for the "'" specifier to print thousands' grouping
  characters in a locale-dependent manner.

- Implement the __vfprintf() side of hexadecimal floating point
  support.  All that is still needed is a routine to convert the
  mantissa to hex digits one nibble at a time in the style of ultoa().

Reviewed by:	silence on standards@
This commit is contained in:
David Schultz 2003-04-05 22:11:42 +00:00
parent 92b93b37c0
commit ebbad5ec5c
2 changed files with 191 additions and 151 deletions

View File

@ -52,3 +52,5 @@
#if LDBL_MAX_EXP > 999999 #if LDBL_MAX_EXP > 999999
#error "floating point buffers too small" #error "floating point buffers too small"
#endif #endif
char *__ldtoa(long double *, int, int, int *, int *, char **);

View File

@ -111,9 +111,9 @@ enum typeid {
static int __sprint(FILE *, struct __suio *); static int __sprint(FILE *, struct __suio *);
static int __sbprintf(FILE *, const char *, va_list) __printflike(2, 0); static int __sbprintf(FILE *, const char *, va_list) __printflike(2, 0);
static char *__ujtoa(uintmax_t, char *, int, int, char *, int, char, static char *__ujtoa(uintmax_t, char *, int, int, const char *, int, char,
const char *); const char *);
static char *__ultoa(u_long, char *, int, int, char *, int, char, static char *__ultoa(u_long, char *, int, int, const char *, int, char,
const char *); const char *);
static char *__wcsconv(wchar_t *, int); static char *__wcsconv(wchar_t *, int);
static void __find_arguments(const char *, va_list, union arg **); static void __find_arguments(const char *, va_list, union arg **);
@ -185,7 +185,7 @@ __sbprintf(FILE *fp, const char *fmt, va_list ap)
* use the given digits. * use the given digits.
*/ */
static char * static char *
__ultoa(u_long val, char *endp, int base, int octzero, char *xdigs, __ultoa(u_long val, char *endp, int base, int octzero, const char *xdigs,
int needgrp, char thousep, const char *grp) int needgrp, char thousep, const char *grp)
{ {
char *cp = endp; char *cp = endp;
@ -262,7 +262,7 @@ __ultoa(u_long val, char *endp, int base, int octzero, char *xdigs,
/* Identical to __ultoa, but for intmax_t. */ /* Identical to __ultoa, but for intmax_t. */
static char * static char *
__ujtoa(uintmax_t val, char *endp, int base, int octzero, char *xdigs, __ujtoa(uintmax_t val, char *endp, int base, int octzero, const char *xdigs,
int needgrp, char thousep, const char *grp) int needgrp, char thousep, const char *grp)
{ {
char *cp = endp; char *cp = endp;
@ -407,15 +407,17 @@ vfprintf(FILE * __restrict fp, const char * __restrict fmt0, va_list ap)
} }
#ifdef FLOATING_POINT #ifdef FLOATING_POINT
#define dtoa __dtoa
#define freedtoa __freedtoa
#include <float.h>
#include <math.h> #include <math.h>
#include "floatio.h" #include "floatio.h"
#include "gdtoa.h"
#define DEFPREC 6 #define DEFPREC 6
extern char *__dtoa(double, int, int, int *, int *, char **);
extern void __freedtoa(char *s);
static char *cvt(double, int, int, char *, int *, int, int *);
static int exponent(char *, int, int); static int exponent(char *, int, int);
#endif /* FLOATING_POINT */ #endif /* FLOATING_POINT */
@ -435,7 +437,6 @@ static int exponent(char *, int, int);
* Flags used during conversion. * Flags used during conversion.
*/ */
#define ALT 0x001 /* alternate form */ #define ALT 0x001 /* alternate form */
#define HEXPREFIX 0x002 /* add 0x or 0X prefix */
#define LADJUST 0x004 /* left adjustment */ #define LADJUST 0x004 /* left adjustment */
#define LONGDBL 0x008 /* long double */ #define LONGDBL 0x008 /* long double */
#define LONGINT 0x010 /* long integer */ #define LONGINT 0x010 /* long integer */
@ -464,19 +465,41 @@ __vfprintf(FILE *fp, const char *fmt0, va_list ap)
int flags; /* flags as above */ int flags; /* flags as above */
int ret; /* return value accumulator */ int ret; /* return value accumulator */
int width; /* width from format (%8d), or 0 */ int width; /* width from format (%8d), or 0 */
int prec; /* precision from format (%.3d), or -1 */ int prec; /* precision from format; <0 for N/A */
char sign; /* sign prefix (' ', '+', '-', or \0) */ char sign; /* sign prefix (' ', '+', '-', or \0) */
char thousands_sep; /* locale specific thousands separator */ char thousands_sep; /* locale specific thousands separator */
const char *grouping; /* locale specific numeric grouping rules */ const char *grouping; /* locale specific numeric grouping rules */
#ifdef FLOATING_POINT #ifdef FLOATING_POINT
/*
* We can decompose the printed representation of floating
* point numbers into several parts, some of which may be empty:
*
* [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
* A B ---C--- D E F
*
* A: 'sign' holds this value if present; '\0' otherwise
* B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
* C: cp points to the string MMMNNN. Leading and trailing
* zeros are not in the string and must be added.
* D: expchar holds this character; '\0' if no exponent, e.g. %f
* F: at least two digits for decimal, at least one digit for hex
*/
char *decimal_point; /* locale specific decimal point */ char *decimal_point; /* locale specific decimal point */
char softsign; /* temporary negative sign for floats */ int signflag; /* true if float is negative */
double _double; /* double precision arguments %[eEfgG] */ union { /* floating point arguments %[aAeEfFgG] */
double dbl;
long double ldbl;
} fparg;
int expt; /* integer value of exponent */ int expt; /* integer value of exponent */
char expchar; /* exponent character: [eEpP\0] */
char *dtoaend; /* pointer to end of converted digits */
int expsize; /* character count for expstr */ int expsize; /* character count for expstr */
int ndig; /* actual number of digits returned by cvt */ int lead; /* sig figs before decimal or group sep */
char expstr[MAXEXPDIG+2]; /* buffer for exponent string */ int ndig; /* actual number of digits returned by dtoa */
char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
char *dtoaresult; /* buffer allocated by dtoa */ char *dtoaresult; /* buffer allocated by dtoa */
int nseps; /* number of group separators with ' */
int nrepeats; /* number of repeats of the last group */
#endif #endif
u_long ulval; /* integer arguments %[diouxX] */ u_long ulval; /* integer arguments %[diouxX] */
uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */ uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
@ -485,12 +508,12 @@ __vfprintf(FILE *fp, const char *fmt0, va_list ap)
int realsz; /* field size expanded by dprec, sign, etc */ int realsz; /* field size expanded by dprec, sign, etc */
int size; /* size of converted field or string */ int size; /* size of converted field or string */
int prsize; /* max size of printed field */ int prsize; /* max size of printed field */
char *xdigs; /* digits for [xX] conversion */ const char *xdigs; /* digits for %[xX] conversion */
#define NIOV 8 #define NIOV 8
struct __suio uio; /* output information: summary */ struct __suio uio; /* output information: summary */
struct __siov iov[NIOV];/* ... and individual io vectors */ struct __siov iov[NIOV];/* ... and individual io vectors */
char buf[BUF]; /* buffer with space for digits of uintmax_t */ char buf[BUF]; /* buffer with space for digits of uintmax_t */
char ox[2]; /* space for 0x hex-prefix */ char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */
union arg *argtable; /* args, built due to positional arg */ union arg *argtable; /* args, built due to positional arg */
union arg statargtable [STATIC_ARG_TBL_SIZE]; union arg statargtable [STATIC_ARG_TBL_SIZE];
int nextarg; /* 1-based argument index */ int nextarg; /* 1-based argument index */
@ -508,6 +531,9 @@ __vfprintf(FILE *fp, const char *fmt0, va_list ap)
static char zeroes[PADSIZE] = static char zeroes[PADSIZE] =
{'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'}; {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
static const char xdigs_lower[16] = "0123456789abcdef";
static const char xdigs_upper[16] = "0123456789ABCDEF";
/* /*
* BEWARE, these `goto error' on error, and PAD uses `n'. * BEWARE, these `goto error' on error, and PAD uses `n'.
*/ */
@ -647,6 +673,7 @@ __vfprintf(FILE *fp, const char *fmt0, va_list ap)
width = 0; width = 0;
prec = -1; prec = -1;
sign = '\0'; sign = '\0';
ox[1] = '\0';
rflag: ch = *fmt++; rflag: ch = *fmt++;
reswitch: switch (ch) { reswitch: switch (ch) {
@ -801,86 +828,122 @@ reswitch: switch (ch) {
#ifdef HEXFLOAT #ifdef HEXFLOAT
case 'a': case 'a':
case 'A': case 'A':
if (ch == 'a') {
ox[1] = 'x';
xdigs = xdigs_lower;
expchar = 'p';
} else {
ox[1] = 'X';
xdigs = xdigs_upper;
expchar = 'P';
}
/*
* XXX We don't actually have a conversion
* XXX routine for this yet.
*/
if (flags & LONGDBL) {
fparg.ldbl = (double)GETARG(long double);
dtoaresult = cp =
__hldtoa(fparg.ldbl, xdigs, prec,
&expt, &signflag, &dtoaend);
} else {
fparg.dbl = GETARG(double);
dtoaresult = cp =
__hdtoa(fparg.dbl, xdigs, prec,
&expt, &signflag, &dtoaend);
}
goto fp_begin;
#endif #endif
case 'e': case 'e':
case 'E': case 'E':
/*- expchar = ch;
* Grouping apply to %i, %d, %u, %f, %F, %g, %G if (prec < 0) /* account for digit before decpt */
* conversion specifiers only. For other conversions prec = DEFPREC + 1;
* behavior is undefined. else
* -- POSIX prec++;
*/ goto fp_begin;
flags &= ~GROUPING;
/*FALLTHROUGH*/
case 'f': case 'f':
case 'F': case 'F':
expchar = '\0';
goto fp_begin; goto fp_begin;
case 'g': case 'g':
case 'G': case 'G':
expchar = ch - ('g' - 'e');
if (prec == 0) if (prec == 0)
prec = 1; prec = 1;
fp_begin: if (prec == -1) fp_begin:
if (prec < 0)
prec = DEFPREC; prec = DEFPREC;
if (flags & LONGDBL) if (dtoaresult != NULL)
/* XXX this loses precision. */ freedtoa(dtoaresult);
_double = (double)GETARG(long double); if (flags & LONGDBL) {
else fparg.ldbl = GETARG(long double);
_double = GETARG(double); dtoaresult = cp =
/* do this before tricky precision changes */ __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
if (isinf(_double)) { &expt, &signflag, &dtoaend);
if (_double < 0) } else {
sign = '-'; fparg.dbl = GETARG(double);
if (isupper(ch)) dtoaresult = cp =
cp = "INF"; dtoa(fparg.dbl, expchar ? 2 : 3, prec,
else &expt, &signflag, &dtoaend);
cp = "inf"; if (expt == 9999)
size = 3; expt = INT_MAX;
break;
} }
if (isnan(_double)) { if (signflag)
if (isupper(ch)) sign = '-';
cp = "NAN"; if (expt == INT_MAX) { /* inf or nan */
else if (*cp == 'N') {
cp = "nan"; cp = (ch >= 'a') ? "nan" : "NAN";
sign = '\0';
} else
cp = (ch >= 'a') ? "inf" : "INF";
size = 3; size = 3;
break; break;
} }
flags |= FPT; flags |= FPT;
if (dtoaresult != NULL) { ndig = dtoaend - cp;
__freedtoa(dtoaresult);
dtoaresult = NULL;
}
dtoaresult = cp = cvt(_double, prec, flags, &softsign,
&expt, ch, &ndig);
if (ch == 'g' || ch == 'G') { if (ch == 'g' || ch == 'G') {
if (expt <= -4 || expt > prec) if (expt > -4 && expt <= prec) {
ch = (ch == 'g') ? 'e' : 'E'; /* Make %[gG] smell like %[fF] */
else expchar = '\0';
ch = 'g'; if (flags & ALT)
prec -= expt;
else
prec = ndig - expt;
if (prec < 0)
prec = 0;
}
} }
if (ch == 'e' || ch == 'E') { if (expchar) {
--expt; expsize = exponent(expstr, expt - 1, expchar);
expsize = exponent(expstr, expt, ch); size = expsize + prec;
size = expsize + ndig; if (prec || flags & ALT)
if (ndig > 1 || flags & ALT)
++size; ++size;
} else if (ch == 'f' || ch == 'F') { } else {
if (expt > 0) { if (expt > 0) {
size = expt; size = expt;
if (prec || flags & ALT) if (prec || flags & ALT)
size += prec + 1; size += prec + 1;
} else /* "0.X" */ } else /* "0.X" */
size = prec + 2; size = prec + 2;
} else if (expt >= ndig) { /* fixed g fmt */ if (grouping && expt > 0) {
size = expt; /* space for thousands' grouping */
if (flags & ALT) nseps = nrepeats = 0;
++size; lead = expt;
} else while (*grouping != CHAR_MAX) {
size = ndig + (expt > 0 ? if (lead <= *grouping)
1 : 2 - expt); break;
lead -= *grouping;
if (softsign) if (*(grouping+1)) {
sign = '-'; nseps++;
grouping++;
} else
nrepeats++;
}
size += nseps + nrepeats;
} else
lead = (expt < ndig) ? expt : ndig;
}
break; break;
#endif /* FLOATING_POINT */ #endif /* FLOATING_POINT */
case 'n': case 'n':
@ -926,9 +989,9 @@ fp_begin: if (prec == -1)
*/ */
ujval = (uintmax_t)(uintptr_t)GETARG(void *); ujval = (uintmax_t)(uintptr_t)GETARG(void *);
base = 16; base = 16;
xdigs = "0123456789abcdef"; xdigs = xdigs_lower;
flags = flags | INTMAXT | HEXPREFIX; flags = flags | INTMAXT;
ch = 'x'; ox[1] = 'x';
goto nosign; goto nosign;
case 'S': case 'S':
flags |= LONGINT; flags |= LONGINT;
@ -980,10 +1043,10 @@ fp_begin: if (prec == -1)
base = 10; base = 10;
goto nosign; goto nosign;
case 'X': case 'X':
xdigs = "0123456789ABCDEF"; xdigs = xdigs_upper;
goto hex; goto hex;
case 'x': case 'x':
xdigs = "0123456789abcdef"; xdigs = xdigs_lower;
hex: hex:
if (flags & INTMAX_SIZE) if (flags & INTMAX_SIZE)
ujval = UJARG(); ujval = UJARG();
@ -993,7 +1056,7 @@ fp_begin: if (prec == -1)
/* leading 0x/X only if non-zero */ /* leading 0x/X only if non-zero */
if (flags & ALT && if (flags & ALT &&
(flags & INTMAX_SIZE ? ujval != 0 : ulval != 0)) (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
flags |= HEXPREFIX; ox[1] = ch;
flags &= ~GROUPING; flags &= ~GROUPING;
/* unsigned conversions */ /* unsigned conversions */
@ -1057,7 +1120,7 @@ number: if ((dprec = prec) >= 0)
realsz = dprec > size ? dprec : size; realsz = dprec > size ? dprec : size;
if (sign) if (sign)
realsz++; realsz++;
else if (flags & HEXPREFIX) else if (ox[1])
realsz += 2; realsz += 2;
prsize = width > realsz ? width : realsz; prsize = width > realsz ? width : realsz;
@ -1073,9 +1136,8 @@ number: if ((dprec = prec) >= 0)
/* prefix */ /* prefix */
if (sign) { if (sign) {
PRINT(&sign, 1); PRINT(&sign, 1);
} else if (flags & HEXPREFIX) { } else if (ox[1]) { /* ox[1] is either x, X, or \0 */
ox[0] = '0'; ox[0] = '0';
ox[1] = ch;
PRINT(ox, 2); PRINT(ox, 2);
} }
@ -1091,42 +1153,49 @@ number: if ((dprec = prec) >= 0)
if ((flags & FPT) == 0) { if ((flags & FPT) == 0) {
PRINT(cp, size); PRINT(cp, size);
} else { /* glue together f_p fragments */ } else { /* glue together f_p fragments */
if (ch >= 'f') { /* 'f' or 'g' */ if (!expchar) { /* %[fF] or sufficiently short %[gG] */
if (_double == 0) { if (expt <= 0) {
/* kludge for __dtoa irregularity */ buf[0] = '0';
PRINT("0", 1); buf[1] = *decimal_point;
if (expt < ndig || (flags & ALT) != 0) { PRINT(buf, 2);
PRINT(decimal_point, 1);
PAD(ndig - 1, zeroes);
}
} else if (expt <= 0) {
PRINT("0", 1);
PRINT(decimal_point, 1);
PAD(-expt, zeroes); PAD(-expt, zeroes);
PRINT(cp, ndig); if (ndig > 0)
} else if (expt >= ndig) { PRINT(cp, ndig);
PRINT(cp, ndig);
PAD(expt - ndig, zeroes);
if (flags & ALT)
PRINT(decimal_point, 1);
} else { } else {
PRINT(cp, expt); PRINT(cp, lead);
cp += expt; cp += lead;
PRINT(decimal_point, 1); if (grouping) {
PRINT(cp, ndig-expt); while (nseps>0 || nrepeats>0) {
if (nrepeats > 0)
nrepeats--;
else {
grouping--;
nseps--;
}
PRINT(&thousands_sep,
1);
PRINT(cp, *grouping);
cp += *grouping;
}
} else {
PAD(expt - lead, zeroes);
}
if (prec || flags & ALT)
PRINT(decimal_point,1);
if (ndig > lead)
PRINT(cp, ndig - lead);
} }
} else { /* 'e' or 'E' */ PAD(prec - ndig + expt, zeroes);
if (ndig > 1 || flags & ALT) { } else { /* %[eE] or sufficiently long %[gG] */
ox[0] = *cp++; if (prec || flags & ALT) {
ox[1] = *decimal_point; buf[0] = *cp++;
PRINT(ox, 2); buf[1] = *decimal_point;
if (_double) { PRINT(buf, 2);
PRINT(cp, ndig-1); PRINT(cp, ndig-1);
} else /* 0.[0..] */ PAD(prec - ndig, zeroes);
/* __dtoa irregularity */
PAD(ndig - 1, zeroes);
} else /* XeYYY */ } else /* XeYYY */
PRINT(cp, 1); PRINT(cp, 1);
PRINT(expstr, expsize); PRINT(expstr, expsize);
} }
} }
@ -1147,7 +1216,7 @@ number: if ((dprec = prec) >= 0)
error: error:
#ifdef FLOATING_POINT #ifdef FLOATING_POINT
if (dtoaresult != NULL) if (dtoaresult != NULL)
__freedtoa(dtoaresult); freedtoa(dtoaresult);
#endif #endif
if (convbuf != NULL) if (convbuf != NULL)
free(convbuf); free(convbuf);
@ -1517,44 +1586,6 @@ __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
#ifdef FLOATING_POINT #ifdef FLOATING_POINT
static char *
cvt(double value, int ndigits, int flags, char *sign, int *decpt,
int ch, int *length)
{
int mode, dsgn;
char *digits, *bp, *rve;
if (ch == 'f')
mode = 3; /* ndigits after the decimal point */
else {
/*
* To obtain ndigits after the decimal point for the 'e'
* and 'E' formats, round to ndigits + 1 significant
* figures.
*/
if (ch == 'e' || ch == 'E')
ndigits++;
mode = 2; /* ndigits significant digits */
}
digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
*sign = dsgn != 0;
if ((ch != 'g' && ch != 'G') || flags & ALT) {
/* print trailing zeros */
bp = digits + ndigits;
if (ch == 'f') {
if ((*digits == '0' || *digits == '\0') && value)
*decpt = -ndigits + 1;
bp += *decpt;
}
if (value == 0) /* kludge for __dtoa irregularity */
rve = bp;
while (rve < bp)
*rve++ = '0';
}
*length = rve - digits;
return (digits);
}
static int static int
exponent(char *p0, int exp, int fmtch) exponent(char *p0, int exp, int fmtch)
{ {
@ -1578,7 +1609,14 @@ exponent(char *p0, int exp, int fmtch)
for (; t < expbuf + MAXEXPDIG; *p++ = *t++); for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
} }
else { else {
*p++ = '0'; /*
* Exponents for decimal floating point conversions
* (%[eEgG]) must be at least two characters long,
* whereas exponents for hexadecimal conversions can
* be only one character long.
*/
if (fmtch == 'e' || fmtch == 'E')
*p++ = '0';
*p++ = to_char(exp); *p++ = to_char(exp);
} }
return (p - p0); return (p - p0);