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 <https://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.
24 # define snprintf test_snprintf
25 # define vsnprintf test_vsnprintf
29 * Copyright Patrick Powell 1995
30 * This code is based on code written by Patrick Powell (papowell@astart.com)
31 * It may be used for any purpose as long as this notice remains intact
32 * on all source code distributions
35 /**************************************************************
37 * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
38 * A bombproof version of doprnt (dopr) included.
39 * Sigh. This sort of thing is always nasty do deal with. Note that
40 * the version here does not include floating point...
42 * snprintf() is used instead of sprintf() as it does limit checks
43 * for string length. This covers a nasty loophole.
45 * The other functions are there to prevent NULL pointers from
46 * causing nast effects.
49 * Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43
50 * This was ugly. It is still ugly. I opted out of floating point
51 * numbers, but the formatter understands just about everything
52 * from the normal C string format, at least as far as I can tell from
53 * the Solaris 2.5 printf(3S) man page.
55 * Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1
56 * Ok, added some minimal floating point support, which means this
57 * probably requires libm on most operating systems. Don't yet
58 * support the exponent (e,E) and sigfig (g,G). Also, fmtint()
59 * was pretty badly broken, it just wasn't being exercised in ways
60 * which showed it, so that's been fixed. Also, formated the code
61 * to mutt conventions, and removed dead code left over from the
62 * original. Also, there is now a builtin-test, just compile with:
63 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm
64 * and run snprintf for results.
66 * Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i
67 * The PGP code was using unsigned hexadecimal formats.
68 * Unfortunately, unsigned formats simply didn't work.
70 * Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8
71 * The original code assumed that both snprintf() and vsnprintf() were
72 * missing. Some systems only have snprintf() but not vsnprintf(), so
73 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
75 * Andrew Tridgell (tridge@samba.org) Oct 1998
76 * fixed handling of %.0f
77 * added test for HAVE_LONG_DOUBLE
79 * Russ Allbery <eagle@eyrie.org> 2000-08-26
80 * fixed return value to comply with C99
81 * fixed handling of snprintf(NULL, ...)
82 * added explicit casts for double to long long int conversion
84 * Hrvoje Niksic <hniksic@arsdigita.com> 2000-11-04
85 * include <stdio.h> for NULL.
86 * added support for long long.
87 * don't declare argument types to (v)snprintf if stdarg is not used.
89 * Hrvoje Niksic <hniksic@xemacs.org> 2005-04-15
90 * use the PARAMS macro to handle prototypes.
91 * write function definitions in the ansi2knr-friendly way.
92 * if string precision is specified, don't read VALUE past it.
93 * fix bug in fmtfp that caused 0.01 to be printed as 0.1.
94 * don't include <ctype.h> because none of it is used.
95 * interpret precision as number of significant digits with %g
96 * omit trailing decimal zeros with %g
98 **************************************************************/
104 #include <sys/types.h>
110 /* varargs declarations: */
113 #define HAVE_STDARGS /* let's hope that works everywhere (mj) */
114 #define VA_LOCAL_DECL va_list ap
115 #define VA_START(f) va_start(ap, f)
116 #define VA_SHIFT(v,t) ; /* no-op for ANSI */
117 #define VA_END va_end(ap)
119 /* Assume all compilers support long double, per Autoconf documentation. */
120 #define LDOUBLE long double
122 #ifdef HAVE_LONG_LONG_INT
123 # define LLONG long long
128 int snprintf (char *str, size_t count, const char *fmt, ...);
129 int vsnprintf (char *str, size_t count, const char *fmt, va_list arg);
131 static int dopr (char *buffer, size_t maxlen, const char *format,
133 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
134 const char *value, int flags, int min, int max);
135 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
136 LLONG value, int base, int min, int max, int flags);
137 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
138 LDOUBLE fvalue, int min, int max, int flags);
139 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c );
142 * dopr(): poor man's version of doprintf
145 /* format read states */
146 #define DP_S_DEFAULT 0
156 /* format flags - Bits */
157 #define DP_F_MINUS (1 << 0)
158 #define DP_F_PLUS (1 << 1)
159 #define DP_F_SPACE (1 << 2)
160 #define DP_F_NUM (1 << 3)
161 #define DP_F_ZERO (1 << 4)
162 #define DP_F_UP (1 << 5)
163 #define DP_F_UNSIGNED (1 << 6)
164 #define DP_F_FP_G (1 << 7)
166 /* Conversion Flags */
170 #define DP_C_LDOUBLE 4
172 #define char_to_int(p) (p - '0')
173 #define MAX(p,q) ((p >= q) ? p : q)
174 #define MIN(p,q) ((p <= q) ? p : q)
176 static int dopr (char *buffer, size_t maxlen, const char *format, va_list args)
190 state = DP_S_DEFAULT;
191 currlen = flags = cflags = min = 0;
196 while (state != DP_S_DONE)
207 total += dopr_outch (buffer, &currlen, maxlen, ch);
239 if ('0' <= ch && ch <= '9')
241 min = 10*min + char_to_int (ch);
246 min = va_arg (args, int);
263 if ('0' <= ch && ch <= '9')
267 max = 10*max + char_to_int (ch);
272 max = va_arg (args, int);
291 cflags = DP_C_LDOUBLE;
297 if (cflags != DP_C_LONG)
319 if (cflags == DP_C_SHORT)
320 value = (short int) va_arg (args, int);
321 else if (cflags == DP_C_LONG)
322 value = va_arg (args, long int);
323 else if (cflags == DP_C_LLONG)
324 value = va_arg (args, LLONG);
326 value = va_arg (args, int);
327 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
330 flags |= DP_F_UNSIGNED;
331 if (cflags == DP_C_SHORT)
332 value = (unsigned short int) va_arg (args, unsigned int);
333 else if (cflags == DP_C_LONG)
334 value = va_arg (args, unsigned long int);
335 else if (cflags == DP_C_LLONG)
336 value = va_arg (args, unsigned LLONG);
338 value = va_arg (args, unsigned int);
339 total += fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
342 flags |= DP_F_UNSIGNED;
343 if (cflags == DP_C_SHORT)
344 value = (unsigned short int) va_arg (args, unsigned int);
345 else if (cflags == DP_C_LONG)
346 value = va_arg (args, unsigned long int);
347 else if (cflags == DP_C_LLONG)
348 value = va_arg (args, unsigned LLONG);
350 value = va_arg (args, unsigned int);
351 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
356 flags |= DP_F_UNSIGNED;
357 if (cflags == DP_C_SHORT)
358 value = (unsigned short int) va_arg (args, unsigned int);
359 else if (cflags == DP_C_LONG)
360 value = va_arg (args, unsigned long int);
361 else if (cflags == DP_C_LLONG)
362 value = va_arg (args, unsigned LLONG);
364 value = va_arg (args, unsigned int);
365 total += fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
368 if (cflags == DP_C_LDOUBLE)
369 fvalue = va_arg (args, LDOUBLE);
371 fvalue = va_arg (args, double);
372 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
377 if (cflags == DP_C_LDOUBLE)
378 fvalue = va_arg (args, LDOUBLE);
380 fvalue = va_arg (args, double);
381 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
387 if (cflags == DP_C_LDOUBLE)
388 fvalue = va_arg (args, LDOUBLE);
390 fvalue = va_arg (args, double);
392 /* C99 says: if precision [for %g] is zero, it is taken as one */
394 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
397 total += dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
400 strvalue = va_arg (args, char *);
401 total += fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
404 strvalue = va_arg (args, void *);
405 total += fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min,
409 if (cflags == DP_C_SHORT)
412 num = va_arg (args, short int *);
415 else if (cflags == DP_C_LONG)
418 num = va_arg (args, long int *);
421 else if (cflags == DP_C_LLONG)
424 num = va_arg (args, LLONG *);
430 num = va_arg (args, int *);
435 total += dopr_outch (buffer, &currlen, maxlen, ch);
438 /* not supported yet, treat as next char */
446 state = DP_S_DEFAULT;
447 flags = cflags = min = 0;
454 break; /* some picky compilers need this */
459 if (currlen < maxlen - 1)
460 buffer[currlen] = '\0';
462 buffer[maxlen - 1] = '\0';
467 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
468 const char *value, int flags, int min, int max)
470 int padlen, strln; /* amount to pad */
480 strln = strlen (value);
482 /* When precision is specified, don't read VALUE past precision. */
483 /*strln = strnlen (value, max);*/
484 for (strln = 0; strln < max && value[strln]; ++strln);
485 padlen = min - strln;
488 if (flags & DP_F_MINUS)
489 padlen = -padlen; /* Left Justify */
493 total += dopr_outch (buffer, currlen, maxlen, ' ');
496 while (*value && ((max < 0) || (cnt < max)))
498 total += dopr_outch (buffer, currlen, maxlen, *value++);
503 total += dopr_outch (buffer, currlen, maxlen, ' ');
509 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
511 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
512 LLONG value, int base, int min, int max, int flags)
515 unsigned LLONG uvalue;
517 unsigned int place = 0;
518 int spadlen = 0; /* amount to space pad */
519 int zpadlen = 0; /* amount to zero pad */
528 if(!(flags & DP_F_UNSIGNED))
535 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
538 if (flags & DP_F_SPACE)
543 /* Should characters be upper case? */
544 digits = "0123456789ABCDEF";
546 digits = "0123456789abcdef";
549 convert[place++] = digits[uvalue % (unsigned)base];
550 uvalue = (uvalue / (unsigned)base );
551 } while(uvalue && (place < sizeof (convert)));
552 if (place == sizeof (convert)) place--;
555 zpadlen = max - place;
556 spadlen = min - MAX ((unsigned int)max, place) - (signvalue ? 1 : 0);
557 if (zpadlen < 0) zpadlen = 0;
558 if (spadlen < 0) spadlen = 0;
559 if (flags & DP_F_ZERO)
561 zpadlen = MAX(zpadlen, spadlen);
564 if (flags & DP_F_MINUS)
565 spadlen = -spadlen; /* Left Justifty */
567 #ifdef DEBUG_SNPRINTF
568 dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
569 zpadlen, spadlen, min, max, place));
575 total += dopr_outch (buffer, currlen, maxlen, ' ');
581 total += dopr_outch (buffer, currlen, maxlen, signvalue);
588 total += dopr_outch (buffer, currlen, maxlen, '0');
595 total += dopr_outch (buffer, currlen, maxlen, convert[--place]);
597 /* Left Justified spaces */
598 while (spadlen < 0) {
599 total += dopr_outch (buffer, currlen, maxlen, ' ');
606 static LDOUBLE abs_val (LDOUBLE value)
608 LDOUBLE result = value;
616 static LLONG pow10_int (int exp)
626 return (LLONG) result;
629 static LLONG round_int (LDOUBLE value)
633 intpart = (LLONG) value;
634 value = value - intpart;
641 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
642 LDOUBLE fvalue, int min, int max, int flags)
650 int padlen = 0; /* amount to pad */
656 int leadingfrac0s = 0; /* zeroes at the start of fractional part */
658 size_t omitcount = 0;
661 * AIX manpage says the default is 0, but Solaris says the default
662 * is 6, and sprintf on AIX defaults to 6
667 ufvalue = abs_val (fvalue);
672 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
675 if (flags & DP_F_SPACE)
679 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
682 intpart = (LLONG) ufvalue;
684 /* With %g precision is the number of significant digits, which
685 includes the digits in intpart. */
686 if (flags & DP_F_FP_G)
690 /* For each digit of INTPART, print one less fractional digit. */
691 LLONG temp = intpart;
692 for (temp = intpart; temp != 0; temp /= 10)
699 /* For each leading 0 in fractional part, print one more
703 for (temp = ufvalue; temp < 0.1; temp *= 10)
708 /* C99: trailing zeros are removed from the fractional portion of the
709 result unless the # flag is specified */
710 if ((flags & DP_F_FP_G) && !(flags & DP_F_NUM))
713 #if SIZEOF_LONG_LONG > 0
714 # define MAX_DIGITS 18 /* grok more digits with long long */
716 # define MAX_DIGITS 9 /* just long */
720 * Sorry, we only support several digits past the decimal because of
721 * our conversion method
723 if (max > MAX_DIGITS)
726 /* Factor of 10 with the needed number of digits, e.g. 1000 for max==3 */
727 mask10 = pow10_int (max);
729 /* We "cheat" by converting the fractional part to integer by
730 * multiplying by a factor of 10
732 fracpart = round_int (mask10 * (ufvalue - intpart));
734 if (fracpart >= mask10)
739 else if (fracpart != 0)
740 /* If fracpart has less digits than the 10* mask, we need to
741 manually insert leading 0s. For example 2.01's fractional part
742 requires one leading zero to distinguish it from 2.1. */
743 while (fracpart < mask10 / 10)
749 #ifdef DEBUG_SNPRINTF
750 dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart));
753 /* Convert integer part */
755 iconvert[iplace++] = '0' + intpart % 10;
756 intpart = (intpart / 10);
757 } while(intpart && (iplace < sizeof(iconvert)));
758 if (iplace == sizeof(iconvert)) iplace--;
759 iconvert[iplace] = 0;
761 /* Convert fractional part */
763 fconvert[fplace++] = '0' + fracpart % 10;
764 fracpart = (fracpart / 10);
765 } while(fracpart && (fplace < sizeof(fconvert)));
766 while (leadingfrac0s-- > 0 && fplace < sizeof(fconvert))
767 fconvert[fplace++] = '0';
768 if (fplace == sizeof(fconvert)) fplace--;
769 fconvert[fplace] = 0;
771 while (omitcount < fplace && fconvert[omitcount] == '0')
774 /* -1 for decimal point, another -1 if we are printing a sign */
775 padlen = min - iplace - (max - omitcount) - 1 - ((signvalue) ? 1 : 0);
777 zpadlen = max - fplace;
782 if (flags & DP_F_MINUS)
783 padlen = -padlen; /* Left Justifty */
785 if ((flags & DP_F_ZERO) && (padlen > 0))
789 total += dopr_outch (buffer, currlen, maxlen, signvalue);
795 total += dopr_outch (buffer, currlen, maxlen, '0');
801 total += dopr_outch (buffer, currlen, maxlen, ' ');
805 total += dopr_outch (buffer, currlen, maxlen, signvalue);
808 total += dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
811 * Decimal point. This should probably use locale to find the correct
814 if (max > 0 && (fplace > omitcount || zpadlen > 0))
816 total += dopr_outch (buffer, currlen, maxlen, '.');
818 while (fplace > omitcount)
819 total += dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
824 total += dopr_outch (buffer, currlen, maxlen, '0');
830 total += dopr_outch (buffer, currlen, maxlen, ' ');
837 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c)
839 if (*currlen + 1 < maxlen)
840 buffer[(*currlen)++] = c;
844 int vsnprintf (char *str, size_t count, const char *fmt, va_list args)
848 return dopr(str, count, fmt, args);
853 int snprintf (char *str,size_t count,const char *fmt,...)
855 int snprintf (va_alist) va_dcl
867 VA_SHIFT (str, char *);
868 VA_SHIFT (count, size_t );
869 VA_SHIFT (fmt, char *);
870 total = vsnprintf(str, count, fmt, ap);
877 #define LONG_STRING 1024
881 char buf1[LONG_STRING];
882 char buf2[LONG_STRING];
899 double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
900 0.9996, 1.996, 4.136, 0};
913 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
918 printf ("Testing snprintf format codes against system sprintf...\n");
920 for (x = 0; fp_fmt[x] != NULL ; x++)
921 for (y = 0; fp_nums[y] != 0 ; y++)
923 snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]);
924 sprintf (buf2, fp_fmt[x], fp_nums[y]);
925 if (strcmp (buf1, buf2))
927 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
928 fp_fmt[x], buf1, buf2);
934 for (x = 0; int_fmt[x] != NULL ; x++)
935 for (y = 0; int_nums[y] != 0 ; y++)
937 snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]);
938 sprintf (buf2, int_fmt[x], int_nums[y]);
939 if (strcmp (buf1, buf2))
941 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
942 int_fmt[x], buf1, buf2);
947 printf ("%d tests failed out of %d.\n", fail, num);
949 #endif /* SNPRINTF_TEST */