1 /* This file is NOT part of Wget, but is used by Wget on the systems
2 where vsnprintf() is not defined. It has been written by Patrick
3 Powell and modified by other people. All the copyright and other
4 notices have been left intact.
6 My changes are documented at the bottom, along with other changes.
7 I hereby place my modifications to this file under the public
11 * Copyright Patrick Powell 1995
12 * This code is based on code written by Patrick Powell (papowell@astart.com)
13 * It may be used for any purpose as long as this notice remains intact
14 * on all source code distributions
17 /**************************************************************
19 * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
20 * A bombproof version of doprnt (dopr) included.
21 * Sigh. This sort of thing is always nasty do deal with. Note that
22 * the version here does not include floating point...
24 * snprintf() is used instead of sprintf() as it does limit checks
25 * for string length. This covers a nasty loophole.
27 * The other functions are there to prevent NULL pointers from
28 * causing nast effects.
31 * Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43
32 * This was ugly. It is still ugly. I opted out of floating point
33 * numbers, but the formatter understands just about everything
34 * from the normal C string format, at least as far as I can tell from
35 * the Solaris 2.5 printf(3S) man page.
37 * Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1
38 * Ok, added some minimal floating point support, which means this
39 * probably requires libm on most operating systems. Don't yet
40 * support the exponent (e,E) and sigfig (g,G). Also, fmtint()
41 * was pretty badly broken, it just wasn't being exercised in ways
42 * which showed it, so that's been fixed. Also, formated the code
43 * to mutt conventions, and removed dead code left over from the
44 * original. Also, there is now a builtin-test, just compile with:
45 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm
46 * and run snprintf for results.
48 * Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i
49 * The PGP code was using unsigned hexadecimal formats.
50 * Unfortunately, unsigned formats simply didn't work.
52 * Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8
53 * The original code assumed that both snprintf() and vsnprintf() were
54 * missing. Some systems only have snprintf() but not vsnprintf(), so
55 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
57 * Andrew Tridgell (tridge@samba.org) Oct 1998
58 * fixed handling of %.0f
59 * added test for HAVE_LONG_DOUBLE
61 * Russ Allbery <rra@stanford.edu> 2000-08-26
62 * fixed return value to comply with C99
63 * fixed handling of snprintf(NULL, ...)
65 * Hrvoje Niksic <hniksic@xemacs.org> 2000-11-04
66 * include <config.h> instead of "config.h".
67 * moved TEST_SNPRINTF stuff out of HAVE_SNPRINTF ifdef.
68 * include <stdio.h> for NULL.
69 * added support and test cases for long long.
70 * don't declare argument types to (v)snprintf if stdarg is not used.
71 * use int instead of short int as 2nd arg to va_arg.
73 * alexk (INN) 2002-08-21
74 * use LLONG in fmtfp to handle more characters during floating
77 * herb (Samba) 2002-12-19
78 * actually print args for %g and %e
80 * Hrvoje Niksic <hniksic@xemacs.org> 2005-04-15
81 * use the PARAMS macro to handle prototypes.
82 * write function definitions in the ansi2knr-friendly way.
83 * if string precision is specified, don't read VALUE past it.
84 * fix bug in fmtfp that caused 0.01 to be printed as 0.1.
85 * don't include <ctype.h> because none of it is used.
86 * interpret precision as number of significant digits with %g
87 * omit trailing decimal zeros with %g
89 **************************************************************/
95 /* For testing purposes, always compile in the code. */
98 # undef HAVE_VSNPRINTF
99 # ifndef SIZEOF_LONG_LONG
101 # define SIZEOF_LONG_LONG 8
106 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF)
111 # include <strings.h>
113 #include <sys/types.h>
114 #include <stdio.h> /* for NULL */
116 /* varargs declarations: */
118 #if defined(HAVE_STDARG_H)
120 # define HAVE_STDARGS /* let's hope that works everywhere (mj) */
121 # define VA_LOCAL_DECL va_list ap
122 # define VA_START(f) va_start(ap, f)
123 # define VA_SHIFT(v,t) ; /* no-op for ANSI */
124 # define VA_END va_end(ap)
126 # include <varargs.h>
128 # define VA_LOCAL_DECL va_list ap
129 # define VA_START(f) va_start(ap) /* f is ignored! */
130 # define VA_SHIFT(v,t) v = va_arg(ap,t)
131 # define VA_END va_end(ap)
134 #ifdef HAVE_LONG_DOUBLE
135 #define LDOUBLE long double
137 #define LDOUBLE double
140 #if SIZEOF_LONG_LONG != 0
141 # define LLONG long long
146 /* If we're running the test suite, rename snprintf and vsnprintf to
147 avoid conflicts with the system version. */
149 # define snprintf test_snprintf
150 # define vsnprintf test_vsnprintf
154 int snprintf (char *str, size_t count, const char *fmt, ...);
155 int vsnprintf (char *str, size_t count, const char *fmt, va_list arg);
165 static int dopr PARAMS ((char *buffer, size_t maxlen, const char *format,
167 static int fmtstr PARAMS ((char *buffer, size_t *currlen, size_t maxlen,
168 const char *value, int flags, int min, int max));
169 static int fmtint PARAMS ((char *buffer, size_t *currlen, size_t maxlen,
170 LLONG value, int base, int min, int max, int flags));
171 static int fmtfp PARAMS ((char *buffer, size_t *currlen, size_t maxlen,
172 LDOUBLE fvalue, int min, int max, int flags));
173 static int dopr_outch PARAMS ((char *buffer, size_t *currlen, size_t maxlen,
177 * dopr(): poor man's version of doprintf
180 /* format read states */
181 #define DP_S_DEFAULT 0
191 /* format flags - Bits */
192 #define DP_F_MINUS (1 << 0)
193 #define DP_F_PLUS (1 << 1)
194 #define DP_F_SPACE (1 << 2)
195 #define DP_F_NUM (1 << 3)
196 #define DP_F_ZERO (1 << 4)
197 #define DP_F_UP (1 << 5)
198 #define DP_F_UNSIGNED (1 << 6)
199 #define DP_F_FP_G (1 << 7)
201 /* Conversion Flags */
205 #define DP_C_LDOUBLE 4
207 #define char_to_int(p) (p - '0')
208 #define MAX(p,q) ((p >= q) ? p : q)
209 #define MIN(p,q) ((p <= q) ? p : q)
212 dopr (char *buffer, size_t maxlen, const char *format, va_list args)
226 state = DP_S_DEFAULT;
227 currlen = flags = cflags = min = 0;
232 while (state != DP_S_DONE)
243 total += dopr_outch (buffer, &currlen, maxlen, ch);
275 if ('0' <= ch && ch <= '9')
277 min = 10*min + char_to_int (ch);
282 min = va_arg (args, int);
299 if ('0' <= ch && ch <= '9')
303 max = 10*max + char_to_int (ch);
308 max = va_arg (args, int);
327 cflags = DP_C_LDOUBLE;
333 if (cflags != DP_C_LONG)
355 if (cflags == DP_C_SHORT)
356 value = (short int) va_arg (args, int);
357 else if (cflags == DP_C_LONG)
358 value = va_arg (args, long int);
359 else if (cflags == DP_C_LLONG)
360 value = va_arg (args, LLONG);
362 value = va_arg (args, int);
363 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
366 flags |= DP_F_UNSIGNED;
367 if (cflags == DP_C_SHORT)
368 value = (unsigned short int) va_arg (args, unsigned int);
369 else if (cflags == DP_C_LONG)
370 value = va_arg (args, unsigned long int);
371 else if (cflags == DP_C_LLONG)
372 value = va_arg (args, unsigned LLONG);
374 value = va_arg (args, unsigned int);
375 total += fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
378 flags |= DP_F_UNSIGNED;
379 if (cflags == DP_C_SHORT)
380 value = (unsigned short int) va_arg (args, unsigned int);
381 else if (cflags == DP_C_LONG)
382 value = va_arg (args, unsigned long int);
383 else if (cflags == DP_C_LLONG)
384 value = va_arg (args, unsigned LLONG);
386 value = va_arg (args, unsigned int);
387 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
392 flags |= DP_F_UNSIGNED;
393 if (cflags == DP_C_SHORT)
394 value = (unsigned short int) va_arg (args, unsigned int);
395 else if (cflags == DP_C_LONG)
396 value = va_arg (args, unsigned long int);
397 else if (cflags == DP_C_LLONG)
398 value = va_arg (args, unsigned LLONG);
400 value = va_arg (args, unsigned int);
401 total += fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
404 if (cflags == DP_C_LDOUBLE)
405 fvalue = va_arg (args, LDOUBLE);
407 fvalue = va_arg (args, double);
408 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
413 if (cflags == DP_C_LDOUBLE)
414 fvalue = va_arg (args, LDOUBLE);
416 fvalue = va_arg (args, double);
417 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
423 if (cflags == DP_C_LDOUBLE)
424 fvalue = va_arg (args, LDOUBLE);
426 fvalue = va_arg (args, double);
428 /* C99 says: if precision [for %g] is zero, it is taken as one */
430 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
433 total += dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
436 strvalue = va_arg (args, char *);
437 total += fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
440 strvalue = va_arg (args, void *);
441 total += fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min,
445 if (cflags == DP_C_SHORT)
448 num = va_arg (args, short int *);
451 else if (cflags == DP_C_LONG)
454 num = va_arg (args, long int *);
457 else if (cflags == DP_C_LLONG)
460 num = va_arg (args, LLONG *);
466 num = va_arg (args, int *);
471 total += dopr_outch (buffer, &currlen, maxlen, ch);
474 /* not supported yet, treat as next char */
482 state = DP_S_DEFAULT;
483 flags = cflags = min = 0;
490 break; /* some picky compilers need this */
495 if (currlen < maxlen - 1)
496 buffer[currlen] = '\0';
498 buffer[maxlen - 1] = '\0';
504 fmtstr (char *buffer, size_t *currlen, size_t maxlen,
505 const char *value, int flags, int min, int max)
507 int padlen, strln; /* amount to pad */
517 strln = strlen (value);
519 /* When precision is specified, don't read VALUE past precision. */
520 /*strln = strnlen (value, max);*/
521 for (strln = 0; strln < max && value[strln]; ++strln);
522 padlen = min - strln;
525 if (flags & DP_F_MINUS)
526 padlen = -padlen; /* Left Justify */
530 total += dopr_outch (buffer, currlen, maxlen, ' ');
533 while (*value && ((max < 0) || (cnt < max)))
535 total += dopr_outch (buffer, currlen, maxlen, *value++);
540 total += dopr_outch (buffer, currlen, maxlen, ' ');
546 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
549 fmtint (char *buffer, size_t *currlen, size_t maxlen,
550 LLONG value, int base, int min, int max, int flags)
553 unsigned LLONG uvalue;
556 int spadlen = 0; /* amount to space pad */
557 int zpadlen = 0; /* amount to zero pad */
566 if(!(flags & DP_F_UNSIGNED))
573 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
576 if (flags & DP_F_SPACE)
581 /* Should characters be upper case? */
582 digits = "0123456789ABCDEF";
584 digits = "0123456789abcdef";
587 convert[place++] = digits[uvalue % (unsigned)base];
588 uvalue = (uvalue / (unsigned)base );
589 } while(uvalue && (place < sizeof (convert)));
590 if (place == sizeof (convert)) place--;
593 zpadlen = max - place;
594 spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
595 if (zpadlen < 0) zpadlen = 0;
596 if (spadlen < 0) spadlen = 0;
597 if (flags & DP_F_ZERO)
599 zpadlen = MAX(zpadlen, spadlen);
602 if (flags & DP_F_MINUS)
603 spadlen = -spadlen; /* Left Justifty */
605 #ifdef DEBUG_SNPRINTF
606 dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
607 zpadlen, spadlen, min, max, place));
613 total += dopr_outch (buffer, currlen, maxlen, ' ');
619 total += dopr_outch (buffer, currlen, maxlen, signvalue);
626 total += dopr_outch (buffer, currlen, maxlen, '0');
633 total += dopr_outch (buffer, currlen, maxlen, convert[--place]);
635 /* Left Justified spaces */
636 while (spadlen < 0) {
637 total += dopr_outch (buffer, currlen, maxlen, ' ');
645 abs_val (LDOUBLE value)
647 LDOUBLE result = value;
670 round (LDOUBLE value)
675 value = value - intpart;
683 fmtfp (char *buffer, size_t *currlen, size_t maxlen,
684 LDOUBLE fvalue, int min, int max, int flags)
692 int padlen = 0; /* amount to pad */
698 int leadingfrac0s = 0; /* zeros at the start of fractional part */
703 * AIX manpage says the default is 0, but Solaris says the default
704 * is 6, and sprintf on AIX defaults to 6
709 ufvalue = abs_val (fvalue);
714 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
717 if (flags & DP_F_SPACE)
721 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
726 /* With %g precision is the number of significant digits, which
727 includes the digits in intpart. */
728 if (flags & DP_F_FP_G)
732 /* For each digit of INTPART, print one less fractional digit. */
733 LLONG temp = intpart;
734 for (temp = intpart; temp != 0; temp /= 10)
741 /* For each leading 0 in fractional part, print one more
745 for (temp = ufvalue; temp < 0.1; temp *= 10)
750 /* C99: trailing zeros are removed from the fractional portion of the
751 result unless the # flag is specified */
752 if ((flags & DP_F_FP_G) && !(flags & DP_F_NUM))
755 #if SIZEOF_LONG_LONG > 0
756 # define MAX_DIGITS 18 /* grok more digits with long long */
758 # define MAX_DIGITS 9 /* just long */
762 * Sorry, we only support several digits past the decimal because of
763 * our conversion method
765 if (max > MAX_DIGITS)
768 /* Factor of 10 with the needed number of digits, e.g. 1000 for max==3 */
769 mask10 = pow10 (max);
771 /* We "cheat" by converting the fractional part to integer by
772 * multiplying by a factor of 10
774 fracpart = round (mask10 * (ufvalue - intpart));
776 if (fracpart >= mask10)
781 else if (fracpart != 0)
782 /* If fracpart has less digits than the 10* mask, we need to
783 manually insert leading 0s. For example 2.01's fractional part
784 requires one leading zero to distinguish it from 2.1. */
785 while (fracpart < mask10 / 10)
791 #ifdef DEBUG_SNPRINTF
792 dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart));
795 /* Convert integer part */
797 iconvert[iplace++] = '0' + intpart % 10;
798 intpart = (intpart / 10);
799 } while(intpart && (iplace < sizeof(iconvert)));
800 if (iplace == sizeof(iconvert)) iplace--;
801 iconvert[iplace] = 0;
803 /* Convert fractional part */
805 fconvert[fplace++] = '0' + fracpart % 10;
806 fracpart = (fracpart / 10);
807 } while(fracpart && (fplace < sizeof(fconvert)));
808 while (leadingfrac0s-- > 0 && fplace < sizeof(fconvert))
809 fconvert[fplace++] = '0';
810 if (fplace == sizeof(fconvert)) fplace--;
811 fconvert[fplace] = 0;
813 while (omitcount < fplace && fconvert[omitcount] == '0')
816 /* -1 for decimal point, another -1 if we are printing a sign */
817 padlen = min - iplace - (max - omitcount) - 1 - ((signvalue) ? 1 : 0);
819 zpadlen = max - fplace;
824 if (flags & DP_F_MINUS)
825 padlen = -padlen; /* Left Justifty */
827 if ((flags & DP_F_ZERO) && (padlen > 0))
831 total += dopr_outch (buffer, currlen, maxlen, signvalue);
837 total += dopr_outch (buffer, currlen, maxlen, '0');
843 total += dopr_outch (buffer, currlen, maxlen, ' ');
847 total += dopr_outch (buffer, currlen, maxlen, signvalue);
850 total += dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
853 * Decimal point. This should probably use locale to find the correct
856 if (max > 0 && (fplace > omitcount || zpadlen > 0))
858 total += dopr_outch (buffer, currlen, maxlen, '.');
860 while (fplace > omitcount)
861 total += dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
866 total += dopr_outch (buffer, currlen, maxlen, '0');
872 total += dopr_outch (buffer, currlen, maxlen, ' ');
880 dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c)
882 if (*currlen + 1 < maxlen)
883 buffer[(*currlen)++] = c;
887 #ifndef HAVE_VSNPRINTF
889 vsnprintf (char *str, size_t count, const char *fmt, va_list args)
893 return dopr(str, count, fmt, args);
895 #endif /* !HAVE_VSNPRINTF */
897 #ifndef HAVE_SNPRINTF
899 snprintf (char *str, size_t count,const char *fmt,...)
910 VA_SHIFT (str, char *);
911 VA_SHIFT (count, size_t );
912 VA_SHIFT (fmt, char *);
913 total = vsnprintf(str, count, fmt, ap);
917 #endif /* !HAVE_SNPRINTF */
918 #endif /* !HAVE_SNPRINTF || !HAVE_VSNPRINTF */
923 # define LONG_STRING 1024
929 char buf1[LONG_STRING];
930 char buf2[LONG_STRING];
948 #if SIZEOF_LONG_LONG != 0
960 #if SIZEOF_LONG_LONG != 0
966 double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
967 0.9996, 1.996, 4.136, 0.00205, 0.0001, 321.000009,
981 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
982 #if SIZEOF_LONG_LONG != 0
983 char *llong_fmt[] = {
985 "%-1.5lld", "%-1.5llu",
986 "%1.5lld", "%1.5llu",
987 "%123.9lld", "%123.9llu",
988 "%5.5lld", "%5.5llu",
989 "%10.5lld", "%10.5llu",
990 "% 10.5lld", "% 10.5llu",
991 "%+22.33lld", "%+22.33llu",
992 "%01.3lld", "%01.3llu",
996 long long llong_nums[] = {
997 ~(long long)0, /* all-1 bit pattern */
998 (~(unsigned long long)0) >> 1, /* largest signed long long */
1000 -150, 134, 91340, 341,
1008 printf ("Testing snprintf format codes against system sprintf...\n");
1010 for (x = 0; fp_fmt[x] != NULL ; x++)
1011 for (y = 0; fp_nums[y] != 0 ; y++)
1013 snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]);
1014 sprintf (buf2, fp_fmt[x], fp_nums[y]);
1015 if (strcmp (buf1, buf2))
1017 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
1018 fp_fmt[x], buf1, buf2);
1024 for (x = 0; int_fmt[x] != NULL ; x++)
1025 for (y = 0; int_nums[y] != 0 ; y++)
1027 snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]);
1028 sprintf (buf2, int_fmt[x], int_nums[y]);
1029 if (strcmp (buf1, buf2))
1031 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
1032 int_fmt[x], buf1, buf2);
1038 #if SIZEOF_LONG_LONG != 0
1039 for (x = 0; llong_fmt[x] != NULL ; x++)
1040 for (y = 0; llong_nums[y] != 0 ; y++)
1042 snprintf (buf1, sizeof (buf1), llong_fmt[x], llong_nums[y]);
1043 sprintf (buf2, llong_fmt[x], llong_nums[y]);
1044 if (strcmp (buf1, buf2))
1046 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
1047 llong_fmt[x], buf1, buf2);
1054 printf ("%d tests failed out of %d.\n", fail, num);
1057 #endif /* TEST_SNPRINTF */