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
142 #ifdef HAVE_LONG_LONG
143 #define LLONG long long
150 #define VA_COPY(dest, src) __va_copy(dest, src)
152 #define VA_COPY(dest, src) (dest) = (src)
156 * dopr(): poor man's version of doprintf
159 /* format read states */
160 #define DP_S_DEFAULT 0
169 /* format flags - Bits */
170 #define DP_F_MINUS (1 << 0)
171 #define DP_F_PLUS (1 << 1)
172 #define DP_F_SPACE (1 << 2)
173 #define DP_F_NUM (1 << 3)
174 #define DP_F_ZERO (1 << 4)
175 #define DP_F_UP (1 << 5)
176 #define DP_F_UNSIGNED (1 << 6)
178 /* Conversion Flags */
181 #define DP_C_LDOUBLE 3
184 #define char_to_int(p) ((p)- '0')
186 #define MAX(p,q) (((p) >= (q)) ? (p) : (q))
189 /* yes this really must be a ||. Don't muck with this (tridge) */
190 #if !defined(HAVE_VSNPRINTF) || !defined(HAVE_C99_VSNPRINTF)
192 static size_t dopr(char *buffer
, size_t maxlen
, const char *format
,
194 static void fmtstr(char *buffer
, size_t *currlen
, size_t maxlen
,
195 char *value
, int flags
, int min
, int max
);
196 static void fmtint(char *buffer
, size_t *currlen
, size_t maxlen
,
197 long value
, int base
, int min
, int max
, int flags
);
198 static void fmtfp(char *buffer
, size_t *currlen
, size_t maxlen
,
199 LDOUBLE fvalue
, int min
, int max
, int flags
);
200 static void dopr_outch(char *buffer
, size_t *currlen
, size_t maxlen
, char c
);
202 static size_t dopr(char *buffer
, size_t maxlen
, const char *format
, va_list args_in
)
216 VA_COPY(args
, args_in
);
218 state
= DP_S_DEFAULT
;
219 currlen
= flags
= cflags
= min
= 0;
223 while (state
!= DP_S_DONE
) {
232 dopr_outch (buffer
, &currlen
, maxlen
, ch
);
263 if (isdigit((unsigned char)ch
)) {
264 min
= 10*min
+ char_to_int (ch
);
266 } else if (ch
== '*') {
267 min
= va_arg (args
, int);
283 if (isdigit((unsigned char)ch
)) {
286 max
= 10*max
+ char_to_int (ch
);
288 } else if (ch
== '*') {
289 max
= va_arg (args
, int);
305 if (ch
== 'l') { /* It's a long long */
311 cflags
= DP_C_LDOUBLE
;
323 if (cflags
== DP_C_SHORT
)
324 value
= va_arg (args
, int);
325 else if (cflags
== DP_C_LONG
)
326 value
= va_arg (args
, long int);
327 else if (cflags
== DP_C_LLONG
)
328 value
= va_arg (args
, LLONG
);
330 value
= va_arg (args
, int);
331 fmtint (buffer
, &currlen
, maxlen
, value
, 10, min
, max
, flags
);
334 flags
|= DP_F_UNSIGNED
;
335 if (cflags
== DP_C_SHORT
)
336 value
= va_arg (args
, unsigned int);
337 else if (cflags
== DP_C_LONG
)
338 value
= (long)va_arg (args
, unsigned long int);
339 else if (cflags
== DP_C_LLONG
)
340 value
= (long)va_arg (args
, unsigned LLONG
);
342 value
= (long)va_arg (args
, unsigned int);
343 fmtint (buffer
, &currlen
, maxlen
, value
, 8, min
, max
, flags
);
346 flags
|= DP_F_UNSIGNED
;
347 if (cflags
== DP_C_SHORT
)
348 value
= va_arg (args
, unsigned int);
349 else if (cflags
== DP_C_LONG
)
350 value
= (long)va_arg (args
, unsigned long int);
351 else if (cflags
== DP_C_LLONG
)
352 value
= (LLONG
)va_arg (args
, unsigned LLONG
);
354 value
= (long)va_arg (args
, unsigned int);
355 fmtint (buffer
, &currlen
, maxlen
, value
, 10, min
, max
, flags
);
360 flags
|= DP_F_UNSIGNED
;
361 if (cflags
== DP_C_SHORT
)
362 value
= va_arg (args
, unsigned int);
363 else if (cflags
== DP_C_LONG
)
364 value
= (long)va_arg (args
, unsigned long int);
365 else if (cflags
== DP_C_LLONG
)
366 value
= (LLONG
)va_arg (args
, unsigned LLONG
);
368 value
= (long)va_arg (args
, unsigned int);
369 fmtint (buffer
, &currlen
, maxlen
, value
, 16, min
, max
, flags
);
372 if (cflags
== DP_C_LDOUBLE
)
373 fvalue
= va_arg (args
, LDOUBLE
);
375 fvalue
= va_arg (args
, double);
376 /* um, floating point? */
377 fmtfp (buffer
, &currlen
, maxlen
, fvalue
, min
, max
, flags
);
382 if (cflags
== DP_C_LDOUBLE
)
383 fvalue
= va_arg (args
, LDOUBLE
);
385 fvalue
= va_arg (args
, double);
386 fmtfp (buffer
, &currlen
, maxlen
, fvalue
, min
, max
, flags
);
391 if (cflags
== DP_C_LDOUBLE
)
392 fvalue
= va_arg (args
, LDOUBLE
);
394 fvalue
= va_arg (args
, double);
395 fmtfp (buffer
, &currlen
, maxlen
, fvalue
, min
, max
, flags
);
398 dopr_outch (buffer
, &currlen
, maxlen
, va_arg (args
, int));
401 strvalue
= va_arg (args
, char *);
402 if (!strvalue
) strvalue
= "(NULL)";
404 max
= strlen(strvalue
);
406 if (min
> 0 && max
>= 0 && min
> max
) max
= min
;
407 fmtstr (buffer
, &currlen
, maxlen
, strvalue
, flags
, min
, max
);
410 strvalue
= va_arg (args
, void *);
411 fmtint (buffer
, &currlen
, maxlen
, (long) strvalue
, 16, min
, max
, flags
);
414 if (cflags
== DP_C_SHORT
) {
416 num
= va_arg (args
, short int *);
418 } else if (cflags
== DP_C_LONG
) {
420 num
= va_arg (args
, long int *);
421 *num
= (long int)currlen
;
422 } else if (cflags
== DP_C_LLONG
) {
424 num
= va_arg (args
, LLONG
*);
425 *num
= (LLONG
)currlen
;
428 num
= va_arg (args
, int *);
433 dopr_outch (buffer
, &currlen
, maxlen
, ch
);
436 /* not supported yet, treat as next char */
444 state
= DP_S_DEFAULT
;
445 flags
= cflags
= min
= 0;
452 break; /* some picky compilers need this */
456 if (currlen
< maxlen
- 1)
457 buffer
[currlen
] = '\0';
459 buffer
[maxlen
- 1] = '\0';
465 static void fmtstr(char *buffer
, size_t *currlen
, size_t maxlen
,
466 char *value
, int flags
, int min
, int max
)
468 int padlen
, strln
; /* amount to pad */
471 #ifdef DEBUG_SNPRINTF
472 printf("fmtstr min=%d max=%d s=[%s]\n", min
, max
, value
);
478 for (strln
= 0; value
[strln
]; ++strln
); /* strlen */
479 padlen
= min
- strln
;
482 if (flags
& DP_F_MINUS
)
483 padlen
= -padlen
; /* Left Justify */
485 while ((padlen
> 0) && (cnt
< max
)) {
486 dopr_outch (buffer
, currlen
, maxlen
, ' ');
490 while (*value
&& (cnt
< max
)) {
491 dopr_outch (buffer
, currlen
, maxlen
, *value
++);
494 while ((padlen
< 0) && (cnt
< max
)) {
495 dopr_outch (buffer
, currlen
, maxlen
, ' ');
501 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
503 static void fmtint(char *buffer
, size_t *currlen
, size_t maxlen
,
504 long value
, int base
, int min
, int max
, int flags
)
507 unsigned long uvalue
;
510 int spadlen
= 0; /* amount to space pad */
511 int zpadlen
= 0; /* amount to zero pad */
519 if(!(flags
& DP_F_UNSIGNED
)) {
524 if (flags
& DP_F_PLUS
) /* Do a sign (+/i) */
526 else if (flags
& DP_F_SPACE
)
531 if (flags
& DP_F_UP
) caps
= 1; /* Should characters be upper case? */
535 (caps
? "0123456789ABCDEF":"0123456789abcdef")
536 [uvalue
% (unsigned)base
];
537 uvalue
= (uvalue
/ (unsigned)base
);
538 } while(uvalue
&& (place
< 20));
539 if (place
== 20) place
--;
542 zpadlen
= max
- place
;
543 spadlen
= min
- MAX (max
, place
) - (signvalue
? 1 : 0);
544 if (zpadlen
< 0) zpadlen
= 0;
545 if (spadlen
< 0) spadlen
= 0;
546 if (flags
& DP_F_ZERO
) {
547 zpadlen
= MAX(zpadlen
, spadlen
);
550 if (flags
& DP_F_MINUS
)
551 spadlen
= -spadlen
; /* Left Justifty */
553 #ifdef DEBUG_SNPRINTF
554 printf("zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
555 zpadlen
, spadlen
, min
, max
, place
);
559 while (spadlen
> 0) {
560 dopr_outch (buffer
, currlen
, maxlen
, ' ');
566 dopr_outch (buffer
, currlen
, maxlen
, signvalue
);
570 while (zpadlen
> 0) {
571 dopr_outch (buffer
, currlen
, maxlen
, '0');
578 dopr_outch (buffer
, currlen
, maxlen
, convert
[--place
]);
580 /* Left Justified spaces */
581 while (spadlen
< 0) {
582 dopr_outch (buffer
, currlen
, maxlen
, ' ');
587 static LDOUBLE
abs_val(LDOUBLE value
)
589 LDOUBLE result
= value
;
597 static LDOUBLE
POW10(int exp
)
609 static LLONG
ROUND(LDOUBLE value
)
613 intpart
= (LLONG
)value
;
614 value
= value
- intpart
;
615 if (value
>= 0.5) intpart
++;
620 /* a replacement for modf that doesn't need the math library. Should
621 be portable, but slow */
622 static double my_modf(double x0
, double *iptr
)
629 for (i
=0;i
<100;i
++) {
631 if (l
<= (x
+1) && l
>= (x
-1)) break;
637 /* yikes! the number is beyond what we can handle. What do we do? */
646 ret
= my_modf(x0
-l
*f
, &i2
);
656 static void fmtfp (char *buffer
, size_t *currlen
, size_t maxlen
,
657 LDOUBLE fvalue
, int min
, int max
, int flags
)
665 int padlen
= 0; /* amount to pad */
674 * AIX manpage says the default is 0, but Solaris says the default
675 * is 6, and sprintf on AIX defaults to 6
680 ufvalue
= abs_val (fvalue
);
685 if (flags
& DP_F_PLUS
) { /* Do a sign (+/i) */
688 if (flags
& DP_F_SPACE
)
694 if (flags
& DP_F_UP
) caps
= 1; /* Should characters be upper case? */
698 if (max
== 0) ufvalue
+= 0.5; /* if max = 0 we must round */
702 * Sorry, we only support 16 digits past the decimal because of our
708 /* We "cheat" by converting the fractional part to integer by
709 * multiplying by a factor of 10
713 my_modf(temp
, &intpart
);
715 fracpart
= ROUND((POW10(max
)) * (ufvalue
- intpart
));
717 if (fracpart
>= POW10(max
)) {
719 fracpart
-= POW10(max
);
723 /* Convert integer part */
726 my_modf(temp
, &intpart
);
727 idx
= (int) ((temp
-intpart
+0.05)* 10.0);
728 /* idx = (int) (((double)(temp*0.1) -intpart +0.05) *10.0); */
729 /* printf ("%llf, %f, %x\n", temp, intpart, idx); */
731 (caps
? "0123456789ABCDEF":"0123456789abcdef")[idx
];
732 } while (intpart
&& (iplace
< 311));
733 if (iplace
== 311) iplace
--;
734 iconvert
[iplace
] = 0;
736 /* Convert fractional part */
741 my_modf(temp
, &fracpart
);
742 idx
= (int) ((temp
-fracpart
+0.05)* 10.0);
743 /* idx = (int) ((((temp/10) -fracpart) +0.05) *10); */
744 /* printf ("%lf, %lf, %ld\n", temp, fracpart, idx ); */
746 (caps
? "0123456789ABCDEF":"0123456789abcdef")[idx
];
747 } while(fracpart
&& (fplace
< 311));
748 if (fplace
== 311) fplace
--;
750 fconvert
[fplace
] = 0;
752 /* -1 for decimal point, another -1 if we are printing a sign */
753 padlen
= min
- iplace
- max
- 1 - ((signvalue
) ? 1 : 0);
754 zpadlen
= max
- fplace
;
755 if (zpadlen
< 0) zpadlen
= 0;
758 if (flags
& DP_F_MINUS
)
759 padlen
= -padlen
; /* Left Justifty */
761 if ((flags
& DP_F_ZERO
) && (padlen
> 0)) {
763 dopr_outch (buffer
, currlen
, maxlen
, signvalue
);
768 dopr_outch (buffer
, currlen
, maxlen
, '0');
773 dopr_outch (buffer
, currlen
, maxlen
, ' ');
777 dopr_outch (buffer
, currlen
, maxlen
, signvalue
);
780 dopr_outch (buffer
, currlen
, maxlen
, iconvert
[--iplace
]);
782 #ifdef DEBUG_SNPRINTF
783 printf("fmtfp: fplace=%d zpadlen=%d\n", fplace
, zpadlen
);
787 * Decimal point. This should probably use locale to find the correct
791 dopr_outch (buffer
, currlen
, maxlen
, '.');
793 while (zpadlen
> 0) {
794 dopr_outch (buffer
, currlen
, maxlen
, '0');
799 dopr_outch (buffer
, currlen
, maxlen
, fconvert
[--fplace
]);
803 dopr_outch (buffer
, currlen
, maxlen
, ' ');
808 static void dopr_outch(char *buffer
, size_t *currlen
, size_t maxlen
, char c
)
810 if (*currlen
< maxlen
) {
811 buffer
[(*currlen
)] = c
;
816 int vsnprintf (char *str
, size_t count
, const char *fmt
, va_list args
)
818 return dopr(str
, count
, fmt
, args
);
822 /* yes this really must be a ||. Don't muck with this (tridge)
824 * The logic for these two is that we need our own definition if the
825 * OS *either* has no definition of *sprintf, or if it does have one
826 * that doesn't work properly according to the autoconf test. Perhaps
827 * these should really be smb_snprintf to avoid conflicts with buggy
830 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_C99_VSNPRINTF)
831 int snprintf(char *str
,size_t count
,const char *fmt
,...)
837 ret
= vsnprintf(str
, count
, fmt
, ap
);
845 #ifndef HAVE_VASPRINTF
846 int vasprintf(char **ptr
, const char *format
, va_list ap
)
853 ret
= vsnprintf(NULL
, 0, format
, ap2
);
854 if (ret
<= 0) return ret
;
856 (*ptr
) = (char *)malloc(ret
+1);
857 if (!*ptr
) return -1;
861 ret
= vsnprintf(*ptr
, ret
+1, format
, ap2
);
868 #ifndef HAVE_ASPRINTF
869 int asprintf(char **ptr
, const char *format
, ...)
875 va_start(ap
, format
);
876 ret
= vasprintf(ptr
, format
, ap
);
885 int sprintf(char *str
,const char *fmt
,...);
909 double fp_nums
[] = { 6442452944.1234, -1.5, 134.21, 91340.2, 341.1234, 203.9, 0.96, 0.996,
910 0.9996, 1.996, 4.136, 5.030201, 0.00205,
925 long int_nums
[] = { -1, 134, 91340, 341, 0203, 0};
939 char *str_vals
[] = {"hello", "a", "", "a longer string", NULL
};
944 printf ("Testing snprintf format codes against system sprintf...\n");
946 for (x
= 0; fp_fmt
[x
] ; x
++) {
947 for (y
= 0; fp_nums
[y
] != 0 ; y
++) {
948 int l1
= snprintf(NULL
, 0, fp_fmt
[x
], fp_nums
[y
]);
949 int l2
= snprintf(buf1
, sizeof(buf1
), fp_fmt
[x
], fp_nums
[y
]);
950 sprintf (buf2
, fp_fmt
[x
], fp_nums
[y
]);
951 if (strcmp (buf1
, buf2
)) {
952 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
953 fp_fmt
[x
], buf1
, buf2
);
957 printf("snprintf l1 != l2 (%d %d) %s\n", l1
, l2
, fp_fmt
[x
]);
964 for (x
= 0; int_fmt
[x
] ; x
++) {
965 for (y
= 0; int_nums
[y
] != 0 ; y
++) {
966 int l1
= snprintf(NULL
, 0, int_fmt
[x
], int_nums
[y
]);
967 int l2
= snprintf(buf1
, sizeof(buf1
), int_fmt
[x
], int_nums
[y
]);
968 sprintf (buf2
, int_fmt
[x
], int_nums
[y
]);
969 if (strcmp (buf1
, buf2
)) {
970 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
971 int_fmt
[x
], buf1
, buf2
);
975 printf("snprintf l1 != l2 (%d %d) %s\n", l1
, l2
, int_fmt
[x
]);
982 for (x
= 0; str_fmt
[x
] ; x
++) {
983 for (y
= 0; str_vals
[y
] != 0 ; y
++) {
984 int l1
= snprintf(NULL
, 0, str_fmt
[x
], str_vals
[y
]);
985 int l2
= snprintf(buf1
, sizeof(buf1
), str_fmt
[x
], str_vals
[y
]);
986 sprintf (buf2
, str_fmt
[x
], str_vals
[y
]);
987 if (strcmp (buf1
, buf2
)) {
988 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n",
989 str_fmt
[x
], buf1
, buf2
);
993 printf("snprintf l1 != l2 (%d %d) %s\n", l1
, l2
, str_fmt
[x
]);
1000 printf ("%d tests failed out of %d.\n", fail
, num
);
1002 printf("seeing how many digits we support\n");
1004 double v0
= 0.12345678901234567890123456789012345678901;
1005 for (x
=0; x
<100; x
++) {
1006 double p
= pow(10, x
);
1008 snprintf(buf1
, sizeof(buf1
), "%1.1f", r
);
1009 sprintf(buf2
, "%1.1f", r
);
1010 if (strcmp(buf1
, buf2
)) {
1011 printf("we seem to support %d digits\n", x
-1);
1019 #endif /* TEST_SNPRINTF */