1/*-
2 * Copyright (c) 1990, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Chris Torek.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/*
34 * IMPORTANT NOTE:
35 * --------------
36 * From ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
37 * paragraph 3 above is now null and void.
38 */
39
40/* SNPRINTF.C
41 * fjc 7-31-97 Modified by Mib Software to be a standalone snprintf.c module.
42 *      http://www.mibsoftware.com
43 * Mib Software does not warrant this software any differently than the
44 * University of California, Berkeley as described above.  All warranties
45 * are disclaimed.  Use this software at your own risk.
46 *
47 *      All code referencing FILE * functions was eliminated, since it could
48 *      never be called.  All header files and necessary files are collapsed
49 *      into one file, internal functions are declared static.  This should
50 *      allow inclusion into libraries with less chance of namespace collisions.
51 *
52 *      snprintf should be the only externally visible item.
53 *
54 *      As of 7-31-97 FLOATING_POINT is NOT provided.  The code is somewhat
55 *        non-portable, so it is disabled.
56 */
57
58/* Define FLOATING_POINT to get floating point. */
59/*
60#define	FLOATING_POINT
61*/
62
63#include <sys/types.h>
64#define u_long unsigned long
65#define u_short unsigned short
66#define u_int unsigned int
67
68#if !defined(HAVE_STDARG_PROTOTYPES)
69#if defined(__STDC__)
70#define HAVE_STDARG_PROTOTYPES 1
71#endif
72#endif
73
74#undef __P
75#if defined(HAVE_STDARG_PROTOTYPES)
76# include <stdarg.h>
77# if !defined(__P)
78#  define __P(x) x
79# endif
80#else
81# define __P(x) ()
82# if !defined(const)
83#  define const
84# endif
85# include <varargs.h>
86#endif
87#ifndef _BSD_VA_LIST_
88#define	_BSD_VA_LIST_ va_list
89#endif
90
91#ifdef __STDC__
92# include <limits.h>
93#else
94# ifndef LONG_MAX
95#  ifdef HAVE_LIMITS_H
96#   include <limits.h>
97#  else
98    /* assuming 32bit(2's compliment) long */
99#   define LONG_MAX 2147483647
100#  endif
101# endif
102#endif
103
104#if defined(__hpux) && !defined(__GNUC__) && !defined(__STDC__)
105#define const
106#endif
107
108#if defined(sgi)
109#undef __const
110#define __const
111#endif /* People who don't like const sys_error */
112
113#include <stddef.h>
114#if defined(__hpux) && !defined(__GNUC__) || defined(__DECC)
115#include <string.h>
116#endif
117
118#if !defined(__CYGWIN32__) && defined(__hpux) && !defined(__GNUC__)
119#include <stdlib.h>
120#endif
121
122#ifndef NULL
123#define	NULL	0
124#endif
125
126#if SIZEOF_LONG > SIZEOF_INT
127# include <errno.h>
128#endif
129
130#if __GNUC__ >= 3
131#define UNINITIALIZED_VAR(x) x = x
132#else
133#define UNINITIALIZED_VAR(x) x
134#endif
135
136/*
137 * NB: to fit things in six character monocase externals, the stdio
138 * code uses the prefix `__s' for stdio objects, typically followed
139 * by a three-character attempt at a mnemonic.
140 */
141
142/* stdio buffers */
143struct __sbuf {
144	unsigned char *_base;
145	size_t	_size;
146};
147
148
149/*
150 * stdio state variables.
151 *
152 * The following always hold:
153 *
154 *	if (_flags&(__SLBF|__SWR)) == (__SLBF|__SWR),
155 *		_lbfsize is -_bf._size, else _lbfsize is 0
156 *	if _flags&__SRD, _w is 0
157 *	if _flags&__SWR, _r is 0
158 *
159 * This ensures that the getc and putc macros (or inline functions) never
160 * try to write or read from a file that is in `read' or `write' mode.
161 * (Moreover, they can, and do, automatically switch from read mode to
162 * write mode, and back, on "r+" and "w+" files.)
163 *
164 * _lbfsize is used only to make the inline line-buffered output stream
165 * code as compact as possible.
166 *
167 * _ub, _up, and _ur are used when ungetc() pushes back more characters
168 * than fit in the current _bf, or when ungetc() pushes back a character
169 * that does not match the previous one in _bf.  When this happens,
170 * _ub._base becomes non-nil (i.e., a stream has ungetc() data iff
171 * _ub._base!=NULL) and _up and _ur save the current values of _p and _r.
172 *
173 * NB: see WARNING above before changing the layout of this structure!
174 */
175typedef	struct __sFILE {
176	unsigned char *_p;	/* current position in (some) buffer */
177#if 0
178	size_t	_r;		/* read space left for getc() */
179#endif
180	size_t	_w;		/* write space left for putc() */
181	short	_flags;		/* flags, below; this FILE is free if 0 */
182	short	_file;		/* fileno, if Unix descriptor, else -1 */
183	struct	__sbuf _bf;	/* the buffer (at least 1 byte, if !NULL) */
184	size_t	_lbfsize;	/* 0 or -_bf._size, for inline putc */
185	int	(*vwrite)(/* struct __sFILE*, struct __suio * */);
186	char	*(*vextra)(/* struct __sFILE*, size_t, void*, long*, int */);
187} FILE;
188
189
190#define	__SLBF	0x0001		/* line buffered */
191#define	__SNBF	0x0002		/* unbuffered */
192#define	__SRD	0x0004		/* OK to read */
193#define	__SWR	0x0008		/* OK to write */
194	/* RD and WR are never simultaneously asserted */
195#define	__SRW	0x0010		/* open for reading & writing */
196#define	__SEOF	0x0020		/* found EOF */
197#define	__SERR	0x0040		/* found error */
198#define	__SMBF	0x0080		/* _buf is from malloc */
199#define	__SAPP	0x0100		/* fdopen()ed in append mode */
200#define	__SSTR	0x0200		/* this is an sprintf/snprintf string */
201#define	__SOPT	0x0400		/* do fseek() optimisation */
202#define	__SNPT	0x0800		/* do not do fseek() optimisation */
203#define	__SOFF	0x1000		/* set iff _offset is in fact correct */
204#define	__SMOD	0x2000		/* true => fgetln modified _p text */
205
206
207#define	EOF	(-1)
208
209
210#define	BSD__sfeof(p)	(((p)->_flags & __SEOF) != 0)
211#define	BSD__sferror(p)	(((p)->_flags & __SERR) != 0)
212#define	BSD__sclearerr(p)	((void)((p)->_flags &= ~(__SERR|__SEOF)))
213#define	BSD__sfileno(p)	((p)->_file)
214
215#undef feof
216#undef ferror
217#undef clearerr
218#define	feof(p)		BSD__sfeof(p)
219#define	ferror(p)	BSD__sferror(p)
220#define	clearerr(p)	BSD__sclearerr(p)
221
222#ifndef _ANSI_SOURCE
223#define	fileno(p)	BSD__sfileno(p)
224#endif
225
226
227/*
228 * I/O descriptors for __sfvwrite().
229 */
230struct __siov {
231	const void *iov_base;
232	size_t	iov_len;
233};
234struct __suio {
235	struct	__siov *uio_iov;
236	int	uio_iovcnt;
237	size_t	uio_resid;
238};
239
240/*
241 * Write some memory regions.  Return zero on success, EOF on error.
242 *
243 * This routine is large and unsightly, but most of the ugliness due
244 * to the three different kinds of output buffering is handled here.
245 */
246static int
247BSD__sfvwrite(register FILE *fp, register struct __suio *uio)
248{
249	register size_t len;
250	register const char *p;
251	register struct __siov *iov;
252	register size_t w;
253
254	if ((len = uio->uio_resid) == 0)
255		return (0);
256#ifndef __hpux
257#define	MIN(a, b) ((a) < (b) ? (a) : (b))
258#endif
259#define	COPY(n)	  (void)memcpy((void *)fp->_p, (void *)p, (size_t)(n))
260
261	iov = uio->uio_iov;
262	p = iov->iov_base;
263	len = iov->iov_len;
264	iov++;
265#define GETIOV(extra_work) \
266	while (len == 0) { \
267		extra_work; \
268		p = iov->iov_base; \
269		len = iov->iov_len; \
270		iov++; \
271	}
272	if (fp->_flags & __SNBF) {
273	/* fjc 7-31-97 Will never happen.  We are working with
274					   strings only
275	*/
276	} else if ((fp->_flags & __SLBF) == 0) {
277	/*
278		 * Fully buffered: fill partially full buffer, if any,
279		 * and then flush.  If there is no partial buffer, write
280		 * one _bf._size byte chunk directly (without copying).
281		 *
282		 * String output is a special case: write as many bytes
283		 * as fit, but pretend we wrote everything.  This makes
284		 * snprintf() return the number of bytes needed, rather
285		 * than the number used, and avoids its write function
286		 * (so that the write function can be invalid).
287		 */
288		do {
289			GETIOV(;);
290			w = fp->_w;
291			if (fp->_flags & __SSTR) {
292				if (len < w)
293					w = len;
294				COPY(w);	/* copy MIN(fp->_w,len), */
295				fp->_w -= w;
296				fp->_p += w;
297				w = len;	/* but pretend copied all */
298			} else {
299				/* fjc 7-31-97 Will never happen.  We are working with
300								   strings only
301				*/
302			}
303			p += w;
304			len -= w;
305		} while ((uio->uio_resid -= w) != 0);
306	} else {
307		/* fjc 7-31-97 Will never happen.  We are working with
308						   strings only
309		*/
310	}
311	return (0);
312}
313
314/*
315 * Actual printf innards.
316 *
317 * This code is large and complicated...
318 */
319
320/*
321 * Flush out all the vectors defined by the given uio,
322 * then reset it so that it can be reused.
323 */
324static int
325BSD__sprint(FILE *fp, register struct __suio *uio)
326{
327	register int err;
328
329	if (uio->uio_resid == 0) {
330		uio->uio_iovcnt = 0;
331		return (0);
332	}
333	err = (*fp->vwrite)(fp, uio);
334	uio->uio_resid = 0;
335	uio->uio_iovcnt = 0;
336	return (err);
337}
338
339
340/*
341 * Helper function for `fprintf to unbuffered unix file': creates a
342 * temporary buffer.  We only work on write-only files; this avoids
343 * worries about ungetc buffers and so forth.
344 */
345static int
346BSD__sbprintf(register FILE *fp, const char *fmt, va_list ap)
347{
348/* We don't support files. */
349	return 0;
350}
351
352
353/*
354 * Macros for converting digits to letters and vice versa
355 */
356#define	to_digit(c)	((c) - '0')
357#define is_digit(c)	((unsigned)to_digit(c) <= 9)
358#define	to_char(n)	(char)((n) + '0')
359
360#ifdef _HAVE_SANE_QUAD_
361/*
362 * Convert an unsigned long long to ASCII for printf purposes, returning
363 * a pointer to the first character of the string representation.
364 * Octal numbers can be forced to have a leading zero; hex numbers
365 * use the given digits.
366 */
367static char *
368BSD__uqtoa(register u_quad_t val, char *endp, int base, int octzero, const char *xdigs)
369{
370	register char *cp = endp;
371	register quad_t sval;
372
373	/*
374	 * Handle the three cases separately, in the hope of getting
375	 * better/faster code.
376	 */
377	switch (base) {
378	case 10:
379		if (val < 10) {	/* many numbers are 1 digit */
380			*--cp = to_char(val);
381			return (cp);
382		}
383		/*
384		 * On many machines, unsigned arithmetic is harder than
385		 * signed arithmetic, so we do at most one unsigned mod and
386		 * divide; this is sufficient to reduce the range of
387		 * the incoming value to where signed arithmetic works.
388		 */
389		if (val > LLONG_MAX) {
390			*--cp = to_char(val % 10);
391			sval = val / 10;
392		} else
393			sval = val;
394		do {
395			*--cp = to_char(sval % 10);
396			sval /= 10;
397		} while (sval != 0);
398		break;
399
400	case 8:
401		do {
402			*--cp = to_char(val & 7);
403			val >>= 3;
404		} while (val);
405		if (octzero && *cp != '0')
406			*--cp = '0';
407		break;
408
409	case 16:
410		do {
411			*--cp = xdigs[val & 15];
412			val >>= 4;
413		} while (val);
414		break;
415
416	default:			/* oops */
417		/*
418		abort();
419		*/
420		break;	/* fjc 7-31-97.  Don't reference abort() here */
421	}
422	return (cp);
423}
424#endif /* _HAVE_SANE_QUAD_ */
425
426/*
427 * Convert an unsigned long to ASCII for printf purposes, returning
428 * a pointer to the first character of the string representation.
429 * Octal numbers can be forced to have a leading zero; hex numbers
430 * use the given digits.
431 */
432static char *
433BSD__ultoa(register u_long val, char *endp, int base, int octzero, const char *xdigs)
434{
435	register char *cp = endp;
436	register long sval;
437
438	/*
439	 * Handle the three cases separately, in the hope of getting
440	 * better/faster code.
441	 */
442	switch (base) {
443	case 10:
444		if (val < 10) {	/* many numbers are 1 digit */
445			*--cp = to_char(val);
446			return (cp);
447		}
448		/*
449		 * On many machines, unsigned arithmetic is harder than
450		 * signed arithmetic, so we do at most one unsigned mod and
451		 * divide; this is sufficient to reduce the range of
452		 * the incoming value to where signed arithmetic works.
453		 */
454		if (val > LONG_MAX) {
455			*--cp = to_char(val % 10);
456			sval = val / 10;
457		} else
458			sval = val;
459		do {
460			*--cp = to_char(sval % 10);
461			sval /= 10;
462		} while (sval != 0);
463		break;
464
465	case 8:
466		do {
467			*--cp = to_char(val & 7);
468			val >>= 3;
469		} while (val);
470		if (octzero && *cp != '0')
471			*--cp = '0';
472		break;
473
474	case 16:
475		do {
476			*--cp = xdigs[val & 15];
477			val >>= 4;
478		} while (val);
479		break;
480
481	default:			/* oops */
482		/*
483		abort();
484		*/
485		break;	/* fjc 7-31-97.  Don't reference abort() here */
486	}
487	return (cp);
488}
489
490#ifdef FLOATING_POINT
491#include <math.h>
492#include <float.h>
493/* #include "floatio.h" */
494
495#ifndef MAXEXP
496# if DBL_MAX_10_EXP > -DBL_MIN_10_EXP
497#   define MAXEXP (DBL_MAX_10_EXP)
498# else
499#   define MAXEXP (-DBL_MIN_10_EXP)
500# endif
501#endif
502
503#ifndef MAXFRACT
504# define MAXFRACT (MAXEXP*10/3)
505#endif
506
507#define	BUF		(MAXEXP+MAXFRACT+1)	/* + decimal point */
508#define	DEFPREC		6
509
510static char *cvt(double, int, int, char *, int *, int, int *, char *);
511static int exponent(char *, int, int);
512
513#else /* no FLOATING_POINT */
514
515#define	BUF		68
516
517#endif /* FLOATING_POINT */
518
519
520/*
521 * Flags used during conversion.
522 */
523#define	ALT		0x001		/* alternate form */
524#define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
525#define	LADJUST		0x004		/* left adjustment */
526#define	LONGDBL		0x008		/* long double; unimplemented */
527#define	LONGINT		0x010		/* long integer */
528
529#ifdef _HAVE_SANE_QUAD_
530#define	QUADINT		0x020		/* quad integer */
531#endif /* _HAVE_SANE_QUAD_ */
532
533#define	SHORTINT	0x040		/* short integer */
534#define	ZEROPAD		0x080		/* zero (as opposed to blank) pad */
535#define FPT		0x100		/* Floating point number */
536static ssize_t
537BSD_vfprintf(FILE *fp, const char *fmt0, va_list ap)
538{
539	register const char *fmt; /* format string */
540	register int ch;	/* character from fmt */
541	register int n;		/* handy integer (short term usage) */
542	register const char *cp;/* handy char pointer (short term usage) */
543	register struct __siov *iovp;/* for PRINT macro */
544	register int flags;	/* flags as above */
545	ssize_t ret;		/* return value accumulator */
546	int width;		/* width from format (%8d), or 0 */
547	int prec;		/* precision from format (%.3d), or -1 */
548	char sign;		/* sign prefix (' ', '+', '-', or \0) */
549#ifdef FLOATING_POINT
550	char softsign;		/* temporary negative sign for floats */
551	double _double = 0;	/* double precision arguments %[eEfgG] */
552	int expt;		/* integer value of exponent */
553	int expsize = 0;	/* character count for expstr */
554	int ndig = 0;		/* actual number of digits returned by cvt */
555	int fprec = 0;		/* floating point precision */
556	char expstr[7];		/* buffer for exponent string */
557#endif
558	u_long UNINITIALIZED_VAR(ulval); /* integer arguments %[diouxX] */
559#ifdef _HAVE_SANE_QUAD_
560	u_quad_t UNINITIALIZED_VAR(uqval); /* %q integers */
561#endif /* _HAVE_SANE_QUAD_ */
562	int base;		/* base for [diouxX] conversion */
563	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
564	long fieldsz;		/* field size expanded by sign, etc */
565	long realsz;		/* field size expanded by dprec */
566	int size;		/* size of converted field or string */
567	const char *xdigs = 0;	/* digits for [xX] conversion */
568#define NIOV 8
569	struct __suio uio;	/* output information: summary */
570	struct __siov iov[NIOV];/* ... and individual io vectors */
571	char buf[BUF];		/* space for %c, %[diouxX], %[eEfgG] */
572	char ox[4];		/* space for 0x hex-prefix, hexadecimal's 1. */
573	char *const ebuf = buf + sizeof(buf);
574#if SIZEOF_LONG > SIZEOF_INT
575	long ln;
576#endif
577
578	/*
579	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
580	 * fields occur frequently, increase PADSIZE and make the initializers
581	 * below longer.
582	 */
583#define	PADSIZE	16		/* pad chunk size */
584	static const char blanks[PADSIZE] =
585	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
586	static const char zeroes[PADSIZE] =
587	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
588
589	/*
590	 * BEWARE, these `goto error' on error, and PAD uses `n'.
591	 */
592#define	PRINT(ptr, len) { \
593	iovp->iov_base = (ptr); \
594	iovp->iov_len = (len); \
595	uio.uio_resid += (len); \
596	iovp++; \
597	if (++uio.uio_iovcnt >= NIOV) { \
598		if (BSD__sprint(fp, &uio)) \
599			goto error; \
600		iovp = iov; \
601	} \
602}
603#define	PAD(howmany, with) { \
604	if ((n = (howmany)) > 0) { \
605		while (n > PADSIZE) { \
606			PRINT((with), PADSIZE); \
607			n -= PADSIZE; \
608		} \
609		PRINT((with), n); \
610	} \
611}
612#if SIZEOF_LONG > SIZEOF_INT
613	/* abandon if too larger padding */
614#define PAD_L(howmany, with) { \
615	ln = (howmany); \
616	if ((long)((int)ln) != ln) { \
617	    errno = ENOMEM; \
618	    goto error; \
619	} \
620	if (ln > 0) PAD((int)ln, (with)); \
621}
622#else
623#define PAD_L(howmany, with) PAD((howmany), (with))
624#endif
625#define	FLUSH() { \
626	if (uio.uio_resid && BSD__sprint(fp, &uio)) \
627		goto error; \
628	uio.uio_iovcnt = 0; \
629	iovp = iov; \
630}
631
632	/*
633	 * To extend shorts properly, we need both signed and unsigned
634	 * argument extraction methods.
635	 */
636#define	SARG() \
637	(flags&LONGINT ? va_arg(ap, long) : \
638	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
639	    (long)va_arg(ap, int))
640#define	UARG() \
641	(flags&LONGINT ? va_arg(ap, u_long) : \
642	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
643	    (u_long)va_arg(ap, u_int))
644
645	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
646	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
647	    fp->_file >= 0)
648		return (BSD__sbprintf(fp, fmt0, ap));
649
650	fmt = fmt0;
651	uio.uio_iov = iovp = iov;
652	uio.uio_resid = 0;
653	uio.uio_iovcnt = 0;
654	ret = 0;
655	xdigs = 0;
656
657	/*
658	 * Scan the format for conversions (`%' character).
659	 */
660	for (;;) {
661		size_t nc;
662		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
663			/* void */;
664		if ((nc = fmt - cp) != 0) {
665			PRINT(cp, nc);
666			ret += nc;
667		}
668		if (ch == '\0')
669			goto done;
670		fmt++;		/* skip over '%' */
671
672		flags = 0;
673		dprec = 0;
674		width = 0;
675		prec = -1;
676		sign = '\0';
677
678rflag:		ch = *fmt++;
679reswitch:	switch (ch) {
680		case ' ':
681			/*
682			 * ``If the space and + flags both appear, the space
683			 * flag will be ignored.''
684			 *	-- ANSI X3J11
685			 */
686			if (!sign)
687				sign = ' ';
688			goto rflag;
689		case '#':
690			flags |= ALT;
691			goto rflag;
692		case '*':
693			/*
694			 * ``A negative field width argument is taken as a
695			 * - flag followed by a positive field width.''
696			 *	-- ANSI X3J11
697			 * They don't exclude field widths read from args.
698			 */
699			if ((width = va_arg(ap, int)) >= 0)
700				goto rflag;
701			width = -width;
702			/* FALLTHROUGH */
703		case '-':
704			flags |= LADJUST;
705			goto rflag;
706		case '+':
707			sign = '+';
708			goto rflag;
709		case '.':
710			if ((ch = *fmt++) == '*') {
711				n = va_arg(ap, int);
712				prec = n < 0 ? -1 : n;
713				goto rflag;
714			}
715			n = 0;
716			while (is_digit(ch)) {
717				n = 10 * n + to_digit(ch);
718				ch = *fmt++;
719			}
720			prec = n < 0 ? -1 : n;
721			goto reswitch;
722		case '0':
723			/*
724			 * ``Note that 0 is taken as a flag, not as the
725			 * beginning of a field width.''
726			 *	-- ANSI X3J11
727			 */
728			flags |= ZEROPAD;
729			goto rflag;
730		case '1': case '2': case '3': case '4':
731		case '5': case '6': case '7': case '8': case '9':
732			n = 0;
733			do {
734				n = 10 * n + to_digit(ch);
735				ch = *fmt++;
736			} while (is_digit(ch));
737			width = n;
738			goto reswitch;
739#ifdef FLOATING_POINT
740		case 'L':
741			flags |= LONGDBL;
742			goto rflag;
743#endif
744		case 'h':
745			flags |= SHORTINT;
746			goto rflag;
747#if SIZEOF_PTRDIFF_T == SIZEOF_LONG
748		case 't':
749#endif
750#if SIZEOF_SIZE_T == SIZEOF_LONG
751		case 'z':
752#endif
753		case 'l':
754#ifdef _HAVE_SANE_QUAD_
755			if (*fmt == 'l') {
756				fmt++;
757				flags |= QUADINT;
758			} else {
759				flags |= LONGINT;
760			}
761#else
762			flags |= LONGINT;
763#endif
764			goto rflag;
765#ifdef _HAVE_SANE_QUAD_
766#if SIZEOF_PTRDIFF_T == SIZEOF_LONG_LONG
767		case 't':
768#endif
769#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
770		case 'z':
771#endif
772		case 'q':
773			flags |= QUADINT;
774			goto rflag;
775#endif /* _HAVE_SANE_QUAD_ */
776#ifdef _WIN32
777		case 'I':
778			if (*fmt == '3' && *(fmt + 1) == '2') {
779			    fmt += 2;
780			    flags |= LONGINT;
781			}
782#ifdef _HAVE_SANE_QUAD_
783			else if (*fmt == '6' && *(fmt + 1) == '4') {
784			    fmt += 2;
785			    flags |= QUADINT;
786			}
787#endif
788			else
789#if defined(_HAVE_SANE_QUAD_) && SIZEOF_SIZE_T == SIZEOF_LONG_LONG
790			    flags |= QUADINT;
791#else
792			    flags |= LONGINT;
793#endif
794			goto rflag;
795#endif
796		case 'c':
797			cp = buf;
798			*buf = (char)va_arg(ap, int);
799			size = 1;
800			sign = '\0';
801			break;
802		case 'i':
803#ifdef _HAVE_SANE_QUAD_
804# define INTPTR_MASK (QUADINT|LONGINT|SHORTINT)
805#else
806# define INTPTR_MASK (LONGINT|SHORTINT)
807#endif
808#if defined _HAVE_SANE_QUAD_ && SIZEOF_VOIDP == SIZEOF_LONG_LONG
809# define INTPTR_FLAG QUADINT
810#elif SIZEOF_VOIDP == SIZEOF_LONG
811# define INTPTR_FLAG LONGINT
812#else
813# define INTPTR_FLAG 0
814#endif
815			if (fp->vextra && (flags & INTPTR_MASK) == INTPTR_FLAG) {
816				FLUSH();
817#if defined _HAVE_SANE_QUAD_ && SIZEOF_VOIDP == SIZEOF_LONG_LONG
818				uqval = va_arg(ap, u_quad_t);
819				cp = (*fp->vextra)(fp, sizeof(uqval), &uqval, &fieldsz, sign);
820#else
821				ulval = va_arg(ap, u_long);
822				cp = (*fp->vextra)(fp, sizeof(ulval), &ulval, &fieldsz, sign);
823#endif
824				sign = '\0';
825				if (!cp) goto error;
826				if (prec < 0) goto long_len;
827				size = fieldsz < prec ? (int)fieldsz : prec;
828				break;
829			}
830			goto decimal;
831		case 'D':
832			flags |= LONGINT;
833			/*FALLTHROUGH*/
834		case 'd':
835		decimal:
836#ifdef _HAVE_SANE_QUAD_
837			if (flags & QUADINT) {
838				uqval = va_arg(ap, quad_t);
839				if ((quad_t)uqval < 0) {
840					uqval = -(quad_t)uqval;
841					sign = '-';
842				}
843			} else
844#endif /* _HAVE_SANE_QUAD_ */
845			{
846				ulval = SARG();
847				if ((long)ulval < 0) {
848					ulval = (u_long)(-(long)ulval);
849					sign = '-';
850				}
851			}
852			base = 10;
853			goto number;
854#ifdef FLOATING_POINT
855		case 'a':
856		case 'A':
857			if (prec > 0) {
858				flags |= ALT;
859				prec++;
860				fprec = prec;
861			}
862			goto fp_begin;
863		case 'e':		/* anomalous precision */
864		case 'E':
865			if (prec != 0)
866				flags |= ALT;
867			prec = (prec == -1) ?
868				DEFPREC + 1 : (fprec = prec + 1);
869			/* FALLTHROUGH */
870			goto fp_begin;
871		case 'f':		/* always print trailing zeroes */
872			if (prec != 0)
873				flags |= ALT;
874		case 'g':
875		case 'G':
876			if (prec == -1)
877				prec = DEFPREC;
878			else
879				fprec = prec;
880fp_begin:		_double = va_arg(ap, double);
881			/* do this before tricky precision changes */
882			if (isinf(_double)) {
883				if (_double < 0)
884					sign = '-';
885				cp = "Inf";
886				size = 3;
887				break;
888			}
889			if (isnan(_double)) {
890				cp = "NaN";
891				size = 3;
892				break;
893			}
894			flags |= FPT;
895			cp = cvt(_double, (prec < MAXFRACT ? prec : MAXFRACT), flags, &softsign,
896				&expt, ch, &ndig, buf);
897			if (ch == 'g' || ch == 'G') {
898				if (expt <= -4 || (expt > prec && expt > 1))
899					ch = (ch == 'g') ? 'e' : 'E';
900				else
901					ch = 'g';
902			}
903			if (ch == 'a' || ch == 'A') {
904				flags |= HEXPREFIX;
905				--expt;
906				expsize = exponent(expstr, expt, ch + 'p' - 'a');
907				ch += 'x' - 'a';
908				size = expsize + ndig;
909				if (ndig > 1 || flags & ALT)
910					++size; /* floating point */
911			}
912			else if (ch <= 'e') {	/* 'e' or 'E' fmt */
913				--expt;
914				expsize = exponent(expstr, expt, ch);
915				size = expsize + ndig;
916				if (ndig > 1 || flags & ALT)
917					++fprec, ++size;
918			} else if (ch == 'f') {		/* f fmt */
919				if (expt > 0) {
920					size = expt;
921					if (prec || flags & ALT)
922						size += prec + 1;
923				} else if (!prec) { /* "0" */
924					size = 1;
925					if (flags & ALT)
926						size += 1;
927				} else	/* "0.X" */
928					size = prec + 2;
929			} else if (expt >= ndig) {	/* fixed g fmt */
930				size = expt;
931				if (flags & ALT)
932					++size;
933			} else
934				size = ndig + (expt > 0 ?
935					1 : 2 - expt);
936
937			if (softsign)
938				sign = '-';
939			break;
940#endif /* FLOATING_POINT */
941		case 'n':
942#ifdef _HAVE_SANE_QUAD_
943			if (flags & QUADINT)
944				*va_arg(ap, quad_t *) = ret;
945			else if (flags & LONGINT)
946#else /* _HAVE_SANE_QUAD_ */
947			if (flags & LONGINT)
948#endif /* _HAVE_SANE_QUAD_ */
949				*va_arg(ap, long *) = ret;
950			else if (flags & SHORTINT)
951				*va_arg(ap, short *) = (short)ret;
952			else
953				*va_arg(ap, int *) = (int)ret;
954			continue;	/* no output */
955		case 'O':
956			flags |= LONGINT;
957			/*FALLTHROUGH*/
958		case 'o':
959#ifdef _HAVE_SANE_QUAD_
960			if (flags & QUADINT)
961				uqval = va_arg(ap, u_quad_t);
962			else
963#endif /* _HAVE_SANE_QUAD_ */
964				ulval = UARG();
965			base = 8;
966			goto nosign;
967		case 'p':
968			/*
969			 * ``The argument shall be a pointer to void.  The
970			 * value of the pointer is converted to a sequence
971			 * of printable characters, in an implementation-
972			 * defined manner.''
973			 *	-- ANSI X3J11
974			 */
975			prec = (int)(sizeof(void*)*CHAR_BIT/4);
976#ifdef _HAVE_LLP64_
977			uqval = (u_quad_t)va_arg(ap, void *);
978			flags = (flags) | QUADINT | HEXPREFIX;
979#else
980			ulval = (u_long)va_arg(ap, void *);
981#ifdef _HAVE_SANE_QUAD_
982			flags = (flags & ~QUADINT) | HEXPREFIX;
983#else /* _HAVE_SANE_QUAD_ */
984			flags = (flags) | HEXPREFIX;
985#endif /* _HAVE_SANE_QUAD_ */
986#endif
987			base = 16;
988			xdigs = "0123456789abcdef";
989			ch = 'x';
990			goto nosign;
991		case 's':
992			if ((cp = va_arg(ap, char *)) == NULL)
993				cp = "(null)";
994			if (prec >= 0) {
995				/*
996				 * can't use strlen; can only look for the
997				 * NUL in the first `prec' characters, and
998				 * strlen() will go further.
999				 */
1000				const char *p = (char *)memchr(cp, 0, prec);
1001
1002				if (p != NULL && (p - cp) > prec)
1003					size = (int)(p - cp);
1004				else
1005					size = prec;
1006			}
1007			else {
1008				fieldsz = strlen(cp);
1009				goto long_len;
1010			}
1011			sign = '\0';
1012			break;
1013		case 'U':
1014			flags |= LONGINT;
1015			/*FALLTHROUGH*/
1016		case 'u':
1017#ifdef _HAVE_SANE_QUAD_
1018			if (flags & QUADINT)
1019				uqval = va_arg(ap, u_quad_t);
1020			else
1021#endif /* _HAVE_SANE_QUAD_ */
1022				ulval = UARG();
1023			base = 10;
1024			goto nosign;
1025		case 'X':
1026			xdigs = "0123456789ABCDEF";
1027			goto hex;
1028		case 'x':
1029			xdigs = "0123456789abcdef";
1030hex:
1031#ifdef _HAVE_SANE_QUAD_
1032			if (flags & QUADINT)
1033				uqval = va_arg(ap, u_quad_t);
1034			else
1035#endif /* _HAVE_SANE_QUAD_ */
1036				ulval = UARG();
1037			base = 16;
1038			/* leading 0x/X only if non-zero */
1039			if (flags & ALT &&
1040#ifdef _HAVE_SANE_QUAD_
1041			    (flags & QUADINT ? uqval != 0 : ulval != 0)
1042#else /* _HAVE_SANE_QUAD_ */
1043			    ulval != 0
1044#endif /* _HAVE_SANE_QUAD_ */
1045			    )
1046				flags |= HEXPREFIX;
1047
1048			/* unsigned conversions */
1049nosign:			sign = '\0';
1050			/*
1051			 * ``... diouXx conversions ... if a precision is
1052			 * specified, the 0 flag will be ignored.''
1053			 *	-- ANSI X3J11
1054			 */
1055number:			if ((dprec = prec) >= 0)
1056				flags &= ~ZEROPAD;
1057
1058			/*
1059			 * ``The result of converting a zero value with an
1060			 * explicit precision of zero is no characters.''
1061			 *	-- ANSI X3J11
1062			 */
1063#ifdef _HAVE_SANE_QUAD_
1064			if (flags & QUADINT) {
1065				if (uqval != 0 || prec != 0)
1066					cp = BSD__uqtoa(uqval, ebuf, base,
1067					    flags & ALT, xdigs);
1068			} else
1069#else /* _HAVE_SANE_QUAD_ */
1070#endif /* _HAVE_SANE_QUAD_ */
1071			{
1072				if (ulval != 0 || prec != 0)
1073					cp = BSD__ultoa(ulval, ebuf, base,
1074					    flags & ALT, xdigs);
1075			}
1076			size = (int)(ebuf - cp);
1077			break;
1078		default:	/* "%?" prints ?, unless ? is NUL */
1079			if (ch == '\0')
1080				goto done;
1081			/* pretend it was %c with argument ch */
1082			cp = buf;
1083			*buf = ch;
1084			size = 1;
1085			sign = '\0';
1086			break;
1087		}
1088
1089		/*
1090		 * All reasonable formats wind up here.  At this point, `cp'
1091		 * points to a string which (if not flags&LADJUST) should be
1092		 * padded out to `width' places.  If flags&ZEROPAD, it should
1093		 * first be prefixed by any sign or other prefix; otherwise,
1094		 * it should be blank padded before the prefix is emitted.
1095		 * After any left-hand padding and prefixing, emit zeroes
1096		 * required by a decimal [diouxX] precision, then print the
1097		 * string proper, then emit zeroes required by any leftover
1098		 * floating precision; finally, if LADJUST, pad with blanks.
1099		 *
1100		 * Compute actual size, so we know how much to pad.
1101		 * fieldsz excludes decimal prec; realsz includes it.
1102		 */
1103		fieldsz = size;
1104long_len:
1105		if (sign)
1106			fieldsz++;
1107		if (flags & HEXPREFIX)
1108			fieldsz += 2;
1109		realsz = dprec > fieldsz ? dprec : fieldsz;
1110
1111		/* right-adjusting blank padding */
1112		if ((flags & (LADJUST|ZEROPAD)) == 0)
1113			PAD_L(width - realsz, blanks);
1114
1115		/* prefix */
1116		if (sign) {
1117			PRINT(&sign, 1);
1118		}
1119		if (flags & HEXPREFIX) {
1120			ox[0] = '0';
1121			ox[1] = ch;
1122			PRINT(ox, 2);
1123		}
1124
1125		/* right-adjusting zero padding */
1126		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1127			PAD_L(width - realsz, zeroes);
1128
1129		/* leading zeroes from decimal precision */
1130		PAD_L(dprec - fieldsz, zeroes);
1131		if (sign)
1132			fieldsz--;
1133		if (flags & HEXPREFIX)
1134			fieldsz -= 2;
1135
1136		/* the string or number proper */
1137#ifdef FLOATING_POINT
1138		if ((flags & FPT) == 0) {
1139			PRINT(cp, fieldsz);
1140		} else {	/* glue together f_p fragments */
1141			if (flags & HEXPREFIX) {
1142				if (ndig > 1 || flags & ALT) {
1143					ox[2] = *cp++;
1144					ox[3] = '.';
1145					PRINT(ox+2, 2);
1146					if (ndig > 0) PRINT(cp, ndig-1);
1147				} else	/* XpYYY */
1148					PRINT(cp, 1);
1149				PAD(fprec-ndig, zeroes);
1150				PRINT(expstr, expsize);
1151			}
1152			else if (ch >= 'f') {	/* 'f' or 'g' */
1153				if (_double == 0) {
1154				/* kludge for __dtoa irregularity */
1155					if (ndig <= 1 &&
1156					    (flags & ALT) == 0) {
1157						PRINT("0", 1);
1158					} else {
1159						PRINT("0.", 2);
1160						PAD((ndig >= fprec ? ndig - 1 : fprec - (ch != 'f')),
1161						    zeroes);
1162					}
1163				} else if (expt == 0 && ndig == 0 && (flags & ALT) == 0) {
1164					PRINT("0", 1);
1165				} else if (expt <= 0) {
1166					PRINT("0.", 2);
1167					PAD(-expt, zeroes);
1168					PRINT(cp, ndig);
1169					if (flags & ALT)
1170						PAD(fprec - ndig + (ch == 'f' ? expt : 0), zeroes);
1171				} else if (expt >= ndig) {
1172					PRINT(cp, ndig);
1173					PAD(expt - ndig, zeroes);
1174					if (flags & ALT)
1175						PRINT(".", 1);
1176				} else {
1177					PRINT(cp, expt);
1178					cp += expt;
1179					PRINT(".", 1);
1180					PRINT(cp, ndig-expt);
1181					if (flags & ALT)
1182						PAD(fprec - ndig + (ch == 'f' ? expt : 0), zeroes);
1183				}
1184			} else {	/* 'e' or 'E' */
1185				if (ndig > 1 || flags & ALT) {
1186					ox[0] = *cp++;
1187					ox[1] = '.';
1188					PRINT(ox, 2);
1189					if (_double /*|| flags & ALT == 0*/) {
1190						PRINT(cp, ndig-1);
1191					} else	/* 0.[0..] */
1192						/* __dtoa irregularity */
1193						PAD(ndig - 1, zeroes);
1194					if (flags & ALT) PAD(fprec - ndig - 1, zeroes);
1195				} else	/* XeYYY */
1196					PRINT(cp, 1);
1197				PRINT(expstr, expsize);
1198			}
1199		}
1200#else
1201		PRINT(cp, fieldsz);
1202#endif
1203		/* left-adjusting padding (always blank) */
1204		if (flags & LADJUST)
1205			PAD_L(width - realsz, blanks);
1206
1207		/* finally, adjust ret */
1208		ret += width > realsz ? width : realsz;
1209
1210		FLUSH();	/* copy out the I/O vectors */
1211	}
1212done:
1213	FLUSH();
1214error:
1215	return (BSD__sferror(fp) ? EOF : ret);
1216	/* NOTREACHED */
1217}
1218
1219#ifdef FLOATING_POINT
1220
1221extern char *BSD__dtoa(double, int, int, int *, int *, char **);
1222extern char *BSD__hdtoa(double, const char *, int, int *, int *, char **);
1223
1224static char *
1225cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch, int *length, char *buf)
1226{
1227	int mode, dsgn;
1228	char *digits, *bp, *rve;
1229
1230	if (ch == 'f')
1231		mode = 3;
1232	else {
1233		mode = 2;
1234	}
1235	if (value < 0) {
1236		value = -value;
1237		*sign = '-';
1238	} else if (value == 0.0 && 1.0/value < 0) {
1239	    *sign = '-';
1240	} else {
1241	    *sign = '\000';
1242	}
1243	if (ch == 'a' || ch =='A') {
1244	    digits = BSD__hdtoa(value,
1245		    ch == 'a' ? "0123456789abcdef" : "0123456789ABCDEF",
1246		    ndigits, decpt, &dsgn, &rve);
1247	}
1248	else {
1249	    digits = BSD__dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1250	}
1251	buf[0] = 0; /* rve - digits may be 0 */
1252	memcpy(buf, digits, rve - digits);
1253	xfree(digits);
1254	rve = buf + (rve - digits);
1255	digits = buf;
1256	if (flags & ALT) {	/* Print trailing zeros */
1257		bp = digits + ndigits;
1258		if (ch == 'f') {
1259			if (*digits == '0' && value)
1260				*decpt = -ndigits + 1;
1261			bp += *decpt;
1262		}
1263		while (rve < bp)
1264			*rve++ = '0';
1265	}
1266	*length = (int)(rve - digits);
1267	return (digits);
1268}
1269
1270static int
1271exponent(char *p0, int exp, int fmtch)
1272{
1273	register char *p, *t;
1274	char expbuf[2 + (MAXEXP < 1000 ? 3 : MAXEXP < 10000 ? 4 : 5)]; /* >= 2 + ceil(log10(MAXEXP)) */
1275
1276	p = p0;
1277	*p++ = fmtch;
1278	if (exp < 0) {
1279		exp = -exp;
1280		*p++ = '-';
1281	}
1282	else
1283		*p++ = '+';
1284	t = expbuf + sizeof(expbuf);
1285	if (exp > 9) {
1286		do {
1287			*--t = to_char(exp % 10);
1288		} while ((exp /= 10) > 9);
1289		*--t = to_char(exp);
1290		for (; t < expbuf + sizeof(expbuf); *p++ = *t++);
1291	}
1292	else {
1293		if (fmtch & 15) *p++ = '0'; /* other than p or P */
1294		*p++ = to_char(exp);
1295	}
1296	return (int)(p - p0);
1297}
1298#endif /* FLOATING_POINT */
1299
1300int
1301ruby_vsnprintf(char *str, size_t n, const char *fmt, va_list ap)
1302{
1303	int ret;
1304	FILE f;
1305
1306	if ((int)n < 1)
1307		return (EOF);
1308	f._flags = __SWR | __SSTR;
1309	f._bf._base = f._p = (unsigned char *)str;
1310	f._bf._size = f._w = n - 1;
1311	f.vwrite = BSD__sfvwrite;
1312	f.vextra = 0;
1313	ret = (int)BSD_vfprintf(&f, fmt, ap);
1314	*f._p = 0;
1315	return (ret);
1316}
1317
1318int
1319ruby_snprintf(char *str, size_t n, char const *fmt, ...)
1320{
1321	int ret;
1322	va_list ap;
1323	FILE f;
1324
1325	if ((int)n < 1)
1326		return (EOF);
1327
1328	va_start(ap, fmt);
1329	f._flags = __SWR | __SSTR;
1330	f._bf._base = f._p = (unsigned char *)str;
1331	f._bf._size = f._w = n - 1;
1332	f.vwrite = BSD__sfvwrite;
1333	f.vextra = 0;
1334	ret = (int)BSD_vfprintf(&f, fmt, ap);
1335	*f._p = 0;
1336	va_end(ap);
1337	return (ret);
1338}
1339