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 */
64 #ifdef TEST_SNPRINTF /* need math library headers for testing */
78 #include <sys/types.h>
86 #define VA_COPY(dest, src) va_copy(dest, src)
87 #elif defined(HAVE___VA_COPY)
88 #define VA_COPY(dest, src) __va_copy(dest, src)
90 #define VA_COPY(dest, src) (dest) = (src)
95 #if defined(HAVE_SNPRINTF) && defined(HAVE_VSNPRINTF) && defined(HAVE_C99_VSNPRINTF)
96 /* only include stdio.h if we are not re-defining snprintf or vsnprintf */
98 /* make the compiler happy with an empty file */
99 void dummy_snprintf(void) {}
102 #ifdef HAVE_LONG_DOUBLE
103 #define LDOUBLE long double
105 #define LDOUBLE double
108 #ifdef HAVE_LONG_LONG
109 #define LLONG long long
114 /* free memory if the pointer is valid and zero the pointer */
116 #define SAFE_FREE(x) do { if ((x) != NULL) {free((x)); (x)=NULL;} } while(0)
119 static size_t dopr(char *buffer, size_t maxlen, const char *format,
121 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
122 char *value, int flags, int min, int max);
123 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
124 long value, int base, int min, int max, int flags);
125 static void fmtfp(char *buffer, size_t *currlen, size_t maxlen,
126 LDOUBLE fvalue, int min, int max, int flags);
127 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c);
130 * dopr(): poor man's version of doprintf
133 /* format read states */
134 #define DP_S_DEFAULT 0
143 /* format flags - Bits */
144 #define DP_F_MINUS (1 << 0)
145 #define DP_F_PLUS (1 << 1)
146 #define DP_F_SPACE (1 << 2)
147 #define DP_F_NUM (1 << 3)
148 #define DP_F_ZERO (1 << 4)
149 #define DP_F_UP (1 << 5)
150 #define DP_F_UNSIGNED (1 << 6)
152 /* Conversion Flags */
155 #define DP_C_LDOUBLE 3
158 #define char_to_int(p) ((p)- '0')
160 #define MAX(p,q) (((p) >= (q)) ? (p) : (q))
163 static size_t dopr(char *buffer, size_t maxlen, const char *format, va_list args_in)
177 VA_COPY(args, args_in);
179 state = DP_S_DEFAULT;
180 currlen = flags = cflags = min = 0;
184 while (state != DP_S_DONE) {
193 dopr_outch (buffer, &currlen, maxlen, ch);
224 if (isdigit((unsigned char)ch)) {
225 min = 10*min + char_to_int (ch);
227 } else if (ch == '*') {
228 min = va_arg (args, int);
244 if (isdigit((unsigned char)ch)) {
247 max = 10*max + char_to_int (ch);
249 } else if (ch == '*') {
250 max = va_arg (args, int);
266 if (ch == 'l') { /* It's a long long */
272 cflags = DP_C_LDOUBLE;
284 if (cflags == DP_C_SHORT)
285 value = va_arg (args, int);
286 else if (cflags == DP_C_LONG)
287 value = va_arg (args, long int);
288 else if (cflags == DP_C_LLONG)
289 value = va_arg (args, LLONG);
291 value = va_arg (args, int);
292 fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
295 flags |= DP_F_UNSIGNED;
296 if (cflags == DP_C_SHORT)
297 value = va_arg (args, unsigned int);
298 else if (cflags == DP_C_LONG)
299 value = (long)va_arg (args, unsigned long int);
300 else if (cflags == DP_C_LLONG)
301 value = (long)va_arg (args, unsigned LLONG);
303 value = (long)va_arg (args, unsigned int);
304 fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
307 flags |= DP_F_UNSIGNED;
308 if (cflags == DP_C_SHORT)
309 value = va_arg (args, unsigned int);
310 else if (cflags == DP_C_LONG)
311 value = (long)va_arg (args, unsigned long int);
312 else if (cflags == DP_C_LLONG)
313 value = (LLONG)va_arg (args, unsigned LLONG);
315 value = (long)va_arg (args, unsigned int);
316 fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
321 flags |= DP_F_UNSIGNED;
322 if (cflags == DP_C_SHORT)
323 value = va_arg (args, unsigned int);
324 else if (cflags == DP_C_LONG)
325 value = (long)va_arg (args, unsigned long int);
326 else if (cflags == DP_C_LLONG)
327 value = (LLONG)va_arg (args, unsigned LLONG);
329 value = (long)va_arg (args, unsigned int);
330 fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
333 if (cflags == DP_C_LDOUBLE)
334 fvalue = va_arg (args, LDOUBLE);
336 fvalue = va_arg (args, double);
337 /* um, floating point? */
338 fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
343 if (cflags == DP_C_LDOUBLE)
344 fvalue = va_arg (args, LDOUBLE);
346 fvalue = va_arg (args, double);
347 fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
352 if (cflags == DP_C_LDOUBLE)
353 fvalue = va_arg (args, LDOUBLE);
355 fvalue = va_arg (args, double);
356 fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
359 dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
362 strvalue = va_arg (args, char *);
363 if (!strvalue) strvalue = "(NULL)";
365 max = strlen(strvalue);
367 if (min > 0 && max >= 0 && min > max) max = min;
368 fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
371 strvalue = va_arg (args, void *);
372 fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min, max, flags);
375 if (cflags == DP_C_SHORT) {
377 num = va_arg (args, short int *);
379 } else if (cflags == DP_C_LONG) {
381 num = va_arg (args, long int *);
382 *num = (long int)currlen;
383 } else if (cflags == DP_C_LLONG) {
385 num = va_arg (args, LLONG *);
386 *num = (LLONG)currlen;
389 num = va_arg (args, int *);
394 dopr_outch (buffer, &currlen, maxlen, ch);
397 /* not supported yet, treat as next char */
405 state = DP_S_DEFAULT;
406 flags = cflags = min = 0;
413 break; /* some picky compilers need this */
417 if (currlen < maxlen - 1)
418 buffer[currlen] = '\0';
420 buffer[maxlen - 1] = '\0';
426 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
427 char *value, int flags, int min, int max)
429 int padlen, strln; /* amount to pad */
432 #ifdef DEBUG_SNPRINTF
433 printf("fmtstr min=%d max=%d s=[%s]\n", min, max, value);
439 for (strln = 0; value[strln]; ++strln); /* strlen */
440 padlen = min - strln;
443 if (flags & DP_F_MINUS)
444 padlen = -padlen; /* Left Justify */
446 while ((padlen > 0) && (cnt < max)) {
447 dopr_outch (buffer, currlen, maxlen, ' ');
451 while (*value && (cnt < max)) {
452 dopr_outch (buffer, currlen, maxlen, *value++);
455 while ((padlen < 0) && (cnt < max)) {
456 dopr_outch (buffer, currlen, maxlen, ' ');
462 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
464 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
465 long value, int base, int min, int max, int flags)
468 unsigned long uvalue;
471 int spadlen = 0; /* amount to space pad */
472 int zpadlen = 0; /* amount to zero pad */
480 if(!(flags & DP_F_UNSIGNED)) {
485 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
487 else if (flags & DP_F_SPACE)
492 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
496 (caps? "0123456789ABCDEF":"0123456789abcdef")
497 [uvalue % (unsigned)base ];
498 uvalue = (uvalue / (unsigned)base );
499 } while(uvalue && (place < 20));
500 if (place == 20) place--;
503 zpadlen = max - place;
504 spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
505 if (zpadlen < 0) zpadlen = 0;
506 if (spadlen < 0) spadlen = 0;
507 if (flags & DP_F_ZERO) {
508 zpadlen = MAX(zpadlen, spadlen);
511 if (flags & DP_F_MINUS)
512 spadlen = -spadlen; /* Left Justifty */
514 #ifdef DEBUG_SNPRINTF
515 printf("zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
516 zpadlen, spadlen, min, max, place);
520 while (spadlen > 0) {
521 dopr_outch (buffer, currlen, maxlen, ' ');
527 dopr_outch (buffer, currlen, maxlen, signvalue);
531 while (zpadlen > 0) {
532 dopr_outch (buffer, currlen, maxlen, '0');
539 dopr_outch (buffer, currlen, maxlen, convert[--place]);
541 /* Left Justified spaces */
542 while (spadlen < 0) {
543 dopr_outch (buffer, currlen, maxlen, ' ');
548 static LDOUBLE abs_val(LDOUBLE value)
550 LDOUBLE result = value;
558 static LDOUBLE POW10(int exp)
570 static LLONG ROUND(LDOUBLE value)
574 intpart = (LLONG)value;
575 value = value - intpart;
576 if (value >= 0.5) intpart++;
581 /* a replacement for modf that doesn't need the math library. Should
582 be portable, but slow */
583 static double my_modf(double x0, double *iptr)
590 for (i=0;i<100;i++) {
592 if (l <= (x+1) && l >= (x-1)) break;
598 /* yikes! the number is beyond what we can handle. What do we do? */
607 ret = my_modf(x0-l*f, &i2);
617 static void 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 */
635 * AIX manpage says the default is 0, but Solaris says the default
636 * is 6, and sprintf on AIX defaults to 6
641 ufvalue = abs_val (fvalue);
646 if (flags & DP_F_PLUS) { /* Do a sign (+/i) */
649 if (flags & DP_F_SPACE)
655 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
659 if (max == 0) ufvalue += 0.5; /* if max = 0 we must round */
663 * Sorry, we only support 16 digits past the decimal because of our
669 /* We "cheat" by converting the fractional part to integer by
670 * multiplying by a factor of 10
674 my_modf(temp, &intpart);
676 fracpart = ROUND((POW10(max)) * (ufvalue - intpart));
678 if (fracpart >= POW10(max)) {
680 fracpart -= POW10(max);
684 /* Convert integer part */
687 my_modf(temp, &intpart);
688 index = (int) ((temp -intpart +0.05)* 10.0);
689 /* index = (int) (((double)(temp*0.1) -intpart +0.05) *10.0); */
690 /* printf ("%llf, %f, %x\n", temp, intpart, index); */
692 (caps? "0123456789ABCDEF":"0123456789abcdef")[index];
693 } while (intpart && (iplace < 311));
694 if (iplace == 311) iplace--;
695 iconvert[iplace] = 0;
697 /* Convert fractional part */
702 my_modf(temp, &fracpart);
703 index = (int) ((temp -fracpart +0.05)* 10.0);
704 /* index = (int) ((((temp/10) -fracpart) +0.05) *10); */
705 /* printf ("%lf, %lf, %ld\n", temp, fracpart, index); */
707 (caps? "0123456789ABCDEF":"0123456789abcdef")[index];
708 } while(fracpart && (fplace < 311));
709 if (fplace == 311) fplace--;
711 fconvert[fplace] = 0;
713 /* -1 for decimal point, another -1 if we are printing a sign */
714 padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0);
715 zpadlen = max - fplace;
716 if (zpadlen < 0) zpadlen = 0;
719 if (flags & DP_F_MINUS)
720 padlen = -padlen; /* Left Justifty */
722 if ((flags & DP_F_ZERO) && (padlen > 0)) {
724 dopr_outch (buffer, currlen, maxlen, signvalue);
729 dopr_outch (buffer, currlen, maxlen, '0');
734 dopr_outch (buffer, currlen, maxlen, ' ');
738 dopr_outch (buffer, currlen, maxlen, signvalue);
741 dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
743 #ifdef DEBUG_SNPRINTF
744 printf("fmtfp: fplace=%d zpadlen=%d\n", fplace, zpadlen);
748 * Decimal point. This should probably use locale to find the correct
752 dopr_outch (buffer, currlen, maxlen, '.');
754 while (zpadlen > 0) {
755 dopr_outch (buffer, currlen, maxlen, '0');
760 dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
764 dopr_outch (buffer, currlen, maxlen, ' ');
769 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c)
771 if (*currlen < maxlen) {
772 buffer[(*currlen)] = c;
777 /* yes this really must be a ||. Don't muck with this (tridge) */
778 #if !defined(HAVE_VSNPRINTF) || !defined(HAVE_C99_VSNPRINTF)
779 int vsnprintf (char *str, size_t count, const char *fmt, va_list args)
781 return dopr(str, count, fmt, args);
785 /* yes this really must be a ||. Don't muck wiith this (tridge)
787 * The logic for these two is that we need our own definition if the
788 * OS *either* has no definition of *sprintf, or if it does have one
789 * that doesn't work properly according to the autoconf test. Perhaps
790 * these should really be smb_snprintf to avoid conflicts with buggy
793 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_C99_SNPRINTF)
794 int snprintf(char *str,size_t count,const char *fmt,...)
800 ret = vsnprintf(str, count, fmt, ap);
808 #ifndef HAVE_VASPRINTF
809 int vasprintf(char **ptr, const char *format, va_list ap)
816 ret = vsnprintf(NULL, 0, format, ap2);
817 if (ret <= 0) return ret;
819 (*ptr) = (char *)malloc(ret+1);
820 if (!*ptr) return -1;
824 ret = vsnprintf(*ptr, ret+1, format, ap2);
831 #ifndef HAVE_ASPRINTF
832 int asprintf(char **ptr, const char *format, ...)
838 va_start(ap, format);
839 ret = vasprintf(ptr, format, ap);
848 int sprintf(char *str,const char *fmt,...);
872 double fp_nums[] = { 6442452944.1234, -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
873 0.9996, 1.996, 4.136, 5.030201, 0};
887 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
901 char *str_vals[] = {"hello", "a", "", "a longer string", NULL};
906 printf ("Testing snprintf format codes against system sprintf...\n");
908 for (x = 0; fp_fmt[x] ; x++) {
909 for (y = 0; fp_nums[y] != 0 ; y++) {
910 int l1 = snprintf(NULL, 0, fp_fmt[x], fp_nums[y]);
911 int l2 = snprintf(buf1, sizeof(buf1), fp_fmt[x], fp_nums[y]);
912 sprintf (buf2, fp_fmt[x], fp_nums[y]);
913 if (strcmp (buf1, buf2)) {
914 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
915 fp_fmt[x], buf1, buf2);
919 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, fp_fmt[x]);
926 for (x = 0; int_fmt[x] ; x++) {
927 for (y = 0; int_nums[y] != 0 ; y++) {
928 int l1 = snprintf(NULL, 0, int_fmt[x], int_nums[y]);
929 int l2 = snprintf(buf1, sizeof(buf1), int_fmt[x], int_nums[y]);
930 sprintf (buf2, int_fmt[x], int_nums[y]);
931 if (strcmp (buf1, buf2)) {
932 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
933 int_fmt[x], buf1, buf2);
937 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, int_fmt[x]);
944 for (x = 0; str_fmt[x] ; x++) {
945 for (y = 0; str_vals[y] != 0 ; y++) {
946 int l1 = snprintf(NULL, 0, str_fmt[x], str_vals[y]);
947 int l2 = snprintf(buf1, sizeof(buf1), str_fmt[x], str_vals[y]);
948 sprintf (buf2, str_fmt[x], str_vals[y]);
949 if (strcmp (buf1, buf2)) {
950 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
951 str_fmt[x], buf1, buf2);
955 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, str_fmt[x]);
962 printf ("%d tests failed out of %d.\n", fail, num);
964 printf("seeing how many digits we support\n");
966 double v0 = 0.12345678901234567890123456789012345678901;
967 for (x=0; x<100; x++) {
968 double p = pow(10, x);
970 snprintf(buf1, sizeof(buf1), "%1.1f", r);
971 sprintf(buf2, "%1.1f", r);
972 if (strcmp(buf1, buf2)) {
973 printf("we seem to support %d digits\n", x-1);
981 #endif /* SNPRINTF_TEST */