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. 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.
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
36
* From ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
37
* paragraph 3 above is now null and void.
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.
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.
52
* snprintf should be the only externally visible item.
54
* As of 7-31-97 FLOATING_POINT is NOT provided. The code is somewhat
55
* non-portable, so it is disabled.
58
/* Define FLOATING_POINT to get floating point. */
60
#define FLOATING_POINT
63
#include <sys/types.h>
64
#define u_long unsigned long
65
#define u_short unsigned short
66
#define u_int unsigned int
82
#define _BSD_VA_LIST_ va_list
92
/* assuming 32bit(2's compliment) long */
93
# define LONG_MAX 2147483647
98
#if defined(__hpux) && !defined(__GNUC__) && !defined(__STDC__)
105
#endif /* People who don't like const sys_error */
114
* NB: to fit things in six character monocase externals, the stdio
115
* code uses the prefix `__s' for stdio objects, typically followed
116
* by a three-character attempt at a mnemonic.
121
unsigned char *_base;
127
* stdio state variables.
129
* The following always hold:
131
* if (_flags&(__SLBF|__SWR)) == (__SLBF|__SWR),
132
* _lbfsize is -_bf._size, else _lbfsize is 0
133
* if _flags&__SRD, _w is 0
134
* if _flags&__SWR, _r is 0
136
* This ensures that the getc and putc macros (or inline functions) never
137
* try to write or read from a file that is in `read' or `write' mode.
138
* (Moreover, they can, and do, automatically switch from read mode to
139
* write mode, and back, on "r+" and "w+" files.)
141
* _lbfsize is used only to make the inline line-buffered output stream
142
* code as compact as possible.
144
* _ub, _up, and _ur are used when ungetc() pushes back more characters
145
* than fit in the current _bf, or when ungetc() pushes back a character
146
* that does not match the previous one in _bf. When this happens,
147
* _ub._base becomes non-nil (i.e., a stream has ungetc() data iff
148
* _ub._base!=NULL) and _up and _ur save the current values of _p and _r.
150
* NB: see WARNING above before changing the layout of this structure!
152
typedef struct __sFILE {
153
unsigned char *_p; /* current position in (some) buffer */
154
int _r; /* read space left for getc() */
155
int _w; /* write space left for putc() */
156
short _flags; /* flags, below; this FILE is free if 0 */
157
short _file; /* fileno, if Unix descriptor, else -1 */
158
struct __sbuf _bf; /* the buffer (at least 1 byte, if !NULL) */
159
int _lbfsize; /* 0 or -_bf._size, for inline putc */
163
#define __SLBF 0x0001 /* line buffered */
164
#define __SNBF 0x0002 /* unbuffered */
165
#define __SRD 0x0004 /* OK to read */
166
#define __SWR 0x0008 /* OK to write */
167
/* RD and WR are never simultaneously asserted */
168
#define __SRW 0x0010 /* open for reading & writing */
169
#define __SEOF 0x0020 /* found EOF */
170
#define __SERR 0x0040 /* found error */
171
#define __SMBF 0x0080 /* _buf is from malloc */
172
#define __SAPP 0x0100 /* fdopen()ed in append mode */
173
#define __SSTR 0x0200 /* this is an sprintf/snprintf string */
174
#define __SOPT 0x0400 /* do fseek() optimisation */
175
#define __SNPT 0x0800 /* do not do fseek() optimisation */
176
#define __SOFF 0x1000 /* set iff _offset is in fact correct */
177
#define __SMOD 0x2000 /* true => fgetln modified _p text */
183
#define __sfeof(p) (((p)->_flags & __SEOF) != 0)
184
#define __sferror(p) (((p)->_flags & __SERR) != 0)
185
#define __sclearerr(p) ((void)((p)->_flags &= ~(__SERR|__SEOF)))
186
#define __sfileno(p) ((p)->_file)
188
#define feof(p) __sfeof(p)
189
#define ferror(p) __sferror(p)
190
#define clearerr(p) __sclearerr(p)
193
#define fileno(p) __sfileno(p)
197
#if defined(__hpux) && !defined(__GNUC__) || defined(__DECC)
202
* I/O descriptors for __sfvwrite().
209
struct __siov *uio_iov;
215
* Write some memory regions. Return zero on success, EOF on error.
217
* This routine is large and unsightly, but most of the ugliness due
218
* to the three different kinds of output buffering is handled here.
220
static BSD__sfvwrite(fp, uio)
222
register struct __suio *uio;
226
register struct __siov *iov;
229
if ((len = uio->uio_resid) == 0)
232
#define MIN(a, b) ((a) < (b) ? (a) : (b))
234
#define COPY(n) (void)memcpy((void *)fp->_p, (void *)p, (size_t)(n))
240
#define GETIOV(extra_work) \
244
len = iov->iov_len; \
247
if (fp->_flags & __SNBF) {
248
/* fjc 7-31-97 Will never happen. We are working with
251
} else if ((fp->_flags & __SLBF) == 0) {
253
* Fully buffered: fill partially full buffer, if any,
254
* and then flush. If there is no partial buffer, write
255
* one _bf._size byte chunk directly (without copying).
257
* String output is a special case: write as many bytes
258
* as fit, but pretend we wrote everything. This makes
259
* snprintf() return the number of bytes needed, rather
260
* than the number used, and avoids its write function
261
* (so that the write function can be invalid).
266
if (fp->_flags & __SSTR) {
269
COPY(w); /* copy MIN(fp->_w,len), */
272
w = len; /* but pretend copied all */
274
/* fjc 7-31-97 Will never happen. We are working with
280
} while ((uio->uio_resid -= w) != 0);
282
/* fjc 7-31-97 Will never happen. We are working with
289
fp->_flags |= __SERR;
294
* Actual printf innards.
296
* This code is large and complicated...
299
#if !defined(__CYGWIN32__) && defined(__hpux) && !defined(__GNUC__)
304
* Flush out all the vectors defined by the given uio,
305
* then reset it so that it can be reused.
310
register struct __suio *uio;
314
if (uio->uio_resid == 0) {
318
err = BSD__sfvwrite(fp, uio);
326
* Helper function for `fprintf to unbuffered unix file': creates a
327
* temporary buffer. We only work on write-only files; this avoids
328
* worries about ungetc buffers and so forth.
331
BSD__sbprintf(fp, fmt, ap)
336
/* We don't support files. */
342
* Macros for converting digits to letters and vice versa
344
#define to_digit(c) ((c) - '0')
345
#define is_digit(c) ((unsigned)to_digit(c) <= 9)
346
#define to_char(n) ((n) + '0')
349
* Convert an unsigned long to ASCII for printf purposes, returning
350
* a pointer to the first character of the string representation.
351
* Octal numbers can be forced to have a leading zero; hex numbers
352
* use the given digits.
355
BSD__ultoa(val, endp, base, octzero, xdigs)
361
register char *cp = endp;
365
* Handle the three cases separately, in the hope of getting
366
* better/faster code.
370
if (val < 10) { /* many numbers are 1 digit */
371
*--cp = to_char(val);
375
* On many machines, unsigned arithmetic is harder than
376
* signed arithmetic, so we do at most one unsigned mod and
377
* divide; this is sufficient to reduce the range of
378
* the incoming value to where signed arithmetic works.
380
if (val > LONG_MAX) {
381
*--cp = to_char(val % 10);
386
*--cp = to_char(sval % 10);
393
*--cp = to_char(val & 7);
396
if (octzero && *cp != '0')
402
*--cp = xdigs[val & 15];
411
break; /* fjc 7-31-97. Don't reference abort() here */
416
#ifdef FLOATING_POINT
418
/* #include "floatio.h" */
428
#define BUF (MAXEXP+MAXFRACT+1) /* + decimal point */
431
static char *cvt __P((double, int, int, char *, int *, int, int *));
432
static int exponent __P((char *, int, int));
434
#else /* no FLOATING_POINT */
438
#endif /* FLOATING_POINT */
442
* Flags used during conversion.
444
#define ALT 0x001 /* alternate form */
445
#define HEXPREFIX 0x002 /* add 0x or 0X prefix */
446
#define LADJUST 0x004 /* left adjustment */
447
#define LONGDBL 0x008 /* long double; unimplemented */
448
#define LONGINT 0x010 /* long integer */
450
#ifdef _HAVE_SANE_QUAD_
451
#define QUADINT 0x020 /* quad integer */
452
#endif /* _HAVE_SANE_QUAD_ */
454
#define SHORTINT 0x040 /* short integer */
455
#define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
456
#define FPT 0x100 /* Floating point number */
458
BSD_vfprintf(fp, fmt0, ap)
463
register char *fmt; /* format string */
464
register int ch; /* character from fmt */
465
register int n; /* handy integer (short term usage) */
466
register char *cp; /* handy char pointer (short term usage) */
467
register struct __siov *iovp;/* for PRINT macro */
468
register int flags; /* flags as above */
469
int ret; /* return value accumulator */
470
int width; /* width from format (%8d), or 0 */
471
int prec; /* precision from format (%.3d), or -1 */
472
char sign; /* sign prefix (' ', '+', '-', or \0) */
473
#ifdef FLOATING_POINT
474
char softsign; /* temporary negative sign for floats */
475
double _double; /* double precision arguments %[eEfgG] */
476
int expt; /* integer value of exponent */
477
int expsize; /* character count for expstr */
478
int ndig; /* actual number of digits returned by cvt */
479
char expstr[7]; /* buffer for exponent string */
481
u_long ulval; /* integer arguments %[diouxX] */
482
#ifdef _HAVE_SANE_QUAD_
483
u_quad_t uqval; /* %q integers */
484
#endif /* _HAVE_SANE_QUAD_ */
485
int base; /* base for [diouxX] conversion */
486
int dprec; /* a copy of prec if [diouxX], 0 otherwise */
487
int fieldsz; /* field size expanded by sign, etc */
488
int realsz; /* field size expanded by dprec */
489
int size; /* size of converted field or string */
490
char *xdigs; /* digits for [xX] conversion */
492
struct __suio uio; /* output information: summary */
493
struct __siov iov[NIOV];/* ... and individual io vectors */
494
char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
495
char ox[2]; /* space for 0x hex-prefix */
498
* Choose PADSIZE to trade efficiency vs. size. If larger printf
499
* fields occur frequently, increase PADSIZE and make the initialisers
502
#define PADSIZE 16 /* pad chunk size */
503
static char blanks[PADSIZE] =
504
{' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
505
static char zeroes[PADSIZE] =
506
{'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
509
* BEWARE, these `goto error' on error, and PAD uses `n'.
511
#define PRINT(ptr, len) { \
512
iovp->iov_base = (ptr); \
513
iovp->iov_len = (len); \
514
uio.uio_resid += (len); \
516
if (++uio.uio_iovcnt >= NIOV) { \
517
if (BSD__sprint(fp, &uio)) \
522
#define PAD(howmany, with) { \
523
if ((n = (howmany)) > 0) { \
524
while (n > PADSIZE) { \
525
PRINT(with, PADSIZE); \
532
if (uio.uio_resid && BSD__sprint(fp, &uio)) \
534
uio.uio_iovcnt = 0; \
539
* To extend shorts properly, we need both signed and unsigned
540
* argument extraction methods.
543
(flags&LONGINT ? va_arg(ap, long) : \
544
flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
545
(long)va_arg(ap, int))
547
(flags&LONGINT ? va_arg(ap, u_long) : \
548
flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
549
(u_long)va_arg(ap, u_int))
551
/* optimise fprintf(stderr) (and other unbuffered Unix files) */
552
if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
554
return (BSD__sbprintf(fp, fmt0, ap));
557
uio.uio_iov = iovp = iov;
563
* Scan the format for conversions (`%' character).
566
for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
568
if ((n = fmt - cp) != 0) {
574
fmt++; /* skip over '%' */
583
reswitch: switch (ch) {
586
* ``If the space and + flags both appear, the space
587
* flag will be ignored.''
598
* ``A negative field width argument is taken as a
599
* - flag followed by a positive field width.''
601
* They don't exclude field widths read from args.
603
if ((width = va_arg(ap, int)) >= 0)
614
if ((ch = *fmt++) == '*') {
616
prec = n < 0 ? -1 : n;
620
while (is_digit(ch)) {
621
n = 10 * n + to_digit(ch);
624
prec = n < 0 ? -1 : n;
628
* ``Note that 0 is taken as a flag, not as the
629
* beginning of a field width.''
634
case '1': case '2': case '3': case '4':
635
case '5': case '6': case '7': case '8': case '9':
638
n = 10 * n + to_digit(ch);
640
} while (is_digit(ch));
643
#ifdef FLOATING_POINT
654
#ifdef _HAVE_SANE_QUAD_
658
#endif /* _HAVE_SANE_QUAD_ */
660
*(cp = buf) = va_arg(ap, int);
669
#ifdef _HAVE_SANE_QUAD_
670
if (flags & QUADINT) {
671
uqval = va_arg(ap, quad_t);
672
if ((quad_t)uqval < 0) {
677
#else /* _HAVE_SANE_QUAD_ */
679
#endif /* _HAVE_SANE_QUAD_ */
681
if ((long)ulval < 0) {
688
#ifdef FLOATING_POINT
689
case 'e': /* anomalous precision */
691
prec = (prec == -1) ?
692
DEFPREC + 1 : prec + 1;
695
case 'f': /* always print trailing zeroes */
702
fp_begin: _double = va_arg(ap, double);
703
/* do this before tricky precision changes */
704
if (isinf(_double)) {
711
if (isnan(_double)) {
717
cp = cvt(_double, prec, flags, &softsign,
719
if (ch == 'g' || ch == 'G') {
720
if (expt <= -4 || expt > prec)
721
ch = (ch == 'g') ? 'e' : 'E';
725
if (ch <= 'e') { /* 'e' or 'E' fmt */
727
expsize = exponent(expstr, expt, ch);
728
size = expsize + ndig;
729
if (ndig > 1 || flags & ALT)
731
} else if (ch == 'f') { /* f fmt */
734
if (prec || flags & ALT)
738
} else if (expt >= ndig) { /* fixed g fmt */
743
size = ndig + (expt > 0 ?
749
#endif /* FLOATING_POINT */
751
#ifdef _HAVE_SANE_QUAD_
753
*va_arg(ap, quad_t *) = ret;
754
else if (flags & LONGINT)
755
#else /* _HAVE_SANE_QUAD_ */
757
#endif /* _HAVE_SANE_QUAD_ */
758
*va_arg(ap, long *) = ret;
759
else if (flags & SHORTINT)
760
*va_arg(ap, short *) = ret;
762
*va_arg(ap, int *) = ret;
763
continue; /* no output */
768
#ifdef _HAVE_SANE_QUAD_
770
uqval = va_arg(ap, u_quad_t);
772
#endif /* _HAVE_SANE_QUAD_ */
778
* ``The argument shall be a pointer to void. The
779
* value of the pointer is converted to a sequence
780
* of printable characters, in an implementation-
785
uqval = (u_long)va_arg(ap, void *);
786
flags = (flags) | QUADINT | HEXPREFIX;
788
ulval = (u_long)va_arg(ap, void *);
789
#ifdef _HAVE_SANE_QUAD_
790
flags = (flags & ~QUADINT) | HEXPREFIX;
791
#else /* _HAVE_SANE_QUAD_ */
792
flags = (flags) | HEXPREFIX;
793
#endif /* _HAVE_SANE_QUAD_ */
796
xdigs = "0123456789abcdef";
800
if ((cp = va_arg(ap, char *)) == NULL)
804
* can't use strlen; can only look for the
805
* NUL in the first `prec' characters, and
806
* strlen() will go further.
808
char *p = (char *)memchr(cp, 0, prec);
824
#ifdef _HAVE_SANE_QUAD_
826
uqval = va_arg(ap, u_quad_t);
828
#endif /* _HAVE_SANE_QUAD_ */
833
xdigs = "0123456789ABCDEF";
836
xdigs = "0123456789abcdef";
838
#ifdef _HAVE_SANE_QUAD_
840
uqval = va_arg(ap, u_quad_t);
842
#endif /* _HAVE_SANE_QUAD_ */
845
/* leading 0x/X only if non-zero */
847
#ifdef _HAVE_SANE_QUAD_
848
(flags & QUADINT ? uqval != 0 : ulval != 0))
849
#else /* _HAVE_SANE_QUAD_ */
851
#endif /* _HAVE_SANE_QUAD_ */
854
/* unsigned conversions */
857
* ``... diouXx conversions ... if a precision is
858
* specified, the 0 flag will be ignored.''
861
number: if ((dprec = prec) >= 0)
865
* ``The result of converting a zero value with an
866
* explicit precision of zero is no characters.''
870
#ifdef _HAVE_SANE_QUAD_
871
if (flags & QUADINT) {
872
if (uqval != 0 || prec != 0)
873
cp = __uqtoa(uqval, cp, base,
876
#else /* _HAVE_SANE_QUAD_ */
878
#endif /* _HAVE_SANE_QUAD_ */
879
if (ulval != 0 || prec != 0)
880
cp = BSD__ultoa(ulval, cp, base,
883
size = buf + BUF - cp;
885
default: /* "%?" prints ?, unless ? is NUL */
888
/* pretend it was %c with argument ch */
897
* All reasonable formats wind up here. At this point, `cp'
898
* points to a string which (if not flags&LADJUST) should be
899
* padded out to `width' places. If flags&ZEROPAD, it should
900
* first be prefixed by any sign or other prefix; otherwise,
901
* it should be blank padded before the prefix is emitted.
902
* After any left-hand padding and prefixing, emit zeroes
903
* required by a decimal [diouxX] precision, then print the
904
* string proper, then emit zeroes required by any leftover
905
* floating precision; finally, if LADJUST, pad with blanks.
907
* Compute actual size, so we know how much to pad.
908
* fieldsz excludes decimal prec; realsz includes it.
913
else if (flags & HEXPREFIX)
915
realsz = dprec > fieldsz ? dprec : fieldsz;
917
/* right-adjusting blank padding */
918
if ((flags & (LADJUST|ZEROPAD)) == 0)
919
PAD(width - realsz, blanks);
924
} else if (flags & HEXPREFIX) {
930
/* right-adjusting zero padding */
931
if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
932
PAD(width - realsz, zeroes);
934
/* leading zeroes from decimal precision */
935
PAD(dprec - fieldsz, zeroes);
937
/* the string or number proper */
938
#ifdef FLOATING_POINT
939
if ((flags & FPT) == 0) {
941
} else { /* glue together f_p fragments */
942
if (ch >= 'f') { /* 'f' or 'g' */
944
/* kludge for __dtoa irregularity */
946
(flags & ALT) == 0) {
950
PAD(ndig - 1, zeroes);
952
} else if (expt <= 0) {
956
} else if (expt >= ndig) {
958
PAD(expt - ndig, zeroes);
965
PRINT(cp, ndig-expt);
967
} else { /* 'e' or 'E' */
968
if (ndig > 1 || flags & ALT) {
972
if (_double || flags & ALT == 0) {
975
/* __dtoa irregularity */
976
PAD(ndig - 1, zeroes);
979
PRINT(expstr, expsize);
985
/* left-adjusting padding (always blank) */
987
PAD(width - realsz, blanks);
989
/* finally, adjust ret */
990
ret += width > realsz ? width : realsz;
992
FLUSH(); /* copy out the I/O vectors */
997
return (__sferror(fp) ? EOF : ret);
1001
#ifdef FLOATING_POINT
1003
extern char *BSD__dtoa __P((double, int, int, int *, int *, char **));
1006
cvt(value, ndigits, flags, sign, decpt, ch, length)
1008
int ndigits, flags, *decpt, ch, *length;
1012
char *digits, *bp, *rve;
1022
} else if (value == 0.0 && 1.0/value < 0) {
1027
digits = BSD__dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1028
if (flags & ALT) { /* Print trailing zeros */
1029
bp = digits + ndigits;
1031
if (*digits == '0' && value)
1032
*decpt = -ndigits + 1;
1035
if (value == 0) /* kludge for __dtoa irregularity */
1040
*length = rve - digits;
1045
exponent(p0, exp, fmtch)
1049
register char *p, *t;
1050
char expbuf[MAXEXP];
1060
t = expbuf + MAXEXP;
1063
*--t = to_char(exp % 10);
1064
} while ((exp /= 10) > 9);
1065
*--t = to_char(exp);
1066
for (; t < expbuf + MAXEXP; *p++ = *t++);
1070
*p++ = to_char(exp);
1074
#endif /* FLOATING_POINT */
1077
vsnprintf(str, n, fmt, ap)
1088
f._flags = __SWR | __SSTR;
1089
f._bf._base = f._p = (unsigned char *)str;
1090
f._bf._size = f._w = n - 1;
1091
ret = BSD_vfprintf(&f, fmt, ap);
1096
#if defined(LIBC_SCCS) && !defined(lint)
1097
static char sccsid[] = "@(#)snprintf.c 8.1 (Berkeley) 6/4/93";
1098
#endif /* LIBC_SCCS and not lint */
1100
#if defined(__STDC__)
1101
# include <stdarg.h>
1103
# include <varargs.h>
1107
#if defined(__STDC__)
1108
snprintf(char *str, size_t n, char const *fmt, ...)
1110
snprintf(str, n, fmt, va_alist)
1123
#if defined(__STDC__)
1128
f._flags = __SWR | __SSTR;
1129
f._bf._base = f._p = (unsigned char *)str;
1130
f._bf._size = f._w = n - 1;
1131
ret = BSD_vfprintf(&f, fmt, ap);