2 * Copyright Patrick Powell 1995
3 * This code is based on code written by Patrick Powell (papowell@astart.com)
4 * It may be used for any purpose as long as this notice remains intact
5 * on all source code distributions
8 /**************************************************************
10 * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
11 * A bombproof version of doprnt (dopr) included.
12 * Sigh. This sort of thing is always nasty do deal with. Note that
13 * the version here does not include floating point...
15 * snprintf() is used instead of sprintf() as it does limit checks
16 * for string length. This covers a nasty loophole.
18 * The other functions are there to prevent NULL pointers from
19 * causing nast effects.
22 * Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43
23 * This was ugly. It is still ugly. I opted out of floating point
24 * numbers, but the formatter understands just about everything
25 * from the normal C string format, at least as far as I can tell from
26 * the Solaris 2.5 printf(3S) man page.
28 * Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1
29 * Ok, added some minimal floating point support, which means this
30 * probably requires libm on most operating systems. Don't yet
31 * support the exponent (e,E) and sigfig (g,G). Also, fmtint()
32 * was pretty badly broken, it just wasn't being exercised in ways
33 * which showed it, so that's been fixed. Also, formated the code
34 * to mutt conventions, and removed dead code left over from the
35 * original. Also, there is now a builtin-test, just compile with:
36 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm
37 * and run snprintf for results.
39 * Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i
40 * The PGP code was using unsigned hexadecimal formats.
41 * Unfortunately, unsigned formats simply didn't work.
43 * Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8
44 * The original code assumed that both snprintf() and vsnprintf() were
45 * missing. Some systems only have snprintf() but not vsnprintf(), so
46 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
48 * Andrew Tridgell (tridge@samba.org) Oct 1998
49 * fixed handling of %.0f
50 * added test for HAVE_LONG_DOUBLE
52 * tridge@samba.org, idra@samba.org, April 2001
53 * got rid of fcvt code (twas buggy and made testing harder)
56 **************************************************************/
58 #ifndef NO_CONFIG_H /* for some tests */
72 #include <sys/types.h>
78 #if defined(HAVE_SNPRINTF) && defined(HAVE_VSNPRINTF) && defined(HAVE_C99_VSNPRINTF)
79 /* only include stdio.h if we are not re-defining snprintf or vsnprintf */
81 /* make the compiler happy with an empty file */
82 void dummy_snprintf(void) {}
85 #ifdef HAVE_LONG_DOUBLE
86 #define LDOUBLE long double
88 #define LDOUBLE double
92 #define LLONG long long
97 static size_t dopr(char *buffer, size_t maxlen, const char *format,
99 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
100 char *value, int flags, int min, int max);
101 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
102 long value, int base, int min, int max, int flags);
103 static void fmtfp(char *buffer, size_t *currlen, size_t maxlen,
104 LDOUBLE fvalue, int min, int max, int flags);
105 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c);
108 * dopr(): poor man's version of doprintf
111 /* format read states */
112 #define DP_S_DEFAULT 0
121 /* format flags - Bits */
122 #define DP_F_MINUS (1 << 0)
123 #define DP_F_PLUS (1 << 1)
124 #define DP_F_SPACE (1 << 2)
125 #define DP_F_NUM (1 << 3)
126 #define DP_F_ZERO (1 << 4)
127 #define DP_F_UP (1 << 5)
128 #define DP_F_UNSIGNED (1 << 6)
130 /* Conversion Flags */
133 #define DP_C_LDOUBLE 3
136 #define char_to_int(p) ((p)- '0')
138 #define MAX(p,q) (((p) >= (q)) ? (p) : (q))
141 static size_t dopr(char *buffer, size_t maxlen, const char *format, va_list args)
154 state = DP_S_DEFAULT;
155 currlen = flags = cflags = min = 0;
159 while (state != DP_S_DONE) {
168 dopr_outch (buffer, &currlen, maxlen, ch);
199 if (isdigit((unsigned char)ch)) {
200 min = 10*min + char_to_int (ch);
202 } else if (ch == '*') {
203 min = va_arg (args, int);
219 if (isdigit((unsigned char)ch)) {
222 max = 10*max + char_to_int (ch);
224 } else if (ch == '*') {
225 max = va_arg (args, int);
241 if (ch == 'l') { /* It's a long long */
247 cflags = DP_C_LDOUBLE;
259 if (cflags == DP_C_SHORT)
260 value = va_arg (args, int);
261 else if (cflags == DP_C_LONG)
262 value = va_arg (args, long int);
263 else if (cflags == DP_C_LLONG)
264 value = va_arg (args, LLONG);
266 value = va_arg (args, int);
267 fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
270 flags |= DP_F_UNSIGNED;
271 if (cflags == DP_C_SHORT)
272 value = va_arg (args, unsigned int);
273 else if (cflags == DP_C_LONG)
274 value = (long)va_arg (args, unsigned long int);
275 else if (cflags == DP_C_LLONG)
276 value = (long)va_arg (args, unsigned LLONG);
278 value = (long)va_arg (args, unsigned int);
279 fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
282 flags |= DP_F_UNSIGNED;
283 if (cflags == DP_C_SHORT)
284 value = va_arg (args, unsigned int);
285 else if (cflags == DP_C_LONG)
286 value = (long)va_arg (args, unsigned long int);
287 else if (cflags == DP_C_LLONG)
288 value = (LLONG)va_arg (args, unsigned LLONG);
290 value = (long)va_arg (args, unsigned int);
291 fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
296 flags |= DP_F_UNSIGNED;
297 if (cflags == DP_C_SHORT)
298 value = va_arg (args, unsigned int);
299 else if (cflags == DP_C_LONG)
300 value = (long)va_arg (args, unsigned long int);
301 else if (cflags == DP_C_LLONG)
302 value = (LLONG)va_arg (args, unsigned LLONG);
304 value = (long)va_arg (args, unsigned int);
305 fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
308 if (cflags == DP_C_LDOUBLE)
309 fvalue = va_arg (args, LDOUBLE);
311 fvalue = va_arg (args, double);
312 /* um, floating point? */
313 fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
318 if (cflags == DP_C_LDOUBLE)
319 fvalue = va_arg (args, LDOUBLE);
321 fvalue = va_arg (args, double);
326 if (cflags == DP_C_LDOUBLE)
327 fvalue = va_arg (args, LDOUBLE);
329 fvalue = va_arg (args, double);
332 dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
335 strvalue = va_arg (args, char *);
336 if (!strvalue) strvalue = "(NULL)";
338 max = strlen(strvalue);
340 if (min > 0 && max >= 0 && min > max) max = min;
341 fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
344 strvalue = va_arg (args, void *);
345 fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min, max, flags);
348 if (cflags == DP_C_SHORT) {
350 num = va_arg (args, short int *);
352 } else if (cflags == DP_C_LONG) {
354 num = va_arg (args, long int *);
355 *num = (long int)currlen;
356 } else if (cflags == DP_C_LLONG) {
358 num = va_arg (args, LLONG *);
359 *num = (LLONG)currlen;
362 num = va_arg (args, int *);
367 dopr_outch (buffer, &currlen, maxlen, ch);
370 /* not supported yet, treat as next char */
378 state = DP_S_DEFAULT;
379 flags = cflags = min = 0;
386 break; /* some picky compilers need this */
390 if (currlen < maxlen - 1)
391 buffer[currlen] = '\0';
393 buffer[maxlen - 1] = '\0';
399 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
400 char *value, int flags, int min, int max)
402 int padlen, strln; /* amount to pad */
405 #ifdef DEBUG_SNPRINTF
406 printf("fmtstr min=%d max=%d s=[%s]\n", min, max, value);
412 for (strln = 0; value[strln]; ++strln); /* strlen */
413 padlen = min - strln;
416 if (flags & DP_F_MINUS)
417 padlen = -padlen; /* Left Justify */
419 while ((padlen > 0) && (cnt < max)) {
420 dopr_outch (buffer, currlen, maxlen, ' ');
424 while (*value && (cnt < max)) {
425 dopr_outch (buffer, currlen, maxlen, *value++);
428 while ((padlen < 0) && (cnt < max)) {
429 dopr_outch (buffer, currlen, maxlen, ' ');
435 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
437 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
438 long value, int base, int min, int max, int flags)
441 unsigned long uvalue;
444 int spadlen = 0; /* amount to space pad */
445 int zpadlen = 0; /* amount to zero pad */
453 if(!(flags & DP_F_UNSIGNED)) {
458 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
460 else if (flags & DP_F_SPACE)
465 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
469 (caps? "0123456789ABCDEF":"0123456789abcdef")
470 [uvalue % (unsigned)base ];
471 uvalue = (uvalue / (unsigned)base );
472 } while(uvalue && (place < 20));
473 if (place == 20) place--;
476 zpadlen = max - place;
477 spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
478 if (zpadlen < 0) zpadlen = 0;
479 if (spadlen < 0) spadlen = 0;
480 if (flags & DP_F_ZERO) {
481 zpadlen = MAX(zpadlen, spadlen);
484 if (flags & DP_F_MINUS)
485 spadlen = -spadlen; /* Left Justifty */
487 #ifdef DEBUG_SNPRINTF
488 printf("zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
489 zpadlen, spadlen, min, max, place);
493 while (spadlen > 0) {
494 dopr_outch (buffer, currlen, maxlen, ' ');
500 dopr_outch (buffer, currlen, maxlen, signvalue);
504 while (zpadlen > 0) {
505 dopr_outch (buffer, currlen, maxlen, '0');
512 dopr_outch (buffer, currlen, maxlen, convert[--place]);
514 /* Left Justified spaces */
515 while (spadlen < 0) {
516 dopr_outch (buffer, currlen, maxlen, ' ');
521 static LDOUBLE abs_val(LDOUBLE value)
523 LDOUBLE result = value;
531 static LDOUBLE POW10(int exp)
543 static LLONG ROUND(LDOUBLE value)
547 intpart = (LLONG)value;
548 value = value - intpart;
549 if (value >= 0.5) intpart++;
554 /* a replacement for modf that doesn't need the math library. Should
555 be portable, but slow */
556 static double my_modf(double x0, double *iptr)
563 for (i=0;i<100;i++) {
565 if (l <= (x+1) && l >= (x-1)) break;
571 /* yikes! the number is beyond what we can handle. What do we do? */
580 ret = my_modf(x0-l*f, &i2);
590 static void fmtfp (char *buffer, size_t *currlen, size_t maxlen,
591 LDOUBLE fvalue, int min, int max, int flags)
599 int padlen = 0; /* amount to pad */
608 * AIX manpage says the default is 0, but Solaris says the default
609 * is 6, and sprintf on AIX defaults to 6
614 ufvalue = abs_val (fvalue);
619 if (flags & DP_F_PLUS) { /* Do a sign (+/i) */
622 if (flags & DP_F_SPACE)
628 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
632 if (max == 0) ufvalue += 0.5; /* if max = 0 we must round */
636 * Sorry, we only support 16 digits past the decimal because of our
642 /* We "cheat" by converting the fractional part to integer by
643 * multiplying by a factor of 10
647 my_modf(temp, &intpart);
649 fracpart = ROUND((POW10(max)) * (ufvalue - intpart));
651 if (fracpart >= POW10(max)) {
653 fracpart -= POW10(max);
657 /* Convert integer part */
660 my_modf(intpart*0.1, &intpart);
662 index = (int) ((temp -intpart +0.05)* 10.0);
663 /* index = (int) (((double)(temp*0.1) -intpart +0.05) *10.0); */
664 /* printf ("%llf, %f, %x\n", temp, intpart, index); */
666 (caps? "0123456789ABCDEF":"0123456789abcdef")[index];
667 } while (intpart && (iplace < 311));
668 if (iplace == 311) iplace--;
669 iconvert[iplace] = 0;
671 /* Convert fractional part */
676 my_modf(fracpart*0.1, &fracpart);
678 index = (int) ((temp -fracpart +0.05)* 10.0);
679 /* index = (int) ((((temp/10) -fracpart) +0.05) *10); */
680 /* printf ("%lf, %lf, %ld\n", temp, fracpart, index); */
682 (caps? "0123456789ABCDEF":"0123456789abcdef")[index];
683 } while(fracpart && (fplace < 311));
684 if (fplace == 311) fplace--;
686 fconvert[fplace] = 0;
688 /* -1 for decimal point, another -1 if we are printing a sign */
689 padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0);
690 zpadlen = max - fplace;
691 if (zpadlen < 0) zpadlen = 0;
694 if (flags & DP_F_MINUS)
695 padlen = -padlen; /* Left Justifty */
697 if ((flags & DP_F_ZERO) && (padlen > 0)) {
699 dopr_outch (buffer, currlen, maxlen, signvalue);
704 dopr_outch (buffer, currlen, maxlen, '0');
709 dopr_outch (buffer, currlen, maxlen, ' ');
713 dopr_outch (buffer, currlen, maxlen, signvalue);
716 dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
718 #ifdef DEBUG_SNPRINTF
719 printf("fmtfp: fplace=%d zpadlen=%d\n", fplace, zpadlen);
723 * Decimal point. This should probably use locale to find the correct
727 dopr_outch (buffer, currlen, maxlen, '.');
730 dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
733 while (zpadlen > 0) {
734 dopr_outch (buffer, currlen, maxlen, '0');
739 dopr_outch (buffer, currlen, maxlen, ' ');
744 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c)
746 if (*currlen < maxlen) {
747 buffer[(*currlen)] = c;
752 /* yes this really must be a ||. Don't muck with this (tridge) */
753 #if !defined(HAVE_VSNPRINTF) || !defined(HAVE_C99_VSNPRINTF)
754 int vsnprintf (char *str, size_t count, const char *fmt, va_list args)
756 return dopr(str, count, fmt, args);
760 /* yes this really must be a ||. Don't muck wiith this (tridge)
762 * The logic for these two is that we need our own definition if the
763 * OS *either* has no definition of *sprintf, or if it does have one
764 * that doesn't work properly according to the autoconf test. Perhaps
765 * these should really be smb_snprintf to avoid conflicts with buggy
768 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_C99_SNPRINTF)
769 int snprintf(char *str,size_t count,const char *fmt,...)
775 ret = vsnprintf(str, count, fmt, ap);
783 #ifndef HAVE_VASPRINTF
784 int vasprintf(char **ptr, const char *format, va_list ap)
788 ret = vsnprintf(NULL, 0, format, ap);
789 if (ret <= 0) return ret;
791 (*ptr) = (char *)malloc(ret+1);
792 if (!*ptr) return -1;
793 ret = vsnprintf(*ptr, ret+1, format, ap);
800 #ifndef HAVE_ASPRINTF
801 int asprintf(char **ptr, const char *format, ...)
806 va_start(ap, format);
807 ret = vasprintf(ptr, format, ap);
816 void vsyslog (int facility_priority, char *format, va_list arglist)
819 vasprintf(&msg, format, arglist);
822 syslog(facility_priority, "%s", msg);
825 #endif /* HAVE_SYSLOG */
826 #endif /* HAVE_VSYSLOG */
830 int sprintf(char *str,const char *fmt,...);
854 double fp_nums[] = { 6442452944.1234, -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
855 0.9996, 1.996, 4.136, 0};
869 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
883 char *str_vals[] = {"hello", "a", "", "a longer string", NULL};
888 printf ("Testing snprintf format codes against system sprintf...\n");
890 for (x = 0; fp_fmt[x] ; x++) {
891 for (y = 0; fp_nums[y] != 0 ; y++) {
892 int l1 = snprintf(NULL, 0, fp_fmt[x], fp_nums[y]);
893 int l2 = snprintf(buf1, sizeof(buf1), fp_fmt[x], fp_nums[y]);
894 sprintf (buf2, fp_fmt[x], fp_nums[y]);
895 if (strcmp (buf1, buf2)) {
896 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
897 fp_fmt[x], buf1, buf2);
901 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, fp_fmt[x]);
908 for (x = 0; int_fmt[x] ; x++) {
909 for (y = 0; int_nums[y] != 0 ; y++) {
910 int l1 = snprintf(NULL, 0, int_fmt[x], int_nums[y]);
911 int l2 = snprintf(buf1, sizeof(buf1), int_fmt[x], int_nums[y]);
912 sprintf (buf2, int_fmt[x], int_nums[y]);
913 if (strcmp (buf1, buf2)) {
914 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
915 int_fmt[x], buf1, buf2);
919 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, int_fmt[x]);
926 for (x = 0; str_fmt[x] ; x++) {
927 for (y = 0; str_vals[y] != 0 ; y++) {
928 int l1 = snprintf(NULL, 0, str_fmt[x], str_vals[y]);
929 int l2 = snprintf(buf1, sizeof(buf1), str_fmt[x], str_vals[y]);
930 sprintf (buf2, str_fmt[x], str_vals[y]);
931 if (strcmp (buf1, buf2)) {
932 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
933 str_fmt[x], buf1, buf2);
937 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, str_fmt[x]);
944 printf ("%d tests failed out of %d.\n", fail, num);
946 printf("seeing how many digits we support\n");
948 double v0 = 0.12345678901234567890123456789012345678901;
949 for (x=0; x<100; x++) {
950 snprintf(buf1, sizeof(buf1), "%1.1f", v0*pow(10, x));
951 sprintf(buf2, "%1.1f", v0*pow(10, x));
952 if (strcmp(buf1, buf2)) {
953 printf("we seem to support %d digits\n", x-1);
961 #endif /* SNPRINTF_TEST */