2 * Replacement for a missing snprintf or vsnprintf.
4 * The following implementation of snprintf was taken mostly verbatim from
5 * <http://www.fiction.net/blong/programs/>; it is the version of snprintf
6 * used in Mutt. A possibly newer version is used in wget, found at
7 * <https://github.com/wertarbyte/wget/blob/master/src/snprintf.c>.
9 * Please do not reformat or otherwise change this file more than necessary so
10 * that later merges with the original source are easy. Bug fixes and
11 * improvements should be sent back to the original author.
13 * The canonical version of this file is maintained in the rra-c-util package,
14 * which can be found at <http://www.eyrie.org/~eagle/software/rra-c-util/>.
18 * If we're running the test suite, rename snprintf and vsnprintf to avoid
19 * conflicts with the system version.
22 # define snprintf test_snprintf
23 # define vsnprintf test_vsnprintf
27 * Copyright Patrick Powell 1995
28 * This code is based on code written by Patrick Powell (papowell@astart.com)
29 * It may be used for any purpose as long as this notice remains intact
30 * on all source code distributions
33 /**************************************************************
35 * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
36 * A bombproof version of doprnt (dopr) included.
37 * Sigh. This sort of thing is always nasty do deal with. Note that
38 * the version here does not include floating point...
40 * snprintf() is used instead of sprintf() as it does limit checks
41 * for string length. This covers a nasty loophole.
43 * The other functions are there to prevent NULL pointers from
44 * causing nast effects.
47 * Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43
48 * This was ugly. It is still ugly. I opted out of floating point
49 * numbers, but the formatter understands just about everything
50 * from the normal C string format, at least as far as I can tell from
51 * the Solaris 2.5 printf(3S) man page.
53 * Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1
54 * Ok, added some minimal floating point support, which means this
55 * probably requires libm on most operating systems. Don't yet
56 * support the exponent (e,E) and sigfig (g,G). Also, fmtint()
57 * was pretty badly broken, it just wasn't being exercised in ways
58 * which showed it, so that's been fixed. Also, formated the code
59 * to mutt conventions, and removed dead code left over from the
60 * original. Also, there is now a builtin-test, just compile with:
61 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm
62 * and run snprintf for results.
64 * Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i
65 * The PGP code was using unsigned hexadecimal formats.
66 * Unfortunately, unsigned formats simply didn't work.
68 * Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8
69 * The original code assumed that both snprintf() and vsnprintf() were
70 * missing. Some systems only have snprintf() but not vsnprintf(), so
71 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
73 * Andrew Tridgell (tridge@samba.org) Oct 1998
74 * fixed handling of %.0f
75 * added test for HAVE_LONG_DOUBLE
77 * Russ Allbery <eagle@eyrie.org> 2000-08-26
78 * fixed return value to comply with C99
79 * fixed handling of snprintf(NULL, ...)
81 * Hrvoje Niksic <hniksic@arsdigita.com> 2000-11-04
82 * include <stdio.h> for NULL.
83 * added support for long long.
84 * don't declare argument types to (v)snprintf if stdarg is not used.
86 * Hrvoje Niksic <hniksic@xemacs.org> 2005-04-15
87 * use the PARAMS macro to handle prototypes.
88 * write function definitions in the ansi2knr-friendly way.
89 * if string precision is specified, don't read VALUE past it.
90 * fix bug in fmtfp that caused 0.01 to be printed as 0.1.
91 * don't include <ctype.h> because none of it is used.
92 * interpret precision as number of significant digits with %g
93 * omit trailing decimal zeros with %g
95 **************************************************************/
101 #include <sys/types.h>
107 /* varargs declarations: */
110 #define HAVE_STDARGS /* let's hope that works everywhere (mj) */
111 #define VA_LOCAL_DECL va_list ap
112 #define VA_START(f) va_start(ap, f)
113 #define VA_SHIFT(v,t) ; /* no-op for ANSI */
114 #define VA_END va_end(ap)
116 /* Assume all compilers support long double, per Autoconf documentation. */
117 #define LDOUBLE long double
119 #ifdef HAVE_LONG_LONG_INT
120 # define LLONG long long
125 int snprintf (char *str, size_t count, const char *fmt, ...);
126 int vsnprintf (char *str, size_t count, const char *fmt, va_list arg);
128 static int dopr (char *buffer, size_t maxlen, const char *format,
130 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
131 const char *value, int flags, int min, int max);
132 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
133 LLONG value, int base, int min, int max, int flags);
134 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
135 LDOUBLE fvalue, int min, int max, int flags);
136 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c );
139 * dopr(): poor man's version of doprintf
142 /* format read states */
143 #define DP_S_DEFAULT 0
153 /* format flags - Bits */
154 #define DP_F_MINUS (1 << 0)
155 #define DP_F_PLUS (1 << 1)
156 #define DP_F_SPACE (1 << 2)
157 #define DP_F_NUM (1 << 3)
158 #define DP_F_ZERO (1 << 4)
159 #define DP_F_UP (1 << 5)
160 #define DP_F_UNSIGNED (1 << 6)
161 #define DP_F_FP_G (1 << 7)
163 /* Conversion Flags */
167 #define DP_C_LDOUBLE 4
169 #define char_to_int(p) (p - '0')
170 #define MAX(p,q) ((p >= q) ? p : q)
171 #define MIN(p,q) ((p <= q) ? p : q)
173 static int dopr (char *buffer, size_t maxlen, const char *format, va_list args)
187 state = DP_S_DEFAULT;
188 currlen = flags = cflags = min = 0;
193 while (state != DP_S_DONE)
204 total += dopr_outch (buffer, &currlen, maxlen, ch);
236 if ('0' <= ch && ch <= '9')
238 min = 10*min + char_to_int (ch);
243 min = va_arg (args, int);
260 if ('0' <= ch && ch <= '9')
264 max = 10*max + char_to_int (ch);
269 max = va_arg (args, int);
288 cflags = DP_C_LDOUBLE;
294 if (cflags != DP_C_LONG)
316 if (cflags == DP_C_SHORT)
317 value = (short int) va_arg (args, int);
318 else if (cflags == DP_C_LONG)
319 value = va_arg (args, long int);
320 else if (cflags == DP_C_LLONG)
321 value = va_arg (args, LLONG);
323 value = va_arg (args, int);
324 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
327 flags |= DP_F_UNSIGNED;
328 if (cflags == DP_C_SHORT)
329 value = (unsigned short int) va_arg (args, unsigned int);
330 else if (cflags == DP_C_LONG)
331 value = va_arg (args, unsigned long int);
332 else if (cflags == DP_C_LLONG)
333 value = va_arg (args, unsigned LLONG);
335 value = va_arg (args, unsigned int);
336 total += fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
339 flags |= DP_F_UNSIGNED;
340 if (cflags == DP_C_SHORT)
341 value = (unsigned short int) va_arg (args, unsigned int);
342 else if (cflags == DP_C_LONG)
343 value = va_arg (args, unsigned long int);
344 else if (cflags == DP_C_LLONG)
345 value = va_arg (args, unsigned LLONG);
347 value = va_arg (args, unsigned int);
348 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
353 flags |= DP_F_UNSIGNED;
354 if (cflags == DP_C_SHORT)
355 value = (unsigned short int) va_arg (args, unsigned int);
356 else if (cflags == DP_C_LONG)
357 value = va_arg (args, unsigned long int);
358 else if (cflags == DP_C_LLONG)
359 value = va_arg (args, unsigned LLONG);
361 value = va_arg (args, unsigned int);
362 total += fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
365 if (cflags == DP_C_LDOUBLE)
366 fvalue = va_arg (args, LDOUBLE);
368 fvalue = va_arg (args, double);
369 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
374 if (cflags == DP_C_LDOUBLE)
375 fvalue = va_arg (args, LDOUBLE);
377 fvalue = va_arg (args, double);
378 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
384 if (cflags == DP_C_LDOUBLE)
385 fvalue = va_arg (args, LDOUBLE);
387 fvalue = va_arg (args, double);
389 /* C99 says: if precision [for %g] is zero, it is taken as one */
391 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
394 total += dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
397 strvalue = va_arg (args, char *);
398 total += fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
401 strvalue = va_arg (args, void *);
402 total += fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min,
406 if (cflags == DP_C_SHORT)
409 num = va_arg (args, short int *);
412 else if (cflags == DP_C_LONG)
415 num = va_arg (args, long int *);
418 else if (cflags == DP_C_LLONG)
421 num = va_arg (args, LLONG *);
427 num = va_arg (args, int *);
432 total += dopr_outch (buffer, &currlen, maxlen, ch);
435 /* not supported yet, treat as next char */
443 state = DP_S_DEFAULT;
444 flags = cflags = min = 0;
451 break; /* some picky compilers need this */
456 if (currlen < maxlen - 1)
457 buffer[currlen] = '\0';
459 buffer[maxlen - 1] = '\0';
464 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
465 const char *value, int flags, int min, int max)
467 int padlen, strln; /* amount to pad */
477 strln = strlen (value);
479 /* When precision is specified, don't read VALUE past precision. */
480 /*strln = strnlen (value, max);*/
481 for (strln = 0; strln < max && value[strln]; ++strln);
482 padlen = min - strln;
485 if (flags & DP_F_MINUS)
486 padlen = -padlen; /* Left Justify */
490 total += dopr_outch (buffer, currlen, maxlen, ' ');
493 while (*value && ((max < 0) || (cnt < max)))
495 total += dopr_outch (buffer, currlen, maxlen, *value++);
500 total += dopr_outch (buffer, currlen, maxlen, ' ');
506 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
508 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
509 LLONG value, int base, int min, int max, int flags)
512 unsigned LLONG uvalue;
514 unsigned int place = 0;
515 int spadlen = 0; /* amount to space pad */
516 int zpadlen = 0; /* amount to zero pad */
525 if(!(flags & DP_F_UNSIGNED))
532 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
535 if (flags & DP_F_SPACE)
540 /* Should characters be upper case? */
541 digits = "0123456789ABCDEF";
543 digits = "0123456789abcdef";
546 convert[place++] = digits[uvalue % (unsigned)base];
547 uvalue = (uvalue / (unsigned)base );
548 } while(uvalue && (place < sizeof (convert)));
549 if (place == sizeof (convert)) place--;
552 zpadlen = max - place;
553 spadlen = min - MAX ((unsigned int)max, place) - (signvalue ? 1 : 0);
554 if (zpadlen < 0) zpadlen = 0;
555 if (spadlen < 0) spadlen = 0;
556 if (flags & DP_F_ZERO)
558 zpadlen = MAX(zpadlen, spadlen);
561 if (flags & DP_F_MINUS)
562 spadlen = -spadlen; /* Left Justifty */
564 #ifdef DEBUG_SNPRINTF
565 dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
566 zpadlen, spadlen, min, max, place));
572 total += dopr_outch (buffer, currlen, maxlen, ' ');
578 total += dopr_outch (buffer, currlen, maxlen, signvalue);
585 total += dopr_outch (buffer, currlen, maxlen, '0');
592 total += dopr_outch (buffer, currlen, maxlen, convert[--place]);
594 /* Left Justified spaces */
595 while (spadlen < 0) {
596 total += dopr_outch (buffer, currlen, maxlen, ' ');
603 static LDOUBLE abs_val (LDOUBLE value)
605 LDOUBLE result = value;
613 static LDOUBLE pow10_int (int exp)
626 static LLONG round_int (LDOUBLE value)
631 value = value - intpart;
638 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
639 LDOUBLE fvalue, int min, int max, int flags)
647 int padlen = 0; /* amount to pad */
653 int leadingfrac0s = 0; /* zeroes at the start of fractional part */
655 size_t omitcount = 0;
658 * AIX manpage says the default is 0, but Solaris says the default
659 * is 6, and sprintf on AIX defaults to 6
664 ufvalue = abs_val (fvalue);
669 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
672 if (flags & DP_F_SPACE)
676 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
681 /* With %g precision is the number of significant digits, which
682 includes the digits in intpart. */
683 if (flags & DP_F_FP_G)
687 /* For each digit of INTPART, print one less fractional digit. */
688 LLONG temp = intpart;
689 for (temp = intpart; temp != 0; temp /= 10)
696 /* For each leading 0 in fractional part, print one more
700 for (temp = ufvalue; temp < 0.1; temp *= 10)
705 /* C99: trailing zeros are removed from the fractional portion of the
706 result unless the # flag is specified */
707 if ((flags & DP_F_FP_G) && !(flags & DP_F_NUM))
710 #if SIZEOF_LONG_LONG > 0
711 # define MAX_DIGITS 18 /* grok more digits with long long */
713 # define MAX_DIGITS 9 /* just long */
717 * Sorry, we only support several digits past the decimal because of
718 * our conversion method
720 if (max > MAX_DIGITS)
723 /* Factor of 10 with the needed number of digits, e.g. 1000 for max==3 */
724 mask10 = pow10_int (max);
726 /* We "cheat" by converting the fractional part to integer by
727 * multiplying by a factor of 10
729 fracpart = round_int (mask10 * (ufvalue - intpart));
731 if (fracpart >= mask10)
736 else if (fracpart != 0)
737 /* If fracpart has less digits than the 10* mask, we need to
738 manually insert leading 0s. For example 2.01's fractional part
739 requires one leading zero to distinguish it from 2.1. */
740 while (fracpart < mask10 / 10)
746 #ifdef DEBUG_SNPRINTF
747 dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart));
750 /* Convert integer part */
752 iconvert[iplace++] = '0' + intpart % 10;
753 intpart = (intpart / 10);
754 } while(intpart && (iplace < sizeof(iconvert)));
755 if (iplace == sizeof(iconvert)) iplace--;
756 iconvert[iplace] = 0;
758 /* Convert fractional part */
760 fconvert[fplace++] = '0' + fracpart % 10;
761 fracpart = (fracpart / 10);
762 } while(fracpart && (fplace < sizeof(fconvert)));
763 while (leadingfrac0s-- > 0 && fplace < sizeof(fconvert))
764 fconvert[fplace++] = '0';
765 if (fplace == sizeof(fconvert)) fplace--;
766 fconvert[fplace] = 0;
768 while (omitcount < fplace && fconvert[omitcount] == '0')
771 /* -1 for decimal point, another -1 if we are printing a sign */
772 padlen = min - iplace - (max - omitcount) - 1 - ((signvalue) ? 1 : 0);
774 zpadlen = max - fplace;
779 if (flags & DP_F_MINUS)
780 padlen = -padlen; /* Left Justifty */
782 if ((flags & DP_F_ZERO) && (padlen > 0))
786 total += dopr_outch (buffer, currlen, maxlen, signvalue);
792 total += dopr_outch (buffer, currlen, maxlen, '0');
798 total += dopr_outch (buffer, currlen, maxlen, ' ');
802 total += dopr_outch (buffer, currlen, maxlen, signvalue);
805 total += dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
808 * Decimal point. This should probably use locale to find the correct
811 if (max > 0 && (fplace > omitcount || zpadlen > 0))
813 total += dopr_outch (buffer, currlen, maxlen, '.');
815 while (fplace > omitcount)
816 total += dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
821 total += dopr_outch (buffer, currlen, maxlen, '0');
827 total += dopr_outch (buffer, currlen, maxlen, ' ');
834 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c)
836 if (*currlen + 1 < maxlen)
837 buffer[(*currlen)++] = c;
841 int vsnprintf (char *str, size_t count, const char *fmt, va_list args)
845 return dopr(str, count, fmt, args);
850 int snprintf (char *str,size_t count,const char *fmt,...)
852 int snprintf (va_alist) va_dcl
864 VA_SHIFT (str, char *);
865 VA_SHIFT (count, size_t );
866 VA_SHIFT (fmt, char *);
867 total = vsnprintf(str, count, fmt, ap);
874 #define LONG_STRING 1024
878 char buf1[LONG_STRING];
879 char buf2[LONG_STRING];
896 double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
897 0.9996, 1.996, 4.136, 0};
910 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
915 printf ("Testing snprintf format codes against system sprintf...\n");
917 for (x = 0; fp_fmt[x] != NULL ; x++)
918 for (y = 0; fp_nums[y] != 0 ; y++)
920 snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]);
921 sprintf (buf2, fp_fmt[x], fp_nums[y]);
922 if (strcmp (buf1, buf2))
924 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
925 fp_fmt[x], buf1, buf2);
931 for (x = 0; int_fmt[x] != NULL ; x++)
932 for (y = 0; int_nums[y] != 0 ; y++)
934 snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]);
935 sprintf (buf2, int_fmt[x], int_nums[y]);
936 if (strcmp (buf1, buf2))
938 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
939 int_fmt[x], buf1, buf2);
944 printf ("%d tests failed out of %d.\n", fail, num);
946 #endif /* SNPRINTF_TEST */