xref: /csrg-svn/lib/libc/stdio/vfprintf.c (revision 34326)
1 /*
2  * Copyright (c) 1988 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that this notice is preserved and that due credit is given
7  * to the University of California at Berkeley. The name of the University
8  * may not be used to endorse or promote products derived from this
9  * software without specific prior written permission. This software
10  * is provided ``as is'' without express or implied warranty.
11  */
12 
13 #if defined(LIBC_SCCS) && !defined(lint)
14 static char sccsid[] = "@(#)vfprintf.c	5.22 (Berkeley) 05/18/88";
15 #endif /* LIBC_SCCS and not lint */
16 
17 #include <sys/types.h>
18 #include <varargs.h>
19 #include <stdio.h>
20 #include <ctype.h>
21 
22 #define	MAXBUF		512
23 
24 #define	PUTC(ch)	{++cnt; putc((char)ch, fp);}
25 
26 #define	ARG() \
27 	_ulong = flags&LONGINT ? va_arg(argp, long) : \
28 	    flags&SHORTINT ? va_arg(argp, short) : va_arg(argp, int);
29 
30 /* have to deal with the negative buffer count kludge */
31 #define	NEGATIVE_COUNT_KLUDGE
32 
33 #define	LONGINT		0x01		/* long integer */
34 #define	LONGDBL		0x02		/* long double; unimplemented */
35 #define	SHORTINT	0x04		/* short integer */
36 #define	ALT		0x08		/* alternate form */
37 #define	LADJUST		0x10		/* left adjustment */
38 
39 _doprnt(fmt0, argp, fp)
40 	u_char *fmt0;
41 	va_list argp;
42 	register FILE *fp;
43 {
44 	register u_char *fmt;
45 	register int ch, cnt, n;
46 	register char *t;
47 	double _double;
48 	u_long _ulong;
49 	int base, flags, prec, size, width;
50 	char padc, sign, *digs, buf[MAXBUF], *_cvt();
51 
52 	fmt = fmt0;
53 	digs = "0123456789abcdef";
54 	for (cnt = 0;; ++fmt) {
55 		n = fp->_cnt;
56 		for (t = fp->_ptr; (ch = *fmt) && ch != '%'; ++cnt, ++fmt)
57 			if (--n < 0
58 #ifdef NEGATIVE_COUNT_KLUDGE
59 			    && (!(fp->_flag & _IOLBF) || -n >= fp->_bufsiz)
60 #endif
61 			    || ch == '\n' && fp->_flag&_IOLBF) {
62 				fp->_cnt = n;
63 				fp->_ptr = t;
64 				(void)_flsbuf(ch, fp);
65 				n = fp->_cnt;
66 				t = fp->_ptr;
67 			}
68 			else
69 				*t++ = ch;
70 		fp->_cnt = n;
71 		fp->_ptr = t;
72 		if (!ch)
73 			return(cnt);
74 
75 		flags = width = 0;
76 		prec = -1;
77 		padc = ' ';
78 		sign = '\0';
79 
80 rflag:		switch (*++fmt) {
81 		case ' ':
82 			sign = ' ';
83 			goto rflag;
84 		case '#':
85 			flags |= ALT;
86 			goto rflag;
87 		case '*':
88 			/*
89 			 * ``A negative field width argument is taken as a
90 			 * - flag followed by a  positive field width.''
91 			 *	-- ANSI X3J11
92 			 * They don't exclude field widths read from args.
93 			 */
94 			if ((width = va_arg(argp, int)) >= 0)
95 				goto rflag;
96 			width = -width;
97 			/*FALLTHROUGH*/
98 		case '-':
99 			flags |= LADJUST;
100 			goto rflag;
101 		case '+':
102 			sign = '+';
103 			goto rflag;
104 		case '.':
105 			if (*++fmt == '*')
106 				n = va_arg(argp, int);
107 			else if (isascii(*fmt) && isdigit(*fmt)) {
108 				n = 0;
109 				do {
110 					n = 10 * n + *fmt - '0';
111 				} while (isascii(*++fmt) && isdigit(*fmt));
112 				--fmt;
113 			}
114 			else {
115 				--fmt;
116 				prec = 0;
117 				goto rflag;
118 			}
119 			prec = n < 0 ? -1 : n;
120 			goto rflag;
121 		case '0':
122 			padc = '0';
123 			/*FALLTHROUGH*/
124 		case '1': case '2': case '3': case '4':
125 		case '5': case '6': case '7': case '8': case '9':
126 			n = 0;
127 			do {
128 				n = 10 * n + *fmt - '0';
129 			} while (isascii(*++fmt) && isdigit(*fmt));
130 			width = n;
131 			--fmt;
132 			goto rflag;
133 		case 'L':
134 			/*
135 			 * C doesn't have a long double; use long for now.
136 			 * flags |= LONGDBL;
137 			 */
138 			flags |= LONGINT;
139 			goto rflag;
140 		case 'h':
141 			flags |= SHORTINT;
142 			goto rflag;
143 		case 'l':
144 			flags |= LONGINT;
145 			goto rflag;
146 		case 'c':
147 			buf[0] = va_arg(argp, int);
148 			size = 1;
149 			t = buf;
150 			goto pforw;
151 		case 'd':
152 		case 'i':
153 			ARG();
154 			if ((long)_ulong < 0) {
155 				_ulong = -_ulong;
156 				sign = '-';
157 			}
158 			if (sign)
159 				PUTC(sign);
160 			base = 10;
161 			goto num;
162 		case 'e':
163 		case 'E':
164 		case 'f':
165 		case 'g':
166 		case 'G':
167 			_double = va_arg(argp, double);
168 			size = _cvt(_double, prec, flags, *fmt, sign,
169 			    buf, buf + sizeof(buf)) - buf;
170 			t = buf;
171 			goto pforw;
172 		case 'n':
173 			if (flags&LONGDBL || flags&LONGINT)
174 				*va_arg(argp, long *) = cnt;
175 			else if (flags&SHORTINT)
176 				*va_arg(argp, short *) = cnt;
177 			else
178 				*va_arg(argp, int *) = cnt;
179 			break;
180 		case 'o':
181 			ARG();
182 			base = 8;
183 			goto num;
184 		case 'p':
185 			/*
186 			 * ``The argument shall be a pointer to void.  The
187 			 * value of the pointer is converted to a sequence
188 			 * of printable characters, in an implementation-
189 			 * defined manner.''
190 			 *	-- ANSI X3J11
191 			 */
192 			_ulong = (u_long)va_arg(argp, void *);
193 			base = 16;
194 			goto num;
195 		case 's':
196 			if (!(t = va_arg(argp, char *)))
197 				t = "(null)";
198 			if (prec >= 0) {
199 				/*
200 				 * can't use strlen; can only look for the
201 				 * NUL in the first `prec' characters, and
202 				 * strlen() will go further.
203 				 */
204 				char *p, *memchr();
205 
206 				if (p = memchr(t, 0, prec)) {
207 					size = p - t;
208 					if (size > prec)
209 						size = prec;
210 				}
211 				else
212 					size = prec;
213 			}
214 			else
215 				size = strlen(t);
216 pforw:			if (!(flags&LADJUST) && width)
217 				for (n = size; n++ < width;)
218 					PUTC(padc);
219 			if (fp->_cnt - (n = size) >= 0) {
220 				cnt += n;
221 				fp->_cnt -= n;
222 				bcopy(t, fp->_ptr, n);
223 				fp->_ptr += n;
224 			}
225 			else for (; n--; ++t)
226 				PUTC(*t);
227 			if (flags&LADJUST)
228 				while (width-- > size)
229 					PUTC(' ');
230 			break;
231 		case 'u':
232 			ARG();
233 			base = 10;
234 			goto num;
235 		case 'X':
236 			digs = "0123456789ABCDEF";
237 			/*FALLTHROUGH*/
238 		case 'x':
239 			ARG();
240 			base = 16;
241 			/* leading 0x/X only if non-zero */
242 			if (!_ulong)
243 				flags &= ~ALT;
244 			/*
245 			 * ``The result of converting a zero value with an
246 			 * explicit precision of zero is no characters.''
247 			 *	-- ANSI X3J11
248 			 */
249 num:			if (!_ulong && !prec)
250 				break;
251 			t = buf + MAXBUF - 1;
252 			do {
253 				*t-- = digs[_ulong % base];
254 				_ulong /= base;
255 			} while(_ulong);
256 			digs = "0123456789abcdef";
257 			for (size = buf + MAXBUF - 1 - t; size < prec; ++size)
258 				*t-- = '0';
259 			if (flags&ALT)
260 				switch (base) {
261 				case 16:
262 					/* avoid "00000x35" */
263 					if (padc == '0') {
264 						PUTC('0');
265 						PUTC(*fmt);
266 					}
267 					else {
268 						*t-- = *fmt;
269 						*t-- = '0';
270 					}
271 					width -= 2;
272 					break;
273 				case 8:
274 					if (t[1] != '0') {
275 						*t-- = '0';
276 						--width;
277 					}
278 					break;
279 				}
280 			if (!(flags&LADJUST))
281 				while (size++ < width)
282 					PUTC(padc);
283 			while (++t < buf + MAXBUF)
284 				PUTC(*t);
285 			while (width-- > size)
286 				PUTC(' ');
287 			break;
288 		case '\0':		/* "%?" prints ?, unless ? is NULL */
289 			return(cnt);
290 		default:
291 			PUTC(*fmt);
292 		}
293 	}
294 	/*NOTREACHED*/
295 }
296 
297 #define	EFORMAT	0x01
298 #define	FFORMAT	0x02
299 #define	GFORMAT	0x04
300 #define	DEFPREC	6
301 
302 static char *
303 _cvt(number, prec, flags, fmtch, sign, startp, endp)
304 	double number;
305 	register int prec;
306 	int flags;
307 	u_char fmtch;
308 	char sign, *startp, *endp;
309 {
310 	register char *p;
311 	register int expcnt, format;
312 	double fract, integer, tmp, modf();
313 	int decpt;
314 	char *savep;
315 
316 	if (prec == -1)
317 		prec = DEFPREC;
318 
319 	if (number < 0) {
320 		*startp++ = '-';
321 		number = -number;
322 	}
323 	else if (sign)
324 		*startp++ = sign;
325 
326 	switch(fmtch) {
327 	case 'e':
328 	case 'E':
329 		format = EFORMAT;
330 		break;
331 	case 'f':
332 		format = FFORMAT;
333 		break;
334 	case 'g':
335 	case 'G':
336 		format = GFORMAT;
337 		fmtch -= 2;
338 	}
339 
340 	/*
341 	 * if the alternate flag is set, or, at least one digit of precision
342 	 * was requested, add a decimal point, unless it's the g/G format
343 	 * in which case we require two digits of precision, as it counts
344 	 * precision differently.
345 	 */
346 	decpt = flags&ALT || prec > (format&GFORMAT ? 1 : 0);
347 
348 	expcnt = 0;
349 	p = endp - 1;
350 	fract = modf(number, &integer);
351 	if (integer) {
352 		register char *p2;
353 
354 		/* get integer part of number; count decimal places */
355 		for (; integer; ++expcnt) {
356 			tmp = modf(integer / 10, &integer);
357 			*p-- = (int)((tmp + .03) * 10) + '0';
358 		}
359 
360 		/* copy, in reverse order, to start of buffer */
361 		p2 = startp;
362 		*p2++ = *++p;
363 
364 		/*
365 		 * if the format is g/G, and the resulting exponent will be
366 		 * greater than the precision, use e/E format.  If e/E format,
367 		 * put in a decimal point as needed, and decrement precision
368 		 * count for each digit after the decimal point.
369 		 */
370 		if (format&GFORMAT && expcnt - 1 > prec || format&EFORMAT) {
371 			if (format&GFORMAT) {
372 				format |= EFORMAT;
373 
374 				/* first digit is precision for g/G format */
375 				if (prec)
376 					--prec;
377 			}
378 			if (decpt)
379 				*p2++ = '.';
380 			for (; ++p < endp && prec; --prec, *p2++ = *p);
381 
382 			/* precision ran out, round */
383 			if (p < endp) {
384 				if (*p > '4') {
385 					for (savep = p2--;; *p2-- = '0') {
386 						if (*p2 == '.')
387 							--p2;
388 						if (++*p2 <= '9')
389 							break;
390 					}
391 					p2 = savep;
392 				}
393 				fract = 0;
394 			}
395 		}
396 		/*
397 		 * g/G in f format; if out of precision, replace digits with
398 		 * zeroes, note, have to round first.
399 		 */
400 		else if (format&GFORMAT) {
401 			for (; ++p < endp && prec; --prec, *p2++ = *p);
402 			/* precision ran out; round and then add zeroes */
403 			if (p < endp) {
404 				if (*p > '4') {
405 					for (savep = p2--; ++*p2 > '9';
406 					    *p2-- = '0');
407 					p2 = savep;
408 				}
409 				do {
410 					*p2++ = '0';
411 				} while (++p < endp);
412 				fract = 0;
413 			}
414 			if (decpt)
415 				*p2++ = '.';
416 		}
417 		/* f format */
418 		else {
419 			for (; ++p < endp; *p2++ = *p);
420 			if (decpt)
421 				*p2++ = '.';
422 		}
423 		p = p2;
424 	}
425 	/*
426 	 * if no fraction, the number was zero, and if no precision, can't
427 	 * show anything after the decimal point.
428 	 */
429 	else if (!fract || !prec) {
430 		*startp++ = '0';
431 		if (decpt && !(format&GFORMAT))
432 			*startp++ = '.';
433 		*startp = '\0';
434 		return(startp);
435 	}
436 	/*
437 	 * if the format is g/G, and the resulting exponent will be less than
438 	 * -4 use e/E format.  If e/E format, compute exponent value.
439 	 */
440 	else if (format&GFORMAT && fract < .0001 || format&EFORMAT) {
441 		format |= EFORMAT;
442 		if (fract)
443 			for (p = startp; fract;) {
444 				fract = modf(fract * 10, &tmp);
445 				if (!tmp) {
446 					--expcnt;
447 					continue;
448 				}
449 				*p++ = (int)tmp + '0';
450 				break;
451 			}
452 		else
453 			*p++ = '0';
454 
455 		/* g/G format, decrement precision for first digit */
456 		if (format&GFORMAT && prec)
457 			--prec;
458 
459 		/* add decimal after first non-zero digit */
460 		if (decpt)
461 			*p++ = '.';
462 	}
463 	/*
464 	 * f format or g/G printed as f format; don't worry about decimal
465 	 * point, if g/G format doesn't need it, will get stripped later.
466 	 */
467 	else {
468 		p = startp;
469 		*p++ = '0';
470 		*p++ = '.';
471 	}
472 
473 	/* finish out requested precision */
474 	while (fract && prec-- > 0) {
475 		fract = modf(fract * 10, &tmp);
476 		*p++ = (int)tmp + '0';
477 	}
478 	while (prec-- > 0)
479 		*p++ = '0';
480 
481 	/*
482 	 * if any fractional value left, "round" it back up to the beginning
483 	 * of the number, fixing the exponent as necessary, and avoiding the
484 	 * decimal point.
485 	 */
486 	if (fract) {
487 		(void)modf(fract * 10, &tmp);
488 		if (tmp > 4) {
489 			for (savep = p--;; *p-- = '0') {
490 				if (*p == '.')
491 					--p;
492 				if (p == startp) {
493 					*p = '1';
494 					++expcnt;
495 					break;
496 				}
497 				if (++*p <= '9')
498 					break;
499 			}
500 			p = savep;
501 		}
502 	}
503 
504 	/*
505 	 * if a g/G format and not alternate flag, lose trailing zeroes,
506 	 * if e/E or g/G format, and last char is decimal point, lose it.
507 	 */
508 	if (!(flags&ALT)) {
509 		if (format&GFORMAT)
510 			for (; p[-1] == '0'; --p);
511 		if (format&(GFORMAT|EFORMAT) && p[-1] == '.')
512 			--p;
513 	}
514 
515 	/* if an e/E format, add exponent */
516 	if (format&EFORMAT) {
517 		*p++ = fmtch;
518 		if (--expcnt < 0) {
519 			expcnt = -expcnt;
520 			*p++ = '-';
521 		}
522 		else
523 			*p++ = '+';
524 		*p++ = expcnt / 10 + '0';
525 		*p++ = expcnt % 10 + '0';
526 	}
527 	return(p);
528 }
529