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 * Paul Green (paulg@samba.org) April 9, 2003
57 * fixed handling of %f when converting fractions with leading zeros.
59 **************************************************************/
61 #ifndef NO_CONFIG_H /* for some tests */
75 #include <sys/types.h>
81 #if defined(HAVE_SNPRINTF) && defined(HAVE_VSNPRINTF) && defined(HAVE_C99_VSNPRINTF)
82 /* only include stdio.h if we are not re-defining snprintf or vsnprintf */
84 /* make the compiler happy with an empty file */
85 void dummy_snprintf(void) {}
88 #ifdef HAVE_LONG_DOUBLE
89 #define LDOUBLE long double
91 #define LDOUBLE double
95 #define LLONG long long
100 static size_t dopr(char *buffer, size_t maxlen, const char *format,
102 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
103 char *value, int flags, int min, int max);
104 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
105 long value, int base, int min, int max, int flags);
106 static void fmtfp(char *buffer, size_t *currlen, size_t maxlen,
107 LDOUBLE fvalue, int min, int max, int flags);
108 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c);
111 * dopr(): poor man's version of doprintf
114 /* format read states */
115 #define DP_S_DEFAULT 0
124 /* format flags - Bits */
125 #define DP_F_MINUS (1 << 0)
126 #define DP_F_PLUS (1 << 1)
127 #define DP_F_SPACE (1 << 2)
128 #define DP_F_NUM (1 << 3)
129 #define DP_F_ZERO (1 << 4)
130 #define DP_F_UP (1 << 5)
131 #define DP_F_UNSIGNED (1 << 6)
133 /* Conversion Flags */
136 #define DP_C_LDOUBLE 3
139 #define char_to_int(p) ((p)- '0')
141 #define MAX(p,q) (((p) >= (q)) ? (p) : (q))
144 static size_t dopr(char *buffer, size_t maxlen, const char *format, va_list args)
157 state = DP_S_DEFAULT;
158 currlen = flags = cflags = min = 0;
162 while (state != DP_S_DONE) {
171 dopr_outch (buffer, &currlen, maxlen, ch);
202 if (isdigit((unsigned char)ch)) {
203 min = 10*min + char_to_int (ch);
205 } else if (ch == '*') {
206 min = va_arg (args, int);
222 if (isdigit((unsigned char)ch)) {
225 max = 10*max + char_to_int (ch);
227 } else if (ch == '*') {
228 max = va_arg (args, int);
244 if (ch == 'l') { /* It's a long long */
250 cflags = DP_C_LDOUBLE;
262 if (cflags == DP_C_SHORT)
263 value = va_arg (args, int);
264 else if (cflags == DP_C_LONG)
265 value = va_arg (args, long int);
266 else if (cflags == DP_C_LLONG)
267 value = va_arg (args, LLONG);
269 value = va_arg (args, int);
270 fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
273 flags |= DP_F_UNSIGNED;
274 if (cflags == DP_C_SHORT)
275 value = va_arg (args, unsigned int);
276 else if (cflags == DP_C_LONG)
277 value = (long)va_arg (args, unsigned long int);
278 else if (cflags == DP_C_LLONG)
279 value = (long)va_arg (args, unsigned LLONG);
281 value = (long)va_arg (args, unsigned int);
282 fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
285 flags |= DP_F_UNSIGNED;
286 if (cflags == DP_C_SHORT)
287 value = va_arg (args, unsigned int);
288 else if (cflags == DP_C_LONG)
289 value = (long)va_arg (args, unsigned long int);
290 else if (cflags == DP_C_LLONG)
291 value = (LLONG)va_arg (args, unsigned LLONG);
293 value = (long)va_arg (args, unsigned int);
294 fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
299 flags |= DP_F_UNSIGNED;
300 if (cflags == DP_C_SHORT)
301 value = va_arg (args, unsigned int);
302 else if (cflags == DP_C_LONG)
303 value = (long)va_arg (args, unsigned long int);
304 else if (cflags == DP_C_LLONG)
305 value = (LLONG)va_arg (args, unsigned LLONG);
307 value = (long)va_arg (args, unsigned int);
308 fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
311 if (cflags == DP_C_LDOUBLE)
312 fvalue = va_arg (args, LDOUBLE);
314 fvalue = va_arg (args, double);
315 /* um, floating point? */
316 fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
321 if (cflags == DP_C_LDOUBLE)
322 fvalue = va_arg (args, LDOUBLE);
324 fvalue = va_arg (args, double);
329 if (cflags == DP_C_LDOUBLE)
330 fvalue = va_arg (args, LDOUBLE);
332 fvalue = va_arg (args, double);
335 dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
338 strvalue = va_arg (args, char *);
340 max = strlen(strvalue);
342 if (min > 0 && max >= 0 && min > max) max = min;
343 fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
346 strvalue = va_arg (args, void *);
347 fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min, max, flags);
350 if (cflags == DP_C_SHORT) {
352 num = va_arg (args, short int *);
354 } else if (cflags == DP_C_LONG) {
356 num = va_arg (args, long int *);
357 *num = (long int)currlen;
358 } else if (cflags == DP_C_LLONG) {
360 num = va_arg (args, LLONG *);
361 *num = (LLONG)currlen;
364 num = va_arg (args, int *);
369 dopr_outch (buffer, &currlen, maxlen, ch);
372 /* not supported yet, treat as next char */
380 state = DP_S_DEFAULT;
381 flags = cflags = min = 0;
388 break; /* some picky compilers need this */
392 if (currlen < maxlen - 1)
393 buffer[currlen] = '\0';
395 buffer[maxlen - 1] = '\0';
401 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
402 char *value, int flags, int min, int max)
404 int padlen, strln; /* amount to pad */
407 #ifdef DEBUG_SNPRINTF
408 printf("fmtstr min=%d max=%d s=[%s]\n", min, max, value);
414 for (strln = 0; value[strln]; ++strln); /* strlen */
415 padlen = min - strln;
418 if (flags & DP_F_MINUS)
419 padlen = -padlen; /* Left Justify */
421 while ((padlen > 0) && (cnt < max)) {
422 dopr_outch (buffer, currlen, maxlen, ' ');
426 while (*value && (cnt < max)) {
427 dopr_outch (buffer, currlen, maxlen, *value++);
430 while ((padlen < 0) && (cnt < max)) {
431 dopr_outch (buffer, currlen, maxlen, ' ');
437 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
439 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
440 long value, int base, int min, int max, int flags)
443 unsigned long uvalue;
446 int spadlen = 0; /* amount to space pad */
447 int zpadlen = 0; /* amount to zero pad */
455 if(!(flags & DP_F_UNSIGNED)) {
460 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
462 else if (flags & DP_F_SPACE)
467 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
471 (caps? "0123456789ABCDEF":"0123456789abcdef")
472 [uvalue % (unsigned)base ];
473 uvalue = (uvalue / (unsigned)base );
474 } while(uvalue && (place < 20));
475 if (place == 20) place--;
478 zpadlen = max - place;
479 spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
480 if (zpadlen < 0) zpadlen = 0;
481 if (spadlen < 0) spadlen = 0;
482 if (flags & DP_F_ZERO) {
483 zpadlen = MAX(zpadlen, spadlen);
486 if (flags & DP_F_MINUS)
487 spadlen = -spadlen; /* Left Justifty */
489 #ifdef DEBUG_SNPRINTF
490 printf("zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
491 zpadlen, spadlen, min, max, place);
495 while (spadlen > 0) {
496 dopr_outch (buffer, currlen, maxlen, ' ');
502 dopr_outch (buffer, currlen, maxlen, signvalue);
506 while (zpadlen > 0) {
507 dopr_outch (buffer, currlen, maxlen, '0');
514 dopr_outch (buffer, currlen, maxlen, convert[--place]);
516 /* Left Justified spaces */
517 while (spadlen < 0) {
518 dopr_outch (buffer, currlen, maxlen, ' ');
523 static LDOUBLE abs_val(LDOUBLE value)
525 LDOUBLE result = value;
533 static LDOUBLE POW10(int exp)
545 static LLONG ROUND(LDOUBLE value)
549 intpart = (LLONG)value;
550 value = value - intpart;
551 if (value >= 0.5) intpart++;
556 /* a replacement for modf that doesn't need the math library. Should
557 be portable, but slow */
558 static double my_modf(double x0, double *iptr)
565 for (i=0;i<100;i++) {
567 if (l <= (x+1) && l >= (x-1)) break;
573 /* yikes! the number is beyond what we can handle. What do we do? */
582 ret = my_modf(x0-l*f, &i2);
592 static void fmtfp (char *buffer, size_t *currlen, size_t maxlen,
593 LDOUBLE fvalue, int min, int max, int flags)
601 int padlen = 0; /* amount to pad */
610 * AIX manpage says the default is 0, but Solaris says the default
611 * is 6, and sprintf on AIX defaults to 6
616 ufvalue = abs_val (fvalue);
621 if (flags & DP_F_PLUS) { /* Do a sign (+/i) */
624 if (flags & DP_F_SPACE)
630 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
634 if (max == 0) ufvalue += 0.5; /* if max = 0 we must round */
638 * Sorry, we only support 16 digits past the decimal because of our
644 /* We "cheat" by converting the fractional part to integer by
645 * multiplying by a factor of 10
649 my_modf(temp, &intpart);
651 fracpart = ROUND((POW10(max)) * (ufvalue - intpart));
653 if (fracpart >= POW10(max)) {
655 fracpart -= POW10(max);
659 /* Convert integer part */
662 my_modf(intpart*0.1, &intpart);
664 index = (int) ((temp -intpart +0.05)* 10.0);
665 /* index = (int) (((double)(temp*0.1) -intpart +0.05) *10.0); */
666 /* printf ("%llf, %f, %x\n", temp, intpart, index); */
668 (caps? "0123456789ABCDEF":"0123456789abcdef")[index];
669 } while (intpart && (iplace < 311));
670 if (iplace == 311) iplace--;
671 iconvert[iplace] = 0;
673 /* Convert fractional part */
678 my_modf(fracpart*0.1, &fracpart);
680 index = (int) ((temp -fracpart +0.05)* 10.0);
681 /* index = (int) ((((temp/10) -fracpart) +0.05) *10); */
682 /* printf ("%lf, %lf, %ld\n", temp, fracpart, index); */
684 (caps? "0123456789ABCDEF":"0123456789abcdef")[index];
685 } while(fracpart && (fplace < 311));
686 if (fplace == 311) fplace--;
688 fconvert[fplace] = 0;
690 /* -1 for decimal point, another -1 if we are printing a sign */
691 padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0);
692 zpadlen = max - fplace;
693 if (zpadlen < 0) zpadlen = 0;
696 if (flags & DP_F_MINUS)
697 padlen = -padlen; /* Left Justifty */
699 if ((flags & DP_F_ZERO) && (padlen > 0)) {
701 dopr_outch (buffer, currlen, maxlen, signvalue);
706 dopr_outch (buffer, currlen, maxlen, '0');
711 dopr_outch (buffer, currlen, maxlen, ' ');
715 dopr_outch (buffer, currlen, maxlen, signvalue);
718 dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
720 #ifdef DEBUG_SNPRINTF
721 printf("fmtfp: fplace=%d zpadlen=%d\n", fplace, zpadlen);
725 * Decimal point. This should probably use locale to find the correct
729 dopr_outch (buffer, currlen, maxlen, '.');
731 while (zpadlen > 0) {
732 dopr_outch (buffer, currlen, maxlen, '0');
737 dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
741 dopr_outch (buffer, currlen, maxlen, ' ');
746 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c)
748 if (*currlen < maxlen) {
749 buffer[(*currlen)] = c;
754 #if !defined(HAVE_VSNPRINTF) || !defined(HAVE_C99_VSNPRINTF)
755 #define vsnprintf rsync_vsnprintf
756 int vsnprintf(char *str, size_t count, const char *fmt, va_list args)
758 return dopr(str, count, fmt, args);
762 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_C99_VSNPRINTF)
763 #define snprintf rsync_snprintf
764 int snprintf(char *str,size_t count,const char *fmt,...)
770 ret = vsnprintf(str, count, fmt, ap);
778 #ifndef HAVE_VASPRINTF
779 int vasprintf(char **ptr, const char *format, va_list ap)
783 ret = vsnprintf(NULL, 0, format, ap);
784 if (ret <= 0) return ret;
786 (*ptr) = (char *)malloc(ret+1);
787 if (!*ptr) return -1;
788 ret = vsnprintf(*ptr, ret+1, format, ap);
795 #ifndef HAVE_ASPRINTF
796 int asprintf(char **ptr, const char *format, ...)
801 va_start(ap, format);
802 ret = vasprintf(ptr, format, ap);
811 int sprintf(char *str,const char *fmt,...);
835 double fp_nums[] = { 6442452944.1234, -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
836 0.9996, 1.996, 4.136, 0};
850 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
864 char *str_vals[] = {"hello", "a", "", "a longer string", NULL};
869 printf ("Testing snprintf format codes against system sprintf...\n");
871 for (x = 0; fp_fmt[x] ; x++) {
872 for (y = 0; fp_nums[y] != 0 ; y++) {
873 int l1 = snprintf(NULL, 0, fp_fmt[x], fp_nums[y]);
874 int l2 = snprintf(buf1, sizeof(buf1), fp_fmt[x], fp_nums[y]);
875 sprintf (buf2, fp_fmt[x], fp_nums[y]);
876 if (strcmp (buf1, buf2)) {
877 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
878 fp_fmt[x], buf1, buf2);
882 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, fp_fmt[x]);
889 for (x = 0; int_fmt[x] ; x++) {
890 for (y = 0; int_nums[y] != 0 ; y++) {
891 int l1 = snprintf(NULL, 0, int_fmt[x], int_nums[y]);
892 int l2 = snprintf(buf1, sizeof(buf1), int_fmt[x], int_nums[y]);
893 sprintf (buf2, int_fmt[x], int_nums[y]);
894 if (strcmp (buf1, buf2)) {
895 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
896 int_fmt[x], buf1, buf2);
900 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, int_fmt[x]);
907 for (x = 0; str_fmt[x] ; x++) {
908 for (y = 0; str_vals[y] != 0 ; y++) {
909 int l1 = snprintf(NULL, 0, str_fmt[x], str_vals[y]);
910 int l2 = snprintf(buf1, sizeof(buf1), str_fmt[x], str_vals[y]);
911 sprintf (buf2, str_fmt[x], str_vals[y]);
912 if (strcmp (buf1, buf2)) {
913 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
914 str_fmt[x], buf1, buf2);
918 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, str_fmt[x]);
925 printf ("%d tests failed out of %d.\n", fail, num);
927 printf("seeing how many digits we support\n");
929 double v0 = 0.12345678901234567890123456789012345678901;
930 for (x=0; x<100; x++) {
931 snprintf(buf1, sizeof(buf1), "%1.1f", v0*pow(10, x));
932 sprintf(buf2, "%1.1f", v0*pow(10, x));
933 if (strcmp(buf1, buf2)) {
934 printf("we seem to support %d digits\n", x-1);
942 #endif /* SNPRINTF_TEST */