1 /* $Id: snprintf.c 7230 2005-04-16 23:33:17Z rra $
3 ** Replacement for a missing snprintf or vsnprintf.
5 ** The following implementation of snprintf was taken mostly verbatim from
6 ** <http://www.fiction.net/~blong/programs/>; it is the version of snprintf
9 ** Please do not reformat or otherwise change this file more than
10 ** necessary so that later merges with the original source are easy.
11 ** Bug fixes and improvements should be sent back to the original author.
14 /* If we're running the test suite, rename snprintf and vsnprintf to avoid
15 conflicts with the system version. */
17 # define snprintf test_snprintf
18 # define vsnprintf test_vsnprintf
22 * Copyright Patrick Powell 1995
23 * This code is based on code written by Patrick Powell (papowell@astart.com)
24 * It may be used for any purpose as long as this notice remains intact
25 * on all source code distributions
28 /**************************************************************
30 * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
31 * A bombproof version of doprnt (dopr) included.
32 * Sigh. This sort of thing is always nasty do deal with. Note that
33 * the version here does not include floating point...
35 * snprintf() is used instead of sprintf() as it does limit checks
36 * for string length. This covers a nasty loophole.
38 * The other functions are there to prevent NULL pointers from
39 * causing nast effects.
42 * Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43
43 * This was ugly. It is still ugly. I opted out of floating point
44 * numbers, but the formatter understands just about everything
45 * from the normal C string format, at least as far as I can tell from
46 * the Solaris 2.5 printf(3S) man page.
48 * Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1
49 * Ok, added some minimal floating point support, which means this
50 * probably requires libm on most operating systems. Don't yet
51 * support the exponent (e,E) and sigfig (g,G). Also, fmtint()
52 * was pretty badly broken, it just wasn't being exercised in ways
53 * which showed it, so that's been fixed. Also, formated the code
54 * to mutt conventions, and removed dead code left over from the
55 * original. Also, there is now a builtin-test, just compile with:
56 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm
57 * and run snprintf for results.
59 * Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i
60 * The PGP code was using unsigned hexadecimal formats.
61 * Unfortunately, unsigned formats simply didn't work.
63 * Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8
64 * The original code assumed that both snprintf() and vsnprintf() were
65 * missing. Some systems only have snprintf() but not vsnprintf(), so
66 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
68 * Andrew Tridgell (tridge@samba.org) Oct 1998
69 * fixed handling of %.0f
70 * added test for HAVE_LONG_DOUBLE
72 * Russ Allbery <rra@stanford.edu> 2000-08-26
73 * fixed return value to comply with C99
74 * fixed handling of snprintf(NULL, ...)
76 * Hrvoje Niksic <hniksic@arsdigita.com> 2000-11-04
77 * include <stdio.h> for NULL.
78 * added support for long long.
79 * don't declare argument types to (v)snprintf if stdarg is not used.
81 **************************************************************/
86 #include <sys/types.h>
92 /* varargs declarations: */
95 #define HAVE_STDARGS /* let's hope that works everywhere (mj) */
96 #define VA_LOCAL_DECL va_list ap
97 #define VA_START(f) va_start(ap, f)
98 #define VA_SHIFT(v,t) ; /* no-op for ANSI */
99 #define VA_END va_end(ap)
101 #ifdef HAVE_LONG_DOUBLE
102 #define LDOUBLE long double
104 #define LDOUBLE double
107 #ifdef HAVE_LONG_LONG
108 # define LLONG long long
113 int snprintf (char *str, size_t count, const char *fmt, ...);
114 int vsnprintf (char *str, size_t count, const char *fmt, va_list arg);
116 static int dopr (char *buffer, size_t maxlen, const char *format,
118 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
119 const char *value, int flags, int min, int max);
120 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
121 LLONG value, int base, int min, int max, int flags);
122 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
123 LDOUBLE fvalue, int min, int max, int flags);
124 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c );
127 * dopr(): poor man's version of doprintf
130 /* format read states */
131 #define DP_S_DEFAULT 0
141 /* format flags - Bits */
142 #define DP_F_MINUS (1 << 0)
143 #define DP_F_PLUS (1 << 1)
144 #define DP_F_SPACE (1 << 2)
145 #define DP_F_NUM (1 << 3)
146 #define DP_F_ZERO (1 << 4)
147 #define DP_F_UP (1 << 5)
148 #define DP_F_UNSIGNED (1 << 6)
150 /* Conversion Flags */
154 #define DP_C_LDOUBLE 4
156 #define char_to_int(p) (p - '0')
157 #define MAX(p,q) ((p >= q) ? p : q)
158 #define MIN(p,q) ((p <= q) ? p : q)
160 static int dopr (char *buffer, size_t maxlen, const char *format, va_list args)
174 state = DP_S_DEFAULT;
175 currlen = flags = cflags = min = 0;
180 while (state != DP_S_DONE)
191 total += dopr_outch (buffer, &currlen, maxlen, ch);
223 if ('0' <= ch && ch <= '9')
225 min = 10*min + char_to_int (ch);
230 min = va_arg (args, int);
247 if ('0' <= ch && ch <= '9')
251 max = 10*max + char_to_int (ch);
256 max = va_arg (args, int);
275 cflags = DP_C_LDOUBLE;
281 if (cflags != DP_C_LONG)
303 if (cflags == DP_C_SHORT)
304 value = (short int) va_arg (args, int);
305 else if (cflags == DP_C_LONG)
306 value = va_arg (args, long int);
307 else if (cflags == DP_C_LLONG)
308 value = va_arg (args, LLONG);
310 value = va_arg (args, int);
311 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
314 flags |= DP_F_UNSIGNED;
315 if (cflags == DP_C_SHORT)
316 value = (unsigned short int) va_arg (args, unsigned int);
317 else if (cflags == DP_C_LONG)
318 value = va_arg (args, unsigned long int);
319 else if (cflags == DP_C_LLONG)
320 value = va_arg (args, unsigned LLONG);
322 value = va_arg (args, unsigned int);
323 total += fmtint (buffer, &currlen, maxlen, value, 8, 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, 10, min, max, flags);
340 flags |= DP_F_UNSIGNED;
341 if (cflags == DP_C_SHORT)
342 value = (unsigned short int) va_arg (args, unsigned int);
343 else if (cflags == DP_C_LONG)
344 value = va_arg (args, unsigned long int);
345 else if (cflags == DP_C_LLONG)
346 value = va_arg (args, unsigned LLONG);
348 value = va_arg (args, unsigned int);
349 total += fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
352 if (cflags == DP_C_LDOUBLE)
353 fvalue = va_arg (args, LDOUBLE);
355 fvalue = va_arg (args, double);
356 /* um, floating point? */
357 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
362 if (cflags == DP_C_LDOUBLE)
363 fvalue = va_arg (args, LDOUBLE);
365 fvalue = va_arg (args, double);
370 if (cflags == DP_C_LDOUBLE)
371 fvalue = va_arg (args, LDOUBLE);
373 fvalue = va_arg (args, double);
376 total += dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
379 strvalue = va_arg (args, char *);
380 total += fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
383 strvalue = va_arg (args, void *);
384 total += fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min,
388 if (cflags == DP_C_SHORT)
391 num = va_arg (args, short int *);
394 else if (cflags == DP_C_LONG)
397 num = va_arg (args, long int *);
400 else if (cflags == DP_C_LLONG)
403 num = va_arg (args, LLONG *);
409 num = va_arg (args, int *);
414 total += dopr_outch (buffer, &currlen, maxlen, ch);
417 /* not supported yet, treat as next char */
425 state = DP_S_DEFAULT;
426 flags = cflags = min = 0;
433 break; /* some picky compilers need this */
438 if (currlen < maxlen - 1)
439 buffer[currlen] = '\0';
441 buffer[maxlen - 1] = '\0';
446 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
447 const char *value, int flags, int min, int max)
449 int padlen, strln; /* amount to pad */
458 for (strln = 0; value[strln]; ++strln); /* strlen */
459 if (max >= 0 && max < strln)
461 padlen = min - strln;
464 if (flags & DP_F_MINUS)
465 padlen = -padlen; /* Left Justify */
469 total += dopr_outch (buffer, currlen, maxlen, ' ');
472 while (*value && ((max < 0) || (cnt < max)))
474 total += dopr_outch (buffer, currlen, maxlen, *value++);
479 total += dopr_outch (buffer, currlen, maxlen, ' ');
485 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
487 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
488 LLONG value, int base, int min, int max, int flags)
491 unsigned LLONG uvalue;
493 unsigned int place = 0;
494 int spadlen = 0; /* amount to space pad */
495 int zpadlen = 0; /* amount to zero pad */
504 if(!(flags & DP_F_UNSIGNED))
511 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
514 if (flags & DP_F_SPACE)
519 /* Should characters be upper case? */
520 digits = "0123456789ABCDEF";
522 digits = "0123456789abcdef";
525 convert[place++] = digits[uvalue % (unsigned)base];
526 uvalue = (uvalue / (unsigned)base );
527 } while(uvalue && (place < sizeof (convert)));
528 if (place == sizeof (convert)) place--;
531 zpadlen = max - place;
532 spadlen = min - MAX ((unsigned int)max, place) - (signvalue ? 1 : 0);
533 if (zpadlen < 0) zpadlen = 0;
534 if (spadlen < 0) spadlen = 0;
535 if (flags & DP_F_ZERO)
537 zpadlen = MAX(zpadlen, spadlen);
540 if (flags & DP_F_MINUS)
541 spadlen = -spadlen; /* Left Justifty */
543 #ifdef DEBUG_SNPRINTF
544 dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
545 zpadlen, spadlen, min, max, place));
551 total += dopr_outch (buffer, currlen, maxlen, ' ');
557 total += dopr_outch (buffer, currlen, maxlen, signvalue);
564 total += dopr_outch (buffer, currlen, maxlen, '0');
571 total += dopr_outch (buffer, currlen, maxlen, convert[--place]);
573 /* Left Justified spaces */
574 while (spadlen < 0) {
575 total += dopr_outch (buffer, currlen, maxlen, ' ');
582 static LDOUBLE abs_val (LDOUBLE value)
584 LDOUBLE result = value;
592 static LDOUBLE pow10 (int exp)
605 static LLONG round (LDOUBLE value)
610 value = value - intpart;
617 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
618 LDOUBLE fvalue, int min, int max, int flags)
626 int padlen = 0; /* amount to pad */
634 * AIX manpage says the default is 0, but Solaris says the default
635 * is 6, and sprintf on AIX defaults to 6
640 ufvalue = abs_val (fvalue);
645 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
648 if (flags & DP_F_SPACE)
652 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
658 * Sorry, we only support 9 digits past the decimal because of our
664 /* We "cheat" by converting the fractional part to integer by
665 * multiplying by a factor of 10
667 fracpart = round ((pow10 (max)) * (ufvalue - intpart));
669 if (fracpart >= pow10 (max))
672 fracpart -= pow10 (max);
675 #ifdef DEBUG_SNPRINTF
676 dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart));
679 /* Convert integer part */
682 (caps? "0123456789ABCDEF":"0123456789abcdef")[intpart % 10];
683 intpart = (intpart / 10);
684 } while(intpart && (iplace < 20));
685 if (iplace == 20) iplace--;
686 iconvert[iplace] = 0;
688 /* Convert fractional part */
691 (caps? "0123456789ABCDEF":"0123456789abcdef")[fracpart % 10];
692 fracpart = (fracpart / 10);
693 } while(fracpart && (fplace < 20));
694 if (fplace == 20) fplace--;
695 fconvert[fplace] = 0;
697 /* -1 for decimal point, another -1 if we are printing a sign */
698 padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0);
699 zpadlen = max - fplace;
704 if (flags & DP_F_MINUS)
705 padlen = -padlen; /* Left Justifty */
707 if ((flags & DP_F_ZERO) && (padlen > 0))
711 total += dopr_outch (buffer, currlen, maxlen, signvalue);
717 total += dopr_outch (buffer, currlen, maxlen, '0');
723 total += dopr_outch (buffer, currlen, maxlen, ' ');
727 total += dopr_outch (buffer, currlen, maxlen, signvalue);
730 total += dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
733 * Decimal point. This should probably use locale to find the correct
738 total += dopr_outch (buffer, currlen, maxlen, '.');
741 total += dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
746 total += dopr_outch (buffer, currlen, maxlen, '0');
752 total += dopr_outch (buffer, currlen, maxlen, ' ');
759 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c)
761 if (*currlen + 1 < maxlen)
762 buffer[(*currlen)++] = c;
766 int vsnprintf (char *str, size_t count, const char *fmt, va_list args)
770 return dopr(str, count, fmt, args);
775 int snprintf (char *str,size_t count,const char *fmt,...)
777 int snprintf (va_alist) va_dcl
789 VA_SHIFT (str, char *);
790 VA_SHIFT (count, size_t );
791 VA_SHIFT (fmt, char *);
792 total = vsnprintf(str, count, fmt, ap);
799 #define LONG_STRING 1024
803 char buf1[LONG_STRING];
804 char buf2[LONG_STRING];
821 double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
822 0.9996, 1.996, 4.136, 0};
835 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
840 printf ("Testing snprintf format codes against system sprintf...\n");
842 for (x = 0; fp_fmt[x] != NULL ; x++)
843 for (y = 0; fp_nums[y] != 0 ; y++)
845 snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]);
846 sprintf (buf2, fp_fmt[x], fp_nums[y]);
847 if (strcmp (buf1, buf2))
849 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
850 fp_fmt[x], buf1, buf2);
856 for (x = 0; int_fmt[x] != NULL ; x++)
857 for (y = 0; int_nums[y] != 0 ; y++)
859 snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]);
860 sprintf (buf2, int_fmt[x], int_nums[y]);
861 if (strcmp (buf1, buf2))
863 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
864 int_fmt[x], buf1, buf2);
869 printf ("%d tests failed out of %d.\n", fail, num);
871 #endif /* SNPRINTF_TEST */