vfprintf.c revision 1.52 1 /* $NetBSD: vfprintf.c,v 1.52 2006/10/28 14:38:55 christos Exp $ */
2
3 /*-
4 * Copyright (c) 1990 The Regents of the University of California.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Chris Torek.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 #include <sys/cdefs.h>
36 #if defined(LIBC_SCCS) && !defined(lint)
37 #if 0
38 static char *sccsid = "@(#)vfprintf.c 5.50 (Berkeley) 12/16/92";
39 #else
40 __RCSID("$NetBSD: vfprintf.c,v 1.52 2006/10/28 14:38:55 christos Exp $");
41 #endif
42 #endif /* LIBC_SCCS and not lint */
43
44 /*
45 * Actual printf innards.
46 *
47 * This code is large and complicated...
48 */
49
50 #include "namespace.h"
51 #include <sys/types.h>
52
53 #include <assert.h>
54 #include <errno.h>
55 #include <stdarg.h>
56 #include <stddef.h>
57 #include <stdint.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <wchar.h>
62
63 #include "reentrant.h"
64 #include "local.h"
65 #include "fvwrite.h"
66 #include "extern.h"
67
68 static int __sprint __P((FILE *, struct __suio *));
69 static int __sbprintf __P((FILE *, const char *, va_list))
70 __attribute__((__format__(__printf__, 2, 0)));
71
72 /*
73 * Flush out all the vectors defined by the given uio,
74 * then reset it so that it can be reused.
75 */
76 /* NB: async-signal-safe when fp->_flags & __SAFE */
77 static int
78 __sprint(fp, uio)
79 FILE *fp;
80 struct __suio *uio;
81 {
82 int err;
83
84 _DIAGASSERT(fp != NULL);
85 _DIAGASSERT(uio != NULL);
86
87 if (uio->uio_resid == 0) {
88 uio->uio_iovcnt = 0;
89 return (0);
90 }
91 err = __sfvwrite(fp, uio);
92 uio->uio_resid = 0;
93 uio->uio_iovcnt = 0;
94 return (err);
95 }
96
97 /*
98 * Helper function for `fprintf to unbuffered unix file': creates a
99 * temporary buffer. We only work on write-only files; this avoids
100 * worries about ungetc buffers and so forth.
101 */
102 static int
103 __sbprintf(fp, fmt, ap)
104 FILE *fp;
105 const char *fmt;
106 va_list ap;
107 {
108 int ret;
109 FILE fake;
110 struct __sfileext fakeext;
111 unsigned char buf[BUFSIZ];
112
113 _DIAGASSERT(fp != NULL);
114 _DIAGASSERT(fmt != NULL);
115
116 _FILEEXT_SETUP(&fake, &fakeext);
117
118 /* copy the important variables */
119 fake._flags = fp->_flags & ~__SNBF;
120 fake._file = fp->_file;
121 fake._cookie = fp->_cookie;
122 fake._write = fp->_write;
123
124 /* set up the buffer */
125 fake._bf._base = fake._p = buf;
126 fake._bf._size = fake._w = sizeof(buf);
127 fake._lbfsize = 0; /* not actually used, but Just In Case */
128
129 /* do the work, then copy any error status */
130 ret = vfprintf(&fake, fmt, ap);
131 if (ret >= 0 && fflush(&fake))
132 ret = -1;
133 if (fake._flags & __SERR)
134 fp->_flags |= __SERR;
135 return (ret);
136 }
137
138
139 #ifndef NO_FLOATING_POINT
140 #include <locale.h>
141 #include <math.h>
142 #include "floatio.h"
143
144 #define BUF (MAXEXP+MAXFRACT+1) /* + decimal point */
145 #define DEFPREC 6
146
147 static char *cvt __P((double, int, int, char *, int *, int, int *));
148 static int exponent __P((char *, int, int));
149
150 #else /* FLOATING_POINT */
151
152 #define BUF 40
153
154 #endif /* NO_FLOATING_POINT */
155
156 /*
157 * Macros for converting digits to letters and vice versa
158 */
159 #define to_digit(c) ((c) - '0')
160 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
161 #define to_char(n) ((char)((n) + '0'))
162
163 /*
164 * Flags used during conversion.
165 */
166 #define ALT 0x001 /* alternate form */
167 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
168 #define LADJUST 0x004 /* left adjustment */
169 #define LONGDBL 0x008 /* long double; unimplemented */
170 #define LONGINT 0x010 /* long integer */
171 #define QUADINT 0x020 /* quad integer */
172 #define SHORTINT 0x040 /* short integer */
173 #define MAXINT 0x080 /* (unsigned) intmax_t */
174 #define PTRINT 0x100 /* (unsigned) ptrdiff_t */
175 #define SIZEINT 0x200 /* (signed) size_t */
176 #define ZEROPAD 0x400 /* zero (as opposed to blank) pad */
177 #define FPT 0x800 /* Floating point number */
178
179 int
180 vfprintf(fp, fmt0, ap)
181 FILE *fp;
182 const char *fmt0;
183 _BSD_VA_LIST_ ap;
184 {
185 int ret;
186
187 FLOCKFILE(fp);
188 ret = __vfprintf_unlocked(fp, fmt0, ap);
189 FUNLOCKFILE(fp);
190
191 return ret;
192 }
193
194
195
196 /* NB: async-signal-safe when fp->_flags & __SAFE */
197 int
198 __vfprintf_unlocked(fp, fmt0, ap)
199 FILE *fp;
200 const char *fmt0;
201 _BSD_VA_LIST_ ap;
202 {
203 const char *fmt;/* format string */
204 int ch; /* character from fmt */
205 int n, m; /* handy integers (short term usage) */
206 const char *cp; /* handy char pointer (short term usage) */
207 char *bp; /* handy char pointer (short term usage) */
208 struct __siov *iovp;/* for PRINT macro */
209 int flags; /* flags as above */
210 int ret; /* return value accumulator */
211 int width; /* width from format (%8d), or 0 */
212 int prec; /* precision from format (%.3d), or -1 */
213 char sign; /* sign prefix (' ', '+', '-', or \0) */
214 wchar_t wc;
215 mbstate_t ps;
216 #ifndef NO_FLOATING_POINT
217 char *decimal_point;
218 char softsign; /* temporary negative sign for floats */
219 double _double; /* double precision arguments %[eEfgG] */
220 int expt; /* integer value of exponent */
221 int expsize = 0; /* character count for expstr */
222 int ndig; /* actual number of digits returned by cvt */
223 char expstr[7]; /* buffer for exponent string */
224 char *dtoaresult = NULL;
225 #endif
226
227 #ifdef __GNUC__ /* gcc has builtin quad type (long long) SOS */
228 #define quad_t long long
229 #define u_quad_t unsigned long long
230 #endif
231
232 #define INTMAX_T intmax_t
233 #define UINTMAX_T uintmax_t
234
235 UINTMAX_T _uintmax; /* integer arguments %[diouxX] */
236 enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
237 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
238 int realsz; /* field size expanded by dprec */
239 int size; /* size of converted field or string */
240 const char *xdigs = NULL;/* digits for [xX] conversion */
241 #define NIOV 8
242 struct __suio uio; /* output information: summary */
243 struct __siov iov[NIOV];/* ... and individual io vectors */
244 char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
245 char ox[2]; /* space for 0x hex-prefix */
246
247 /*
248 * Choose PADSIZE to trade efficiency vs. size. If larger printf
249 * fields occur frequently, increase PADSIZE and make the initialisers
250 * below longer.
251 */
252 #define PADSIZE 16 /* pad chunk size */
253 static const char blanks[PADSIZE] =
254 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
255 static const char zeroes[PADSIZE] =
256 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
257
258 /*
259 * BEWARE, these `goto error' on error, and PAD uses `n'.
260 */
261 #define PRINT(ptr, len) { \
262 iovp->iov_base = __UNCONST(ptr); \
263 iovp->iov_len = (len); \
264 uio.uio_resid += (len); \
265 iovp++; \
266 if (++uio.uio_iovcnt >= NIOV) { \
267 if (__sprint(fp, &uio)) \
268 goto error; \
269 iovp = iov; \
270 } \
271 }
272 #define PAD(howmany, with) { \
273 if ((n = (howmany)) > 0) { \
274 while (n > PADSIZE) { \
275 PRINT(with, PADSIZE); \
276 n -= PADSIZE; \
277 } \
278 PRINT(with, n); \
279 } \
280 }
281 #define FLUSH() { \
282 if (uio.uio_resid && __sprint(fp, &uio)) \
283 goto error; \
284 uio.uio_iovcnt = 0; \
285 iovp = iov; \
286 }
287
288 /*
289 * To extend shorts properly, we need both signed and unsigned
290 * argument extraction methods.
291 */
292 #define SARG() \
293 (flags&MAXINT ? va_arg(ap, intmax_t) : \
294 flags&PTRINT ? va_arg(ap, ptrdiff_t) : \
295 flags&SIZEINT ? va_arg(ap, ssize_t) : /* XXX */ \
296 flags&QUADINT ? va_arg(ap, quad_t) : \
297 flags&LONGINT ? va_arg(ap, long) : \
298 flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
299 (long)va_arg(ap, int))
300 #define UARG() \
301 (flags&MAXINT ? va_arg(ap, uintmax_t) : \
302 flags&PTRINT ? va_arg(ap, uintptr_t) : /* XXX */ \
303 flags&SIZEINT ? va_arg(ap, size_t) : \
304 flags&QUADINT ? va_arg(ap, u_quad_t) : \
305 flags&LONGINT ? va_arg(ap, u_long) : \
306 flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
307 (u_long)va_arg(ap, u_int))
308
309 _DIAGASSERT(fp != NULL);
310 _DIAGASSERT(fmt0 != NULL);
311
312 _SET_ORIENTATION(fp, -1);
313
314 /* sorry, fprintf(read_only_file, "") returns -1, not 0 */
315 if (cantwrite(fp)) {
316 errno = EBADF;
317 return (-1);
318 }
319
320 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
321 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
322 fp->_file >= 0) {
323 ret = __sbprintf(fp, fmt0, ap);
324 return (ret);
325 }
326
327 fmt = fmt0;
328 uio.uio_iov = iovp = iov;
329 uio.uio_resid = 0;
330 uio.uio_iovcnt = 0;
331 ret = 0;
332
333 memset(&ps, 0, sizeof(ps));
334
335 /*
336 * Scan the format for conversions (`%' character).
337 */
338 for (;;) {
339 cp = fmt;
340 if (fp->_flags & __SAFE) {
341 for (; *fmt &&*fmt != '%'; fmt++)
342 continue;
343 } else {
344 while ((n = mbrtowc(&wc, fmt, MB_CUR_MAX, &ps)) > 0) {
345 fmt += n;
346 if (wc == '%') {
347 fmt--;
348 break;
349 }
350 }
351 }
352 if ((m = fmt - cp) != 0) {
353 PRINT(cp, m);
354 ret += m;
355 }
356 if (n <= 0)
357 goto done;
358 fmt++; /* skip over '%' */
359
360 flags = 0;
361 dprec = 0;
362 width = 0;
363 prec = -1;
364 sign = '\0';
365
366 rflag: ch = *fmt++;
367 reswitch: switch (ch) {
368 case ' ':
369 /*
370 * ``If the space and + flags both appear, the space
371 * flag will be ignored.''
372 * -- ANSI X3J11
373 */
374 if (!sign)
375 sign = ' ';
376 goto rflag;
377 case '#':
378 flags |= ALT;
379 goto rflag;
380 case '*':
381 /*
382 * ``A negative field width argument is taken as a
383 * - flag followed by a positive field width.''
384 * -- ANSI X3J11
385 * They don't exclude field widths read from args.
386 */
387 if ((width = va_arg(ap, int)) >= 0)
388 goto rflag;
389 width = -width;
390 /* FALLTHROUGH */
391 case '-':
392 flags |= LADJUST;
393 goto rflag;
394 case '+':
395 sign = '+';
396 goto rflag;
397 case '.':
398 if ((ch = *fmt++) == '*') {
399 n = va_arg(ap, int);
400 prec = n < 0 ? -1 : n;
401 goto rflag;
402 }
403 n = 0;
404 while (is_digit(ch)) {
405 n = 10 * n + to_digit(ch);
406 ch = *fmt++;
407 }
408 prec = n < 0 ? -1 : n;
409 goto reswitch;
410 case '0':
411 /*
412 * ``Note that 0 is taken as a flag, not as the
413 * beginning of a field width.''
414 * -- ANSI X3J11
415 */
416 flags |= ZEROPAD;
417 goto rflag;
418 case '1': case '2': case '3': case '4':
419 case '5': case '6': case '7': case '8': case '9':
420 n = 0;
421 do {
422 n = 10 * n + to_digit(ch);
423 ch = *fmt++;
424 } while (is_digit(ch));
425 width = n;
426 goto reswitch;
427 #ifndef NO_FLOATING_POINT
428 case 'L':
429 flags |= LONGDBL;
430 goto rflag;
431 #endif
432 case 'h':
433 flags |= SHORTINT;
434 goto rflag;
435 case 'j':
436 flags |= MAXINT;
437 goto rflag;
438 case 'l':
439 if (*fmt == 'l') {
440 fmt++;
441 flags |= QUADINT;
442 } else {
443 flags |= LONGINT;
444 }
445 goto rflag;
446 case 'q':
447 flags |= QUADINT;
448 goto rflag;
449 case 't':
450 flags |= PTRINT;
451 goto rflag;
452 case 'z':
453 flags |= SIZEINT;
454 goto rflag;
455 case 'c':
456 *buf = va_arg(ap, int);
457 cp = buf;
458 size = 1;
459 sign = '\0';
460 break;
461 case 'D':
462 flags |= LONGINT;
463 /*FALLTHROUGH*/
464 case 'd':
465 case 'i':
466 _uintmax = SARG();
467 if ((intmax_t)_uintmax < 0) {
468 _uintmax = -_uintmax;
469 sign = '-';
470 }
471 base = DEC;
472 goto number;
473 #ifndef NO_FLOATING_POINT
474 case 'e':
475 case 'E':
476 case 'f':
477 case 'F':
478 case 'g':
479 case 'G':
480 if (prec == -1) {
481 prec = DEFPREC;
482 } else if ((ch == 'g' || ch == 'G') && prec == 0) {
483 prec = 1;
484 }
485
486 if (flags & LONGDBL) {
487 _double = (double) va_arg(ap, long double);
488 } else {
489 _double = va_arg(ap, double);
490 }
491
492 /* do this before tricky precision changes */
493 if (isinf(_double)) {
494 if (_double < 0)
495 sign = '-';
496 if (ch == 'E' || ch == 'F' || ch == 'G')
497 cp = "INF";
498 else
499 cp = "inf";
500 size = 3;
501 break;
502 }
503 if (isnan(_double)) {
504 if (ch == 'E' || ch == 'F' || ch == 'G')
505 cp = "NAN";
506 else
507 cp = "nan";
508 size = 3;
509 break;
510 }
511 if (fp->_flags & __SAFE) {
512 if (ch == 'E' || ch == 'F' || ch == 'G')
513 cp = "UNK";
514 else
515 cp = "unk";
516 size = 3;
517 break;
518 }
519
520 flags |= FPT;
521 if (dtoaresult)
522 __freedtoa(dtoaresult);
523 cp = dtoaresult = cvt(_double, prec, flags, &softsign,
524 &expt, ch, &ndig);
525 if (ch == 'g' || ch == 'G') {
526 if (expt <= -4 || expt > prec)
527 ch = (ch == 'g') ? 'e' : 'E';
528 else
529 ch = 'g';
530 }
531 if (ch == 'e' || ch == 'E') {
532 --expt;
533 expsize = exponent(expstr, expt, ch);
534 size = expsize + ndig;
535 if (ndig > 1 || flags & ALT)
536 ++size;
537 } else if (ch == 'f' || ch == 'F') {
538 if (expt > 0) {
539 size = expt;
540 if (prec || flags & ALT)
541 size += prec + 1;
542 } else /* "0.X" */
543 size = prec + 2;
544 } else if (expt >= ndig) { /* fixed g fmt */
545 size = expt;
546 if (flags & ALT)
547 ++size;
548 } else
549 size = ndig + (expt > 0 ?
550 1 : 2 - expt);
551
552 if (softsign)
553 sign = '-';
554 break;
555 #endif /* NO_FLOATING_POINT */
556 case 'n':
557 if (flags & MAXINT)
558 *va_arg(ap, intmax_t *) = ret;
559 else if (flags & PTRINT)
560 *va_arg(ap, ptrdiff_t *) = ret;
561 else if (flags & SIZEINT)
562 *va_arg(ap, ssize_t *) = ret; /* XXX */
563 else if (flags & QUADINT)
564 *va_arg(ap, quad_t *) = ret;
565 else if (flags & LONGINT)
566 *va_arg(ap, long *) = ret;
567 else if (flags & SHORTINT)
568 *va_arg(ap, short *) = ret;
569 else
570 *va_arg(ap, int *) = ret;
571 continue; /* no output */
572 case 'O':
573 flags |= LONGINT;
574 /*FALLTHROUGH*/
575 case 'o':
576 _uintmax = UARG();
577 base = OCT;
578 goto nosign;
579 case 'p':
580 /*
581 * ``The argument shall be a pointer to void. The
582 * value of the pointer is converted to a sequence
583 * of printable characters, in an implementation-
584 * defined manner.''
585 * -- ANSI X3J11
586 */
587 /* NOSTRICT */
588 _uintmax = (u_long)va_arg(ap, void *);
589 base = HEX;
590 xdigs = "0123456789abcdef";
591 flags |= HEXPREFIX;
592 ch = 'x';
593 goto nosign;
594 case 's':
595 if ((cp = va_arg(ap, char *)) == NULL)
596 cp = "(null)";
597 if (prec >= 0) {
598 /*
599 * can't use strlen; can only look for the
600 * NUL in the first `prec' characters, and
601 * strlen() will go further.
602 */
603 char *p = memchr(cp, 0, (size_t)prec);
604
605 if (p != NULL) {
606 size = p - cp;
607 if (size > prec)
608 size = prec;
609 } else
610 size = prec;
611 } else
612 size = strlen(cp);
613 sign = '\0';
614 break;
615 case 'U':
616 flags |= LONGINT;
617 /*FALLTHROUGH*/
618 case 'u':
619 _uintmax = UARG();
620 base = DEC;
621 goto nosign;
622 case 'X':
623 xdigs = "0123456789ABCDEF";
624 goto hex;
625 case 'x':
626 xdigs = "0123456789abcdef";
627 hex: _uintmax = UARG();
628 base = HEX;
629 /* leading 0x/X only if non-zero */
630 if (flags & ALT && _uintmax != 0)
631 flags |= HEXPREFIX;
632
633 /* unsigned conversions */
634 nosign: sign = '\0';
635 /*
636 * ``... diouXx conversions ... if a precision is
637 * specified, the 0 flag will be ignored.''
638 * -- ANSI X3J11
639 */
640 number: if ((dprec = prec) >= 0)
641 flags &= ~ZEROPAD;
642
643 /*
644 * ``The result of converting a zero value with an
645 * explicit precision of zero is no characters.''
646 * -- ANSI X3J11
647 */
648 bp = buf + BUF;
649 if (_uintmax != 0 || prec != 0) {
650 /*
651 * Unsigned mod is hard, and unsigned mod
652 * by a constant is easier than that by
653 * a variable; hence this switch.
654 */
655 switch (base) {
656 case OCT:
657 do {
658 *--bp = to_char(_uintmax & 7);
659 _uintmax >>= 3;
660 } while (_uintmax);
661 /* handle octal leading 0 */
662 if (flags & ALT && *bp != '0')
663 *--bp = '0';
664 break;
665
666 case DEC:
667 /* many numbers are 1 digit */
668 while (_uintmax >= 10) {
669 *--bp = to_char(_uintmax % 10);
670 _uintmax /= 10;
671 }
672 *--bp = to_char(_uintmax);
673 break;
674
675 case HEX:
676 do {
677 *--bp = xdigs[(size_t)
678 (_uintmax & 15)];
679 _uintmax >>= 4;
680 } while (_uintmax);
681 break;
682
683 default:
684 cp = "bug in vfprintf: bad base";
685 size = strlen(cp);
686 goto skipsize;
687 }
688 }
689 cp = bp;
690 size = buf + BUF - bp;
691 skipsize:
692 break;
693 default: /* "%?" prints ?, unless ? is NUL */
694 if (ch == '\0')
695 goto done;
696 /* pretend it was %c with argument ch */
697 *buf = ch;
698 cp = buf;
699 size = 1;
700 sign = '\0';
701 break;
702 }
703
704 /*
705 * All reasonable formats wind up here. At this point, `cp'
706 * points to a string which (if not flags&LADJUST) should be
707 * padded out to `width' places. If flags&ZEROPAD, it should
708 * first be prefixed by any sign or other prefix; otherwise,
709 * it should be blank padded before the prefix is emitted.
710 * After any left-hand padding and prefixing, emit zeroes
711 * required by a decimal [diouxX] precision, then print the
712 * string proper, then emit zeroes required by any leftover
713 * floating precision; finally, if LADJUST, pad with blanks.
714 *
715 * Compute actual size, so we know how much to pad.
716 * size excludes decimal prec; realsz includes it.
717 */
718 realsz = dprec > size ? dprec : size;
719 if (sign)
720 realsz++;
721 else if (flags & HEXPREFIX)
722 realsz+= 2;
723
724 /* right-adjusting blank padding */
725 if ((flags & (LADJUST|ZEROPAD)) == 0)
726 PAD(width - realsz, blanks);
727
728 /* prefix */
729 if (sign) {
730 PRINT(&sign, 1);
731 } else if (flags & HEXPREFIX) {
732 ox[0] = '0';
733 ox[1] = ch;
734 PRINT(ox, 2);
735 }
736
737 /* right-adjusting zero padding */
738 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
739 PAD(width - realsz, zeroes);
740
741 /* leading zeroes from decimal precision */
742 PAD(dprec - size, zeroes);
743
744 /* the string or number proper */
745 #ifndef NO_FLOATING_POINT
746 if ((flags & FPT) == 0) {
747 PRINT(cp, size);
748 } else { /* glue together f_p fragments */
749 if (ch >= 'f') { /* 'f' or 'g' */
750 if (decimal_point == NULL)
751 decimal_point =
752 localeconv()->decimal_point;
753 if (_double == 0) {
754 /* kludge for __dtoa irregularity */
755 PRINT("0", 1);
756 if (expt < ndig || (flags & ALT) != 0) {
757 PRINT(decimal_point, 1);
758 PAD(ndig - 1, zeroes);
759 }
760 } else if (expt <= 0) {
761 PRINT("0", 1);
762 PRINT(decimal_point, 1);
763 PAD(-expt, zeroes);
764 PRINT(cp, ndig);
765 } else if (expt >= ndig) {
766 PRINT(cp, ndig);
767 PAD(expt - ndig, zeroes);
768 if (flags & ALT)
769 PRINT(".", 1);
770 } else {
771 PRINT(cp, expt);
772 cp += expt;
773 PRINT(".", 1);
774 PRINT(cp, ndig-expt);
775 }
776 } else { /* 'e' or 'E' */
777 if (ndig > 1 || flags & ALT) {
778 ox[0] = *cp++;
779 ox[1] = '.';
780 PRINT(ox, 2);
781 if (_double) {
782 PRINT(cp, ndig-1);
783 } else /* 0.[0..] */
784 /* __dtoa irregularity */
785 PAD(ndig - 1, zeroes);
786 } else /* XeYYY */
787 PRINT(cp, 1);
788 PRINT(expstr, expsize);
789 }
790 }
791 #else
792 PRINT(cp, size);
793 #endif
794 /* left-adjusting padding (always blank) */
795 if (flags & LADJUST)
796 PAD(width - realsz, blanks);
797
798 /* finally, adjust ret */
799 ret += width > realsz ? width : realsz;
800
801 FLUSH(); /* copy out the I/O vectors */
802 }
803 done:
804 FLUSH();
805 error:
806 #ifndef NO_FLOATING_POINT
807 if (dtoaresult)
808 __freedtoa(dtoaresult);
809 #endif
810 if (__sferror(fp))
811 ret = -1;
812 return (ret);
813 }
814
815 #ifndef NO_FLOATING_POINT
816
817 static char *
818 cvt(value, ndigits, flags, sign, decpt, ch, length)
819 double value;
820 int ndigits, flags, *decpt, ch, *length;
821 char *sign;
822 {
823 int mode, dsgn;
824 char *digits, *bp, *rve;
825
826 _DIAGASSERT(decpt != NULL);
827 _DIAGASSERT(length != NULL);
828 _DIAGASSERT(sign != NULL);
829
830 if (ch == 'f') {
831 mode = 3; /* ndigits after the decimal point */
832 } else {
833 /* To obtain ndigits after the decimal point for the 'e'
834 * and 'E' formats, round to ndigits + 1 significant
835 * figures.
836 */
837 if (ch == 'e' || ch == 'E') {
838 ndigits++;
839 }
840 mode = 2; /* ndigits significant digits */
841 }
842
843 digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
844 if (dsgn) {
845 value = -value;
846 *sign = '-';
847 } else
848 *sign = '\000';
849 if ((ch != 'g' && ch != 'G') || flags & ALT) { /* Print trailing zeros */
850 bp = digits + ndigits;
851 if (ch == 'f') {
852 if (*digits == '0' && value)
853 *decpt = -ndigits + 1;
854 bp += *decpt;
855 }
856 if (value == 0) /* kludge for __dtoa irregularity */
857 rve = bp;
858 while (rve < bp)
859 *rve++ = '0';
860 }
861 *length = rve - digits;
862 return (digits);
863 }
864
865 static int
866 exponent(p0, expon, fmtch)
867 char *p0;
868 int expon, fmtch;
869 {
870 char *p, *t;
871 char expbuf[MAXEXP];
872
873 _DIAGASSERT(p0 != NULL);
874
875 p = p0;
876 *p++ = fmtch;
877 if (expon < 0) {
878 expon = -expon;
879 *p++ = '-';
880 }
881 else
882 *p++ = '+';
883 t = expbuf + MAXEXP;
884 if (expon > 9) {
885 do {
886 *--t = to_char(expon % 10);
887 } while ((expon /= 10) > 9);
888 *--t = to_char(expon);
889 for (; t < expbuf + MAXEXP; *p++ = *t++);
890 }
891 else {
892 *p++ = '0';
893 *p++ = to_char(expon);
894 }
895 return (p - p0);
896 }
897 #endif /* NO_FLOATING_POINT */
898