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
8 * Please do not reformat or otherwise change this file more than necessary so
9 * that later merges with the original source are easy. Bug fixes and
10 * improvements should be sent back to the original author.
12 * The canonical version of this file is maintained in the rra-c-util package,
13 * which can be found at <http://www.eyrie.org/~eagle/software/rra-c-util/>.
17 * If we're running the test suite, rename snprintf and vsnprintf to avoid
18 * conflicts with the system version.
21 # define snprintf test_snprintf
22 # define vsnprintf test_vsnprintf
26 * Copyright Patrick Powell 1995
27 * This code is based on code written by Patrick Powell (papowell@astart.com)
28 * It may be used for any purpose as long as this notice remains intact
29 * on all source code distributions
32 /**************************************************************
34 * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
35 * A bombproof version of doprnt (dopr) included.
36 * Sigh. This sort of thing is always nasty do deal with. Note that
37 * the version here does not include floating point...
39 * snprintf() is used instead of sprintf() as it does limit checks
40 * for string length. This covers a nasty loophole.
42 * The other functions are there to prevent NULL pointers from
43 * causing nast effects.
46 * Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43
47 * This was ugly. It is still ugly. I opted out of floating point
48 * numbers, but the formatter understands just about everything
49 * from the normal C string format, at least as far as I can tell from
50 * the Solaris 2.5 printf(3S) man page.
52 * Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1
53 * Ok, added some minimal floating point support, which means this
54 * probably requires libm on most operating systems. Don't yet
55 * support the exponent (e,E) and sigfig (g,G). Also, fmtint()
56 * was pretty badly broken, it just wasn't being exercised in ways
57 * which showed it, so that's been fixed. Also, formated the code
58 * to mutt conventions, and removed dead code left over from the
59 * original. Also, there is now a builtin-test, just compile with:
60 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm
61 * and run snprintf for results.
63 * Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i
64 * The PGP code was using unsigned hexadecimal formats.
65 * Unfortunately, unsigned formats simply didn't work.
67 * Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8
68 * The original code assumed that both snprintf() and vsnprintf() were
69 * missing. Some systems only have snprintf() but not vsnprintf(), so
70 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
72 * Andrew Tridgell (tridge@samba.org) Oct 1998
73 * fixed handling of %.0f
74 * added test for HAVE_LONG_DOUBLE
76 * Russ Allbery <eagle@eyrie.org> 2000-08-26
77 * fixed return value to comply with C99
78 * fixed handling of snprintf(NULL, ...)
80 * Hrvoje Niksic <hniksic@arsdigita.com> 2000-11-04
81 * include <stdio.h> for NULL.
82 * added support for long long.
83 * don't declare argument types to (v)snprintf if stdarg is not used.
85 * Hrvoje Niksic <hniksic@xemacs.org> 2005-04-15
86 * use the PARAMS macro to handle prototypes.
87 * write function definitions in the ansi2knr-friendly way.
88 * if string precision is specified, don't read VALUE past it.
89 * fix bug in fmtfp that caused 0.01 to be printed as 0.1.
90 * don't include <ctype.h> because none of it is used.
91 * interpret precision as number of significant digits with %g
92 * omit trailing decimal zeros with %g
94 **************************************************************/
100 #include <sys/types.h>
106 /* varargs declarations: */
109 #define HAVE_STDARGS /* let's hope that works everywhere (mj) */
110 #define VA_LOCAL_DECL va_list ap
111 #define VA_START(f) va_start(ap, f)
112 #define VA_SHIFT(v,t) ; /* no-op for ANSI */
113 #define VA_END va_end(ap)
115 /* Assume all compilers support long double, per Autoconf documentation. */
116 #define LDOUBLE long double
118 #ifdef HAVE_LONG_LONG_INT
119 # define LLONG long long
124 int snprintf (char *str, size_t count, const char *fmt, ...);
125 int vsnprintf (char *str, size_t count, const char *fmt, va_list arg);
127 static int dopr (char *buffer, size_t maxlen, const char *format,
129 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
130 const char *value, int flags, int min, int max);
131 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
132 LLONG value, int base, int min, int max, int flags);
133 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
134 LDOUBLE fvalue, int min, int max, int flags);
135 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c );
138 * dopr(): poor man's version of doprintf
141 /* format read states */
142 #define DP_S_DEFAULT 0
152 /* format flags - Bits */
153 #define DP_F_MINUS (1 << 0)
154 #define DP_F_PLUS (1 << 1)
155 #define DP_F_SPACE (1 << 2)
156 #define DP_F_NUM (1 << 3)
157 #define DP_F_ZERO (1 << 4)
158 #define DP_F_UP (1 << 5)
159 #define DP_F_UNSIGNED (1 << 6)
160 #define DP_F_FP_G (1 << 7)
162 /* Conversion Flags */
166 #define DP_C_LDOUBLE 4
168 #define char_to_int(p) (p - '0')
169 #define MAX(p,q) ((p >= q) ? p : q)
170 #define MIN(p,q) ((p <= q) ? p : q)
172 static int dopr (char *buffer, size_t maxlen, const char *format, va_list args)
186 state = DP_S_DEFAULT;
187 currlen = flags = cflags = min = 0;
192 while (state != DP_S_DONE)
203 total += dopr_outch (buffer, &currlen, maxlen, ch);
235 if ('0' <= ch && ch <= '9')
237 min = 10*min + char_to_int (ch);
242 min = va_arg (args, int);
259 if ('0' <= ch && ch <= '9')
263 max = 10*max + char_to_int (ch);
268 max = va_arg (args, int);
287 cflags = DP_C_LDOUBLE;
293 if (cflags != DP_C_LONG)
315 if (cflags == DP_C_SHORT)
316 value = (short int) va_arg (args, int);
317 else if (cflags == DP_C_LONG)
318 value = va_arg (args, long int);
319 else if (cflags == DP_C_LLONG)
320 value = va_arg (args, LLONG);
322 value = va_arg (args, int);
323 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
326 flags |= DP_F_UNSIGNED;
327 if (cflags == DP_C_SHORT)
328 value = (unsigned short int) va_arg (args, unsigned int);
329 else if (cflags == DP_C_LONG)
330 value = va_arg (args, unsigned long int);
331 else if (cflags == DP_C_LLONG)
332 value = va_arg (args, unsigned LLONG);
334 value = va_arg (args, unsigned int);
335 total += fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
338 flags |= DP_F_UNSIGNED;
339 if (cflags == DP_C_SHORT)
340 value = (unsigned short int) va_arg (args, unsigned int);
341 else if (cflags == DP_C_LONG)
342 value = va_arg (args, unsigned long int);
343 else if (cflags == DP_C_LLONG)
344 value = va_arg (args, unsigned LLONG);
346 value = va_arg (args, unsigned int);
347 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
352 flags |= DP_F_UNSIGNED;
353 if (cflags == DP_C_SHORT)
354 value = (unsigned short int) va_arg (args, unsigned int);
355 else if (cflags == DP_C_LONG)
356 value = va_arg (args, unsigned long int);
357 else if (cflags == DP_C_LLONG)
358 value = va_arg (args, unsigned LLONG);
360 value = va_arg (args, unsigned int);
361 total += fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
364 if (cflags == DP_C_LDOUBLE)
365 fvalue = va_arg (args, LDOUBLE);
367 fvalue = va_arg (args, double);
368 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
373 if (cflags == DP_C_LDOUBLE)
374 fvalue = va_arg (args, LDOUBLE);
376 fvalue = va_arg (args, double);
377 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
383 if (cflags == DP_C_LDOUBLE)
384 fvalue = va_arg (args, LDOUBLE);
386 fvalue = va_arg (args, double);
388 /* C99 says: if precision [for %g] is zero, it is taken as one */
390 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
393 total += dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
396 strvalue = va_arg (args, char *);
397 total += fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
400 strvalue = va_arg (args, void *);
401 total += fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min,
405 if (cflags == DP_C_SHORT)
408 num = va_arg (args, short int *);
411 else if (cflags == DP_C_LONG)
414 num = va_arg (args, long int *);
417 else if (cflags == DP_C_LLONG)
420 num = va_arg (args, LLONG *);
426 num = va_arg (args, int *);
431 total += dopr_outch (buffer, &currlen, maxlen, ch);
434 /* not supported yet, treat as next char */
442 state = DP_S_DEFAULT;
443 flags = cflags = min = 0;
450 break; /* some picky compilers need this */
455 if (currlen < maxlen - 1)
456 buffer[currlen] = '\0';
458 buffer[maxlen - 1] = '\0';
463 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
464 const char *value, int flags, int min, int max)
466 int padlen, strln; /* amount to pad */
476 strln = strlen (value);
478 /* When precision is specified, don't read VALUE past precision. */
479 /*strln = strnlen (value, max);*/
480 for (strln = 0; strln < max && value[strln]; ++strln);
481 padlen = min - strln;
484 if (flags & DP_F_MINUS)
485 padlen = -padlen; /* Left Justify */
489 total += dopr_outch (buffer, currlen, maxlen, ' ');
492 while (*value && ((max < 0) || (cnt < max)))
494 total += dopr_outch (buffer, currlen, maxlen, *value++);
499 total += dopr_outch (buffer, currlen, maxlen, ' ');
505 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
507 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
508 LLONG value, int base, int min, int max, int flags)
511 unsigned LLONG uvalue;
513 unsigned int place = 0;
514 int spadlen = 0; /* amount to space pad */
515 int zpadlen = 0; /* amount to zero pad */
524 if(!(flags & DP_F_UNSIGNED))
531 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
534 if (flags & DP_F_SPACE)
539 /* Should characters be upper case? */
540 digits = "0123456789ABCDEF";
542 digits = "0123456789abcdef";
545 convert[place++] = digits[uvalue % (unsigned)base];
546 uvalue = (uvalue / (unsigned)base );
547 } while(uvalue && (place < sizeof (convert)));
548 if (place == sizeof (convert)) place--;
551 zpadlen = max - place;
552 spadlen = min - MAX ((unsigned int)max, place) - (signvalue ? 1 : 0);
553 if (zpadlen < 0) zpadlen = 0;
554 if (spadlen < 0) spadlen = 0;
555 if (flags & DP_F_ZERO)
557 zpadlen = MAX(zpadlen, spadlen);
560 if (flags & DP_F_MINUS)
561 spadlen = -spadlen; /* Left Justifty */
563 #ifdef DEBUG_SNPRINTF
564 dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
565 zpadlen, spadlen, min, max, place));
571 total += dopr_outch (buffer, currlen, maxlen, ' ');
577 total += dopr_outch (buffer, currlen, maxlen, signvalue);
584 total += dopr_outch (buffer, currlen, maxlen, '0');
591 total += dopr_outch (buffer, currlen, maxlen, convert[--place]);
593 /* Left Justified spaces */
594 while (spadlen < 0) {
595 total += dopr_outch (buffer, currlen, maxlen, ' ');
602 static LDOUBLE abs_val (LDOUBLE value)
604 LDOUBLE result = value;
612 static LDOUBLE pow10_int (int exp)
625 static LLONG round_int (LDOUBLE value)
630 value = value - intpart;
637 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
638 LDOUBLE fvalue, int min, int max, int flags)
646 int padlen = 0; /* amount to pad */
652 int leadingfrac0s = 0; /* zeroes at the start of fractional part */
654 size_t omitcount = 0;
657 * AIX manpage says the default is 0, but Solaris says the default
658 * is 6, and sprintf on AIX defaults to 6
663 ufvalue = abs_val (fvalue);
668 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
671 if (flags & DP_F_SPACE)
675 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
680 /* With %g precision is the number of significant digits, which
681 includes the digits in intpart. */
682 if (flags & DP_F_FP_G)
686 /* For each digit of INTPART, print one less fractional digit. */
687 LLONG temp = intpart;
688 for (temp = intpart; temp != 0; temp /= 10)
695 /* For each leading 0 in fractional part, print one more
699 for (temp = ufvalue; temp < 0.1; temp *= 10)
704 /* C99: trailing zeros are removed from the fractional portion of the
705 result unless the # flag is specified */
706 if ((flags & DP_F_FP_G) && !(flags & DP_F_NUM))
709 #if SIZEOF_LONG_LONG > 0
710 # define MAX_DIGITS 18 /* grok more digits with long long */
712 # define MAX_DIGITS 9 /* just long */
716 * Sorry, we only support several digits past the decimal because of
717 * our conversion method
719 if (max > MAX_DIGITS)
722 /* Factor of 10 with the needed number of digits, e.g. 1000 for max==3 */
723 mask10 = pow10_int (max);
725 /* We "cheat" by converting the fractional part to integer by
726 * multiplying by a factor of 10
728 fracpart = round_int (mask10 * (ufvalue - intpart));
730 if (fracpart >= mask10)
735 else if (fracpart != 0)
736 /* If fracpart has less digits than the 10* mask, we need to
737 manually insert leading 0s. For example 2.01's fractional part
738 requires one leading zero to distinguish it from 2.1. */
739 while (fracpart < mask10 / 10)
745 #ifdef DEBUG_SNPRINTF
746 dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart));
749 /* Convert integer part */
751 iconvert[iplace++] = '0' + intpart % 10;
752 intpart = (intpart / 10);
753 } while(intpart && (iplace < sizeof(iconvert)));
754 if (iplace == sizeof(iconvert)) iplace--;
755 iconvert[iplace] = 0;
757 /* Convert fractional part */
759 fconvert[fplace++] = '0' + fracpart % 10;
760 fracpart = (fracpart / 10);
761 } while(fracpart && (fplace < sizeof(fconvert)));
762 while (leadingfrac0s-- > 0 && fplace < sizeof(fconvert))
763 fconvert[fplace++] = '0';
764 if (fplace == sizeof(fconvert)) fplace--;
765 fconvert[fplace] = 0;
767 while (omitcount < fplace && fconvert[omitcount] == '0')
770 /* -1 for decimal point, another -1 if we are printing a sign */
771 padlen = min - iplace - (max - omitcount) - 1 - ((signvalue) ? 1 : 0);
773 zpadlen = max - fplace;
778 if (flags & DP_F_MINUS)
779 padlen = -padlen; /* Left Justifty */
781 if ((flags & DP_F_ZERO) && (padlen > 0))
785 total += dopr_outch (buffer, currlen, maxlen, signvalue);
791 total += dopr_outch (buffer, currlen, maxlen, '0');
797 total += dopr_outch (buffer, currlen, maxlen, ' ');
801 total += dopr_outch (buffer, currlen, maxlen, signvalue);
804 total += dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
807 * Decimal point. This should probably use locale to find the correct
810 if (max > 0 && (fplace > omitcount || zpadlen > 0))
812 total += dopr_outch (buffer, currlen, maxlen, '.');
814 while (fplace > omitcount)
815 total += dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
820 total += dopr_outch (buffer, currlen, maxlen, '0');
826 total += dopr_outch (buffer, currlen, maxlen, ' ');
833 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c)
835 if (*currlen + 1 < maxlen)
836 buffer[(*currlen)++] = c;
840 int vsnprintf (char *str, size_t count, const char *fmt, va_list args)
844 return dopr(str, count, fmt, args);
849 int snprintf (char *str,size_t count,const char *fmt,...)
851 int snprintf (va_alist) va_dcl
863 VA_SHIFT (str, char *);
864 VA_SHIFT (count, size_t );
865 VA_SHIFT (fmt, char *);
866 total = vsnprintf(str, count, fmt, ap);
873 #define LONG_STRING 1024
877 char buf1[LONG_STRING];
878 char buf2[LONG_STRING];
895 double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
896 0.9996, 1.996, 4.136, 0};
909 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
914 printf ("Testing snprintf format codes against system sprintf...\n");
916 for (x = 0; fp_fmt[x] != NULL ; x++)
917 for (y = 0; fp_nums[y] != 0 ; y++)
919 snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]);
920 sprintf (buf2, fp_fmt[x], fp_nums[y]);
921 if (strcmp (buf1, buf2))
923 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
924 fp_fmt[x], buf1, buf2);
930 for (x = 0; int_fmt[x] != NULL ; x++)
931 for (y = 0; int_nums[y] != 0 ; y++)
933 snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]);
934 sprintf (buf2, int_fmt[x], int_nums[y]);
935 if (strcmp (buf1, buf2))
937 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
938 int_fmt[x], buf1, buf2);
943 printf ("%d tests failed out of %d.\n", fail, num);
945 #endif /* SNPRINTF_TEST */