2 * NOTE: If you change this file, please merge it into rsync, samba, etc.
6 * Copyright Patrick Powell 1995
7 * This code is based on code written by Patrick Powell (papowell@astart.com)
8 * It may be used for any purpose as long as this notice remains intact
9 * on all source code distributions
12 /**************************************************************
14 * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
15 * A bombproof version of doprnt (dopr) included.
16 * Sigh. This sort of thing is always nasty do deal with. Note that
17 * the version here does not include floating point...
19 * snprintf() is used instead of sprintf() as it does limit checks
20 * for string length. This covers a nasty loophole.
22 * The other functions are there to prevent NULL pointers from
23 * causing nast effects.
26 * Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43
27 * This was ugly. It is still ugly. I opted out of floating point
28 * numbers, but the formatter understands just about everything
29 * from the normal C string format, at least as far as I can tell from
30 * the Solaris 2.5 printf(3S) man page.
32 * Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1
33 * Ok, added some minimal floating point support, which means this
34 * probably requires libm on most operating systems. Don't yet
35 * support the exponent (e,E) and sigfig (g,G). Also, fmtint()
36 * was pretty badly broken, it just wasn't being exercised in ways
37 * which showed it, so that's been fixed. Also, formated the code
38 * to mutt conventions, and removed dead code left over from the
39 * original. Also, there is now a builtin-test, just compile with:
40 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm
41 * and run snprintf for results.
43 * Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i
44 * The PGP code was using unsigned hexadecimal formats.
45 * Unfortunately, unsigned formats simply didn't work.
47 * Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8
48 * The original code assumed that both snprintf() and vsnprintf() were
49 * missing. Some systems only have snprintf() but not vsnprintf(), so
50 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
52 * Andrew Tridgell (tridge@samba.org) Oct 1998
53 * fixed handling of %.0f
54 * added test for HAVE_LONG_DOUBLE
56 * tridge@samba.org, idra@samba.org, April 2001
57 * got rid of fcvt code (twas buggy and made testing harder)
60 * date: 2002/12/19 19:56:31; author: herb; state: Exp; lines: +2 -0
61 * actually print args for %g and %e
63 * date: 2002/06/03 13:37:52; author: jmcd; state: Exp; lines: +8 -0
64 * Since includes.h isn't included here, VA_COPY has to be defined here. I don't
65 * see any include file that is guaranteed to be here, so I'm defining it
66 * locally. Fixes AIX and Solaris builds.
68 * date: 2002/06/03 03:07:24; author: tridge; state: Exp; lines: +5 -13
69 * put the ifdef for HAVE_VA_COPY in one place rather than in lots of
72 * date: 2002/05/17 14:51:22; author: jmcd; state: Exp; lines: +21 -4
73 * Fix usage of va_list passed as an arg. Use __va_copy before using it
76 * date: 2002/04/16 22:38:04; author: idra; state: Exp; lines: +20 -14
77 * Fix incorrect zpadlen handling in fmtfp.
78 * Thanks to Ollie Oldham <ollie.oldham@metro-optix.com> for spotting it.
79 * few mods to make it easier to compile the tests.
80 * addedd the "Ollie" test to the floating point ones.
82 * Martin Pool (mbp@samba.org) April 2003
83 * Remove NO_CONFIG_H so that the test case can be built within a source
84 * tree with less trouble.
85 * Remove unnecessary SAFE_FREE() definition.
87 * Martin Pool (mbp@samba.org) May 2003
88 * Put in a prototype for dummy_snprintf() to quiet compiler warnings.
90 * Move #endif to make sure VA_COPY, LDOUBLE, etc are defined even
91 * if the C library has some snprintf functions already.
92 **************************************************************/
100 #ifdef TEST_SNPRINTF /* need math library headers for testing */
102 /* In test mode, we pretend that this system doesn't have any snprintf
103 * functions, regardless of what config.h says. */
104 # undef HAVE_SNPRINTF
105 # undef HAVE_VSNPRINTF
106 # undef HAVE_C99_VSNPRINTF
107 # undef HAVE_ASPRINTF
108 # undef HAVE_VASPRINTF
110 #endif /* TEST_SNPRINTF */
116 #ifdef HAVE_STRINGS_H
122 #include <sys/types.h>
128 #if defined(HAVE_SNPRINTF) && defined(HAVE_VSNPRINTF) && defined(HAVE_C99_VSNPRINTF)
129 /* only include stdio.h if we are not re-defining snprintf or vsnprintf */
131 /* make the compiler happy with an empty file */
132 void dummy_snprintf(void);
133 void dummy_snprintf(void) {}
134 #endif /* HAVE_SNPRINTF, etc */
136 #ifdef HAVE_LONG_DOUBLE
137 #define LDOUBLE long double
139 #define LDOUBLE double
143 #define LLONG long long
149 #if defined HAVE_VA_COPY || defined va_copy
150 #define VA_COPY(dest, src) va_copy(dest, src)
152 #ifdef HAVE___VA_COPY
153 #define VA_COPY(dest, src) __va_copy(dest, src)
155 #define VA_COPY(dest, src) (dest) = (src)
160 * dopr(): poor man's version of doprintf
163 /* format read states */
164 #define DP_S_DEFAULT 0
173 /* format flags - Bits */
174 #define DP_F_MINUS (1 << 0)
175 #define DP_F_PLUS (1 << 1)
176 #define DP_F_SPACE (1 << 2)
177 #define DP_F_NUM (1 << 3)
178 #define DP_F_ZERO (1 << 4)
179 #define DP_F_UP (1 << 5)
180 #define DP_F_UNSIGNED (1 << 6)
182 /* Conversion Flags */
185 #define DP_C_LDOUBLE 3
188 #define char_to_int(p) ((p)- '0')
190 #define MAX(p,q) (((p) >= (q)) ? (p) : (q))
193 /* yes this really must be a ||. Don't muck with this (tridge) */
194 #if !defined(HAVE_VSNPRINTF) || !defined(HAVE_C99_VSNPRINTF)
196 static size_t dopr(char *buffer, size_t maxlen, const char *format,
198 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
199 char *value, int flags, int min, int max);
200 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
201 long value, int base, int min, int max, int flags);
202 static void fmtfp(char *buffer, size_t *currlen, size_t maxlen,
203 LDOUBLE fvalue, int min, int max, int flags);
204 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c);
206 static size_t dopr(char *buffer, size_t maxlen, const char *format, va_list args_in)
220 VA_COPY(args, args_in);
222 state = DP_S_DEFAULT;
223 currlen = flags = cflags = min = 0;
227 while (state != DP_S_DONE) {
236 dopr_outch (buffer, &currlen, maxlen, ch);
267 if (isdigit((unsigned char)ch)) {
268 min = 10*min + char_to_int (ch);
270 } else if (ch == '*') {
271 min = va_arg (args, int);
287 if (isdigit((unsigned char)ch)) {
290 max = 10*max + char_to_int (ch);
292 } else if (ch == '*') {
293 max = va_arg (args, int);
309 if (ch == 'l') { /* It's a long long */
315 cflags = DP_C_LDOUBLE;
327 if (cflags == DP_C_SHORT)
328 value = va_arg (args, int);
329 else if (cflags == DP_C_LONG)
330 value = va_arg (args, long int);
331 else if (cflags == DP_C_LLONG)
332 value = va_arg (args, LLONG);
334 value = va_arg (args, int);
335 fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
338 flags |= DP_F_UNSIGNED;
339 if (cflags == DP_C_SHORT)
340 value = va_arg (args, unsigned int);
341 else if (cflags == DP_C_LONG)
342 value = (long)va_arg (args, unsigned long int);
343 else if (cflags == DP_C_LLONG)
344 value = (long)va_arg (args, unsigned LLONG);
346 value = (long)va_arg (args, unsigned int);
347 fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
350 flags |= DP_F_UNSIGNED;
351 if (cflags == DP_C_SHORT)
352 value = va_arg (args, unsigned int);
353 else if (cflags == DP_C_LONG)
354 value = (long)va_arg (args, unsigned long int);
355 else if (cflags == DP_C_LLONG)
356 value = (LLONG)va_arg (args, unsigned LLONG);
358 value = (long)va_arg (args, unsigned int);
359 fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
364 flags |= DP_F_UNSIGNED;
365 if (cflags == DP_C_SHORT)
366 value = va_arg (args, unsigned int);
367 else if (cflags == DP_C_LONG)
368 value = (long)va_arg (args, unsigned long int);
369 else if (cflags == DP_C_LLONG)
370 value = (LLONG)va_arg (args, unsigned LLONG);
372 value = (long)va_arg (args, unsigned int);
373 fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
376 if (cflags == DP_C_LDOUBLE)
377 fvalue = va_arg (args, LDOUBLE);
379 fvalue = va_arg (args, double);
380 /* um, floating point? */
381 fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
386 if (cflags == DP_C_LDOUBLE)
387 fvalue = va_arg (args, LDOUBLE);
389 fvalue = va_arg (args, double);
390 fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
395 if (cflags == DP_C_LDOUBLE)
396 fvalue = va_arg (args, LDOUBLE);
398 fvalue = va_arg (args, double);
399 fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
402 dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
405 strvalue = va_arg (args, char *);
406 if (!strvalue) strvalue = "(NULL)";
408 max = strlen(strvalue);
410 if (min > 0 && max >= 0 && min > max) max = min;
411 fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
414 strvalue = va_arg (args, void *);
415 fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min, max, flags);
418 if (cflags == DP_C_SHORT) {
420 num = va_arg (args, short int *);
422 } else if (cflags == DP_C_LONG) {
424 num = va_arg (args, long int *);
425 *num = (long int)currlen;
426 } else if (cflags == DP_C_LLONG) {
428 num = va_arg (args, LLONG *);
429 *num = (LLONG)currlen;
432 num = va_arg (args, int *);
437 dopr_outch (buffer, &currlen, maxlen, ch);
440 /* not supported yet, treat as next char */
448 state = DP_S_DEFAULT;
449 flags = cflags = min = 0;
456 break; /* some picky compilers need this */
460 if (currlen < maxlen - 1)
461 buffer[currlen] = '\0';
463 buffer[maxlen - 1] = '\0';
469 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
470 char *value, int flags, int min, int max)
472 int padlen, strln; /* amount to pad */
475 #ifdef DEBUG_SNPRINTF
476 printf("fmtstr min=%d max=%d s=[%s]\n", min, max, value);
482 for (strln = 0; value[strln]; ++strln); /* strlen */
483 padlen = min - strln;
486 if (flags & DP_F_MINUS)
487 padlen = -padlen; /* Left Justify */
489 while ((padlen > 0) && (cnt < max)) {
490 dopr_outch (buffer, currlen, maxlen, ' ');
494 while (*value && (cnt < max)) {
495 dopr_outch (buffer, currlen, maxlen, *value++);
498 while ((padlen < 0) && (cnt < max)) {
499 dopr_outch (buffer, currlen, maxlen, ' ');
505 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
507 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
508 long value, int base, int min, int max, int flags)
511 unsigned long uvalue;
514 int spadlen = 0; /* amount to space pad */
515 int zpadlen = 0; /* amount to zero pad */
523 if(!(flags & DP_F_UNSIGNED)) {
528 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
530 else if (flags & DP_F_SPACE)
535 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
539 (caps? "0123456789ABCDEF":"0123456789abcdef")
540 [uvalue % (unsigned)base ];
541 uvalue = (uvalue / (unsigned)base );
542 } while(uvalue && (place < 20));
543 if (place == 20) place--;
546 zpadlen = max - place;
547 spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
548 if (zpadlen < 0) zpadlen = 0;
549 if (spadlen < 0) spadlen = 0;
550 if (flags & DP_F_ZERO) {
551 zpadlen = MAX(zpadlen, spadlen);
554 if (flags & DP_F_MINUS)
555 spadlen = -spadlen; /* Left Justifty */
557 #ifdef DEBUG_SNPRINTF
558 printf("zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
559 zpadlen, spadlen, min, max, place);
563 while (spadlen > 0) {
564 dopr_outch (buffer, currlen, maxlen, ' ');
570 dopr_outch (buffer, currlen, maxlen, signvalue);
574 while (zpadlen > 0) {
575 dopr_outch (buffer, currlen, maxlen, '0');
582 dopr_outch (buffer, currlen, maxlen, convert[--place]);
584 /* Left Justified spaces */
585 while (spadlen < 0) {
586 dopr_outch (buffer, currlen, maxlen, ' ');
591 static LDOUBLE abs_val(LDOUBLE value)
593 LDOUBLE result = value;
601 static LDOUBLE POW10(int exp)
613 static LLONG ROUND(LDOUBLE value)
617 intpart = (LLONG)value;
618 value = value - intpart;
619 if (value >= 0.5) intpart++;
624 /* a replacement for modf that doesn't need the math library. Should
625 be portable, but slow */
626 static double my_modf(double x0, double *iptr)
633 for (i=0;i<100;i++) {
635 if (l <= (x+1) && l >= (x-1)) {
640 ret = my_modf(x0-l*f, &i2);
652 /* yikes! the number is beyond what we can handle. What do we do? */
658 static void fmtfp (char *buffer, size_t *currlen, size_t maxlen,
659 LDOUBLE fvalue, int min, int max, int flags)
667 int padlen = 0; /* amount to pad */
676 * AIX manpage says the default is 0, but Solaris says the default
677 * is 6, and sprintf on AIX defaults to 6
682 ufvalue = abs_val (fvalue);
687 if (flags & DP_F_PLUS) { /* Do a sign (+/i) */
690 if (flags & DP_F_SPACE)
696 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
700 if (max == 0) ufvalue += 0.5; /* if max = 0 we must round */
704 * Sorry, we only support 16 digits past the decimal because of our
710 /* We "cheat" by converting the fractional part to integer by
711 * multiplying by a factor of 10
715 my_modf(temp, &intpart);
717 fracpart = ROUND((POW10(max)) * (ufvalue - intpart));
719 if (fracpart >= POW10(max)) {
721 fracpart -= POW10(max);
725 /* Convert integer part */
728 my_modf(temp, &intpart);
729 idx = (int) ((temp -intpart +0.05)* 10.0);
730 /* idx = (int) (((double)(temp*0.1) -intpart +0.05) *10.0); */
731 /* printf ("%llf, %f, %x\n", temp, intpart, idx); */
733 (caps? "0123456789ABCDEF":"0123456789abcdef")[idx];
734 } while (intpart && (iplace < 311));
735 if (iplace == 311) iplace--;
736 iconvert[iplace] = 0;
738 /* Convert fractional part */
743 my_modf(temp, &fracpart);
744 idx = (int) ((temp -fracpart +0.05)* 10.0);
745 /* idx = (int) ((((temp/10) -fracpart) +0.05) *10); */
746 /* printf ("%lf, %lf, %ld\n", temp, fracpart, idx ); */
748 (caps? "0123456789ABCDEF":"0123456789abcdef")[idx];
749 } while(fracpart && (fplace < 311));
750 if (fplace == 311) fplace--;
752 fconvert[fplace] = 0;
754 /* -1 for decimal point, another -1 if we are printing a sign */
755 padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0);
756 zpadlen = max - fplace;
757 if (zpadlen < 0) zpadlen = 0;
760 if (flags & DP_F_MINUS)
761 padlen = -padlen; /* Left Justifty */
763 if ((flags & DP_F_ZERO) && (padlen > 0)) {
765 dopr_outch (buffer, currlen, maxlen, signvalue);
770 dopr_outch (buffer, currlen, maxlen, '0');
775 dopr_outch (buffer, currlen, maxlen, ' ');
779 dopr_outch (buffer, currlen, maxlen, signvalue);
782 dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
784 #ifdef DEBUG_SNPRINTF
785 printf("fmtfp: fplace=%d zpadlen=%d\n", fplace, zpadlen);
789 * Decimal point. This should probably use locale to find the correct
793 dopr_outch (buffer, currlen, maxlen, '.');
795 while (zpadlen > 0) {
796 dopr_outch (buffer, currlen, maxlen, '0');
801 dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
805 dopr_outch (buffer, currlen, maxlen, ' ');
810 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c)
812 if (*currlen < maxlen) {
813 buffer[(*currlen)] = c;
818 int rsync_vsnprintf (char *str, size_t count, const char *fmt, va_list args)
820 return dopr(str, count, fmt, args);
822 #define vsnprintf rsync_vsnprintf
825 /* yes this really must be a ||. Don't muck with this (tridge)
827 * The logic for these two is that we need our own definition if the
828 * OS *either* has no definition of *sprintf, or if it does have one
829 * that doesn't work properly according to the autoconf test.
831 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_C99_VSNPRINTF)
832 int rsync_snprintf(char *str,size_t count,const char *fmt,...)
838 ret = vsnprintf(str, count, fmt, ap);
842 #define snprintf rsync_snprintf
847 #ifndef HAVE_VASPRINTF
848 int vasprintf(char **ptr, const char *format, va_list ap)
855 ret = vsnprintf(NULL, 0, format, ap2);
856 if (ret <= 0) return ret;
858 (*ptr) = (char *)malloc(ret+1);
859 if (!*ptr) return -1;
863 ret = vsnprintf(*ptr, ret+1, format, ap2);
870 #ifndef HAVE_ASPRINTF
871 int asprintf(char **ptr, const char *format, ...)
877 va_start(ap, format);
878 ret = vasprintf(ptr, format, ap);
887 int sprintf(char *str,const char *fmt,...);
911 double fp_nums[] = { 6442452944.1234, -1.5, 134.21, 91340.2, 341.1234, 203.9, 0.96, 0.996,
912 0.9996, 1.996, 4.136, 5.030201, 0.00205,
927 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
941 char *str_vals[] = {"hello", "a", "", "a longer string", NULL};
946 printf ("Testing snprintf format codes against system sprintf...\n");
948 for (x = 0; fp_fmt[x] ; x++) {
949 for (y = 0; fp_nums[y] != 0 ; y++) {
950 int l1 = snprintf(NULL, 0, fp_fmt[x], fp_nums[y]);
951 int l2 = snprintf(buf1, sizeof(buf1), fp_fmt[x], fp_nums[y]);
952 sprintf (buf2, fp_fmt[x], fp_nums[y]);
953 if (strcmp (buf1, buf2)) {
954 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
955 fp_fmt[x], buf1, buf2);
959 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, fp_fmt[x]);
966 for (x = 0; int_fmt[x] ; x++) {
967 for (y = 0; int_nums[y] != 0 ; y++) {
968 int l1 = snprintf(NULL, 0, int_fmt[x], int_nums[y]);
969 int l2 = snprintf(buf1, sizeof(buf1), int_fmt[x], int_nums[y]);
970 sprintf (buf2, int_fmt[x], int_nums[y]);
971 if (strcmp (buf1, buf2)) {
972 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
973 int_fmt[x], buf1, buf2);
977 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, int_fmt[x]);
984 for (x = 0; str_fmt[x] ; x++) {
985 for (y = 0; str_vals[y] != 0 ; y++) {
986 int l1 = snprintf(NULL, 0, str_fmt[x], str_vals[y]);
987 int l2 = snprintf(buf1, sizeof(buf1), str_fmt[x], str_vals[y]);
988 sprintf (buf2, str_fmt[x], str_vals[y]);
989 if (strcmp (buf1, buf2)) {
990 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
991 str_fmt[x], buf1, buf2);
995 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, str_fmt[x]);
1002 printf ("%d tests failed out of %d.\n", fail, num);
1004 printf("seeing how many digits we support\n");
1006 double v0 = 0.12345678901234567890123456789012345678901;
1007 for (x=0; x<100; x++) {
1008 double p = pow(10, x);
1010 snprintf(buf1, sizeof(buf1), "%1.1f", r);
1011 sprintf(buf2, "%1.1f", r);
1012 if (strcmp(buf1, buf2)) {
1013 printf("we seem to support %d digits\n", x-1);
1021 #endif /* TEST_SNPRINTF */