2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 * From ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
41 * paragraph 3 above is now null and void.
45 * fjc 7-31-97 Modified by Mib Software to be a standalone snprintf.c module.
46 * http://www.mibsoftware.com
47 * Mib Software does not warrant this software any differently than the
48 * University of California, Berkeley as described above. All warranties
49 * are disclaimed. Use this software at your own risk.
51 * All code referencing FILE * functions was eliminated, since it could
52 * never be called. All header files and necessary files are collapsed
53 * into one file, internal functions are declared static. This should
54 * allow inclusion into libraries with less chance of namespace collisions.
56 * snprintf should be the only externally visible item.
58 * As of 7-31-97 FLOATING_POINT is NOT provided. The code is somewhat
59 * non-portable, so it is disabled.
62 /* Define FLOATING_POINT to get floating point. */
64 #define FLOATING_POINT
67 #include <sys/types.h>
68 #define u_long unsigned long
69 #define u_short unsigned short
70 #define u_int unsigned int
86 #define _BSD_VA_LIST_ va_list
96 /* assuming 32bit(2's compliment) long */
97 # define LONG_MAX 2147483647
102 #if defined(__hpux) && !defined(__GNUC__)
109 #endif /* People who don't like const sys_error */
118 * NB: to fit things in six character monocase externals, the stdio
119 * code uses the prefix `__s' for stdio objects, typically followed
120 * by a three-character attempt at a mnemonic.
125 unsigned char *_base;
131 * stdio state variables.
133 * The following always hold:
135 * if (_flags&(__SLBF|__SWR)) == (__SLBF|__SWR),
136 * _lbfsize is -_bf._size, else _lbfsize is 0
137 * if _flags&__SRD, _w is 0
138 * if _flags&__SWR, _r is 0
140 * This ensures that the getc and putc macros (or inline functions) never
141 * try to write or read from a file that is in `read' or `write' mode.
142 * (Moreover, they can, and do, automatically switch from read mode to
143 * write mode, and back, on "r+" and "w+" files.)
145 * _lbfsize is used only to make the inline line-buffered output stream
146 * code as compact as possible.
148 * _ub, _up, and _ur are used when ungetc() pushes back more characters
149 * than fit in the current _bf, or when ungetc() pushes back a character
150 * that does not match the previous one in _bf. When this happens,
151 * _ub._base becomes non-nil (i.e., a stream has ungetc() data iff
152 * _ub._base!=NULL) and _up and _ur save the current values of _p and _r.
154 * NB: see WARNING above before changing the layout of this structure!
156 typedef struct __sFILE {
157 unsigned char *_p; /* current position in (some) buffer */
158 int _r; /* read space left for getc() */
159 int _w; /* write space left for putc() */
160 short _flags; /* flags, below; this FILE is free if 0 */
161 short _file; /* fileno, if Unix descriptor, else -1 */
162 struct __sbuf _bf; /* the buffer (at least 1 byte, if !NULL) */
163 int _lbfsize; /* 0 or -_bf._size, for inline putc */
167 #define __SLBF 0x0001 /* line buffered */
168 #define __SNBF 0x0002 /* unbuffered */
169 #define __SRD 0x0004 /* OK to read */
170 #define __SWR 0x0008 /* OK to write */
171 /* RD and WR are never simultaneously asserted */
172 #define __SRW 0x0010 /* open for reading & writing */
173 #define __SEOF 0x0020 /* found EOF */
174 #define __SERR 0x0040 /* found error */
175 #define __SMBF 0x0080 /* _buf is from malloc */
176 #define __SAPP 0x0100 /* fdopen()ed in append mode */
177 #define __SSTR 0x0200 /* this is an sprintf/snprintf string */
178 #define __SOPT 0x0400 /* do fseek() optimisation */
179 #define __SNPT 0x0800 /* do not do fseek() optimisation */
180 #define __SOFF 0x1000 /* set iff _offset is in fact correct */
181 #define __SMOD 0x2000 /* true => fgetln modified _p text */
187 #define __sfeof(p) (((p)->_flags & __SEOF) != 0)
188 #define __sferror(p) (((p)->_flags & __SERR) != 0)
189 #define __sclearerr(p) ((void)((p)->_flags &= ~(__SERR|__SEOF)))
190 #define __sfileno(p) ((p)->_file)
192 #define feof(p) __sfeof(p)
193 #define ferror(p) __sferror(p)
194 #define clearerr(p) __sclearerr(p)
197 #define fileno(p) __sfileno(p)
201 #if defined(__hpux) && !defined(__GNUC__) || defined(__DECC) || defined(__DJGPP__)
206 * I/O descriptors for __sfvwrite().
213 struct __siov *uio_iov;
219 * Write some memory regions. Return zero on success, EOF on error.
221 * This routine is large and unsightly, but most of the ugliness due
222 * to the three different kinds of output buffering is handled here.
224 static BSD__sfvwrite(fp, uio)
226 register struct __suio *uio;
230 register struct __siov *iov;
233 if ((len = uio->uio_resid) == 0)
236 #define MIN(a, b) ((a) < (b) ? (a) : (b))
238 #define COPY(n) (void)memcpy((void *)fp->_p, (void *)p, (size_t)(n))
244 #define GETIOV(extra_work) \
248 len = iov->iov_len; \
251 if (fp->_flags & __SNBF) {
252 /* fjc 7-31-97 Will never happen. We are working with
255 } else if ((fp->_flags & __SLBF) == 0) {
257 * Fully buffered: fill partially full buffer, if any,
258 * and then flush. If there is no partial buffer, write
259 * one _bf._size byte chunk directly (without copying).
261 * String output is a special case: write as many bytes
262 * as fit, but pretend we wrote everything. This makes
263 * snprintf() return the number of bytes needed, rather
264 * than the number used, and avoids its write function
265 * (so that the write function can be invalid).
270 if (fp->_flags & __SSTR) {
273 COPY(w); /* copy MIN(fp->_w,len), */
276 w = len; /* but pretend copied all */
278 /* fjc 7-31-97 Will never happen. We are working with
284 } while ((uio->uio_resid -= w) != 0);
286 /* fjc 7-31-97 Will never happen. We are working with
293 fp->_flags |= __SERR;
298 * Actual printf innards.
300 * This code is large and complicated...
303 #if !defined(__CYGWIN32__) && defined(__hpux) && !defined(__GNUC__)
308 * Flush out all the vectors defined by the given uio,
309 * then reset it so that it can be reused.
314 register struct __suio *uio;
318 if (uio->uio_resid == 0) {
322 err = BSD__sfvwrite(fp, uio);
330 * Helper function for `fprintf to unbuffered unix file': creates a
331 * temporary buffer. We only work on write-only files; this avoids
332 * worries about ungetc buffers and so forth.
335 BSD__sbprintf(fp, fmt, ap)
340 /* We don't support files. */
346 * Macros for converting digits to letters and vice versa
348 #define to_digit(c) ((c) - '0')
349 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
350 #define to_char(n) ((n) + '0')
353 * Convert an unsigned long to ASCII for printf purposes, returning
354 * a pointer to the first character of the string representation.
355 * Octal numbers can be forced to have a leading zero; hex numbers
356 * use the given digits.
359 BSD__ultoa(val, endp, base, octzero, xdigs)
365 register char *cp = endp;
369 * Handle the three cases separately, in the hope of getting
370 * better/faster code.
374 if (val < 10) { /* many numbers are 1 digit */
375 *--cp = to_char(val);
379 * On many machines, unsigned arithmetic is harder than
380 * signed arithmetic, so we do at most one unsigned mod and
381 * divide; this is sufficient to reduce the range of
382 * the incoming value to where signed arithmetic works.
384 if (val > LONG_MAX) {
385 *--cp = to_char(val % 10);
390 *--cp = to_char(sval % 10);
397 *--cp = to_char(val & 7);
400 if (octzero && *cp != '0')
406 *--cp = xdigs[val & 15];
415 break; /* fjc 7-31-97. Don't reference abort() here */
420 #ifdef FLOATING_POINT
422 /* #include "floatio.h" */
432 #define BUF (MAXEXP+MAXFRACT+1) /* + decimal point */
435 static char *cvt __P((double, int, int, char *, int *, int, int *));
436 static int exponent __P((char *, int, int));
438 #else /* no FLOATING_POINT */
442 #endif /* FLOATING_POINT */
446 * Flags used during conversion.
448 #define ALT 0x001 /* alternate form */
449 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
450 #define LADJUST 0x004 /* left adjustment */
451 #define LONGDBL 0x008 /* long double; unimplemented */
452 #define LONGINT 0x010 /* long integer */
454 #ifdef _HAVE_SANE_QUAD_
455 #define QUADINT 0x020 /* quad integer */
456 #endif /* _HAVE_SANE_QUAD_ */
458 #define SHORTINT 0x040 /* short integer */
459 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
460 #define FPT 0x100 /* Floating point number */
462 BSD_vfprintf(fp, fmt0, ap)
467 register char *fmt; /* format string */
468 register int ch; /* character from fmt */
469 register int n; /* handy integer (short term usage) */
470 register char *cp; /* handy char pointer (short term usage) */
471 register struct __siov *iovp;/* for PRINT macro */
472 register int flags; /* flags as above */
473 int ret; /* return value accumulator */
474 int width; /* width from format (%8d), or 0 */
475 int prec; /* precision from format (%.3d), or -1 */
476 char sign; /* sign prefix (' ', '+', '-', or \0) */
477 #ifdef FLOATING_POINT
478 char softsign; /* temporary negative sign for floats */
479 double _double; /* double precision arguments %[eEfgG] */
480 int expt; /* integer value of exponent */
481 int expsize; /* character count for expstr */
482 int ndig; /* actual number of digits returned by cvt */
483 char expstr[7]; /* buffer for exponent string */
485 u_long ulval; /* integer arguments %[diouxX] */
486 #ifdef _HAVE_SANE_QUAD_
487 u_quad_t uqval; /* %q integers */
488 #endif /* _HAVE_SANE_QUAD_ */
489 int base; /* base for [diouxX] conversion */
490 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
491 int fieldsz; /* field size expanded by sign, etc */
492 int realsz; /* field size expanded by dprec */
493 int size; /* size of converted field or string */
494 char *xdigs; /* digits for [xX] conversion */
496 struct __suio uio; /* output information: summary */
497 struct __siov iov[NIOV];/* ... and individual io vectors */
498 char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
499 char ox[2]; /* space for 0x hex-prefix */
502 * Choose PADSIZE to trade efficiency vs. size. If larger printf
503 * fields occur frequently, increase PADSIZE and make the initialisers
506 #define PADSIZE 16 /* pad chunk size */
507 static char blanks[PADSIZE] =
508 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
509 static char zeroes[PADSIZE] =
510 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
513 * BEWARE, these `goto error' on error, and PAD uses `n'.
515 #define PRINT(ptr, len) { \
516 iovp->iov_base = (ptr); \
517 iovp->iov_len = (len); \
518 uio.uio_resid += (len); \
520 if (++uio.uio_iovcnt >= NIOV) { \
521 if (BSD__sprint(fp, &uio)) \
526 #define PAD(howmany, with) { \
527 if ((n = (howmany)) > 0) { \
528 while (n > PADSIZE) { \
529 PRINT(with, PADSIZE); \
536 if (uio.uio_resid && BSD__sprint(fp, &uio)) \
538 uio.uio_iovcnt = 0; \
543 * To extend shorts properly, we need both signed and unsigned
544 * argument extraction methods.
547 (flags&LONGINT ? va_arg(ap, long) : \
548 flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
549 (long)va_arg(ap, int))
551 (flags&LONGINT ? va_arg(ap, u_long) : \
552 flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
553 (u_long)va_arg(ap, u_int))
555 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
556 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
558 return (BSD__sbprintf(fp, fmt0, ap));
561 uio.uio_iov = iovp = iov;
567 * Scan the format for conversions (`%' character).
570 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
572 if ((n = fmt - cp) != 0) {
578 fmt++; /* skip over '%' */
587 reswitch: switch (ch) {
590 * ``If the space and + flags both appear, the space
591 * flag will be ignored.''
602 * ``A negative field width argument is taken as a
603 * - flag followed by a positive field width.''
605 * They don't exclude field widths read from args.
607 if ((width = va_arg(ap, int)) >= 0)
618 if ((ch = *fmt++) == '*') {
620 prec = n < 0 ? -1 : n;
624 while (is_digit(ch)) {
625 n = 10 * n + to_digit(ch);
628 prec = n < 0 ? -1 : n;
632 * ``Note that 0 is taken as a flag, not as the
633 * beginning of a field width.''
638 case '1': case '2': case '3': case '4':
639 case '5': case '6': case '7': case '8': case '9':
642 n = 10 * n + to_digit(ch);
644 } while (is_digit(ch));
647 #ifdef FLOATING_POINT
658 #ifdef _HAVE_SANE_QUAD_
662 #endif /* _HAVE_SANE_QUAD_ */
664 *(cp = buf) = va_arg(ap, int);
673 #ifdef _HAVE_SANE_QUAD_
674 if (flags & QUADINT) {
675 uqval = va_arg(ap, quad_t);
676 if ((quad_t)uqval < 0) {
681 #else /* _HAVE_SANE_QUAD_ */
683 #endif /* _HAVE_SANE_QUAD_ */
685 if ((long)ulval < 0) {
692 #ifdef FLOATING_POINT
693 case 'e': /* anomalous precision */
695 prec = (prec == -1) ?
696 DEFPREC + 1 : prec + 1;
699 case 'f': /* always print trailing zeroes */
706 fp_begin: _double = va_arg(ap, double);
707 /* do this before tricky precision changes */
708 if (isinf(_double)) {
715 if (isnan(_double)) {
721 cp = cvt(_double, prec, flags, &softsign,
723 if (ch == 'g' || ch == 'G') {
724 if (expt <= -4 || expt > prec)
725 ch = (ch == 'g') ? 'e' : 'E';
729 if (ch <= 'e') { /* 'e' or 'E' fmt */
731 expsize = exponent(expstr, expt, ch);
732 size = expsize + ndig;
733 if (ndig > 1 || flags & ALT)
735 } else if (ch == 'f') { /* f fmt */
738 if (prec || flags & ALT)
742 } else if (expt >= ndig) { /* fixed g fmt */
747 size = ndig + (expt > 0 ?
753 #endif /* FLOATING_POINT */
755 #ifdef _HAVE_SANE_QUAD_
757 *va_arg(ap, quad_t *) = ret;
758 else if (flags & LONGINT)
759 #else /* _HAVE_SANE_QUAD_ */
761 #endif /* _HAVE_SANE_QUAD_ */
762 *va_arg(ap, long *) = ret;
763 else if (flags & SHORTINT)
764 *va_arg(ap, short *) = ret;
766 *va_arg(ap, int *) = ret;
767 continue; /* no output */
772 #ifdef _HAVE_SANE_QUAD_
774 uqval = va_arg(ap, u_quad_t);
776 #endif /* _HAVE_SANE_QUAD_ */
782 * ``The argument shall be a pointer to void. The
783 * value of the pointer is converted to a sequence
784 * of printable characters, in an implementation-
788 ulval = (u_long)va_arg(ap, void *);
790 xdigs = "0123456789abcdef";
791 #ifdef _HAVE_SANE_QUAD_
792 flags = (flags & ~QUADINT) | HEXPREFIX;
793 #else /* _HAVE_SANE_QUAD_ */
794 flags = (flags) | HEXPREFIX;
795 #endif /* _HAVE_SANE_QUAD_ */
799 if ((cp = va_arg(ap, char *)) == NULL)
803 * can't use strlen; can only look for the
804 * NUL in the first `prec' characters, and
805 * strlen() will go further.
807 char *p = (char *)memchr(cp, 0, prec);
823 #ifdef _HAVE_SANE_QUAD_
825 uqval = va_arg(ap, u_quad_t);
827 #endif /* _HAVE_SANE_QUAD_ */
832 xdigs = "0123456789ABCDEF";
835 xdigs = "0123456789abcdef";
837 #ifdef _HAVE_SANE_QUAD_
839 uqval = va_arg(ap, u_quad_t);
841 #endif /* _HAVE_SANE_QUAD_ */
844 /* leading 0x/X only if non-zero */
846 #ifdef _HAVE_SANE_QUAD_
847 (flags & QUADINT ? uqval != 0 : ulval != 0))
848 #else /* _HAVE_SANE_QUAD_ */
850 #endif /* _HAVE_SANE_QUAD_ */
853 /* unsigned conversions */
856 * ``... diouXx conversions ... if a precision is
857 * specified, the 0 flag will be ignored.''
860 number: if ((dprec = prec) >= 0)
864 * ``The result of converting a zero value with an
865 * explicit precision of zero is no characters.''
869 #ifdef _HAVE_SANE_QUAD_
870 if (flags & QUADINT) {
871 if (uqval != 0 || prec != 0)
872 cp = __uqtoa(uqval, cp, base,
875 #else /* _HAVE_SANE_QUAD_ */
877 #endif /* _HAVE_SANE_QUAD_ */
878 if (ulval != 0 || prec != 0)
879 cp = BSD__ultoa(ulval, cp, base,
882 size = buf + BUF - cp;
884 default: /* "%?" prints ?, unless ? is NUL */
887 /* pretend it was %c with argument ch */
896 * All reasonable formats wind up here. At this point, `cp'
897 * points to a string which (if not flags&LADJUST) should be
898 * padded out to `width' places. If flags&ZEROPAD, it should
899 * first be prefixed by any sign or other prefix; otherwise,
900 * it should be blank padded before the prefix is emitted.
901 * After any left-hand padding and prefixing, emit zeroes
902 * required by a decimal [diouxX] precision, then print the
903 * string proper, then emit zeroes required by any leftover
904 * floating precision; finally, if LADJUST, pad with blanks.
906 * Compute actual size, so we know how much to pad.
907 * fieldsz excludes decimal prec; realsz includes it.
912 else if (flags & HEXPREFIX)
914 realsz = dprec > fieldsz ? dprec : fieldsz;
916 /* right-adjusting blank padding */
917 if ((flags & (LADJUST|ZEROPAD)) == 0)
918 PAD(width - realsz, blanks);
923 } else if (flags & HEXPREFIX) {
929 /* right-adjusting zero padding */
930 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
931 PAD(width - realsz, zeroes);
933 /* leading zeroes from decimal precision */
934 PAD(dprec - fieldsz, zeroes);
936 /* the string or number proper */
937 #ifdef FLOATING_POINT
938 if ((flags & FPT) == 0) {
940 } else { /* glue together f_p fragments */
941 if (ch >= 'f') { /* 'f' or 'g' */
943 /* kludge for __dtoa irregularity */
945 (flags & ALT) == 0) {
949 PAD(ndig - 1, zeroes);
951 } else if (expt <= 0) {
955 } else if (expt >= ndig) {
957 PAD(expt - ndig, zeroes);
964 PRINT(cp, ndig-expt);
966 } else { /* 'e' or 'E' */
967 if (ndig > 1 || flags & ALT) {
971 if (_double || flags & ALT == 0) {
974 /* __dtoa irregularity */
975 PAD(ndig - 1, zeroes);
978 PRINT(expstr, expsize);
984 /* left-adjusting padding (always blank) */
986 PAD(width - realsz, blanks);
988 /* finally, adjust ret */
989 ret += width > realsz ? width : realsz;
991 FLUSH(); /* copy out the I/O vectors */
996 return (__sferror(fp) ? EOF : ret);
1000 #ifdef FLOATING_POINT
1002 extern char *BSD__dtoa __P((double, int, int, int *, int *, char **));
1005 cvt(value, ndigits, flags, sign, decpt, ch, length)
1007 int ndigits, flags, *decpt, ch, *length;
1011 char *digits, *bp, *rve;
1023 digits = BSD__dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1024 if (flags & ALT) { /* Print trailing zeros */
1025 bp = digits + ndigits;
1027 if (*digits == '0' && value)
1028 *decpt = -ndigits + 1;
1031 if (value == 0) /* kludge for __dtoa irregularity */
1036 *length = rve - digits;
1041 exponent(p0, exp, fmtch)
1045 register char *p, *t;
1046 char expbuf[MAXEXP];
1056 t = expbuf + MAXEXP;
1059 *--t = to_char(exp % 10);
1060 } while ((exp /= 10) > 9);
1061 *--t = to_char(exp);
1062 for (; t < expbuf + MAXEXP; *p++ = *t++);
1066 *p++ = to_char(exp);
1070 #endif /* FLOATING_POINT */
1073 vsnprintf(str, n, fmt, ap)
1084 f._flags = __SWR | __SSTR;
1085 f._bf._base = f._p = (unsigned char *)str;
1086 f._bf._size = f._w = n - 1;
1087 ret = BSD_vfprintf(&f, fmt, ap);
1092 #if defined(LIBC_SCCS) && !defined(lint)
1093 static char sccsid[] = "@(#)snprintf.c 8.1 (Berkeley) 6/4/93";
1094 #endif /* LIBC_SCCS and not lint */
1096 #if defined(__STDC__)
1097 # include <stdarg.h>
1099 # include <varargs.h>
1103 #if defined(__STDC__)
1104 snprintf(char *str, size_t n, char const *fmt, ...)
1106 snprintf(str, n, fmt, va_alist)
1119 #if defined(__STDC__)
1124 f._flags = __SWR | __SSTR;
1125 f._bf._base = f._p = (unsigned char *)str;
1126 f._bf._size = f._w = n - 1;
1127 ret = BSD_vfprintf(&f, fmt, ap);