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 * write function definitions in the ansi2knr-friendly way.
82 * if string precision is specified, don't read VALUE past it.
83 * fix bug in fmtfp that caused 0.01 to be printed as 0.1.
84 * don't include <ctype.h> because none of it is used.
85 * interpret precision as number of significant digits with %g
86 * omit trailing decimal zeros with %g
88 **************************************************************/
92 /* For testing purposes, always compile in the code. */
95 # undef HAVE_VSNPRINTF
96 # ifndef SIZEOF_LONG_LONG
98 # define SIZEOF_LONG_LONG 8
103 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF)
106 #include <sys/types.h>
107 #include <stdio.h> /* for NULL */
111 #ifdef HAVE_LONG_DOUBLE
112 #define LDOUBLE long double
114 #define LDOUBLE double
117 #if SIZEOF_LONG_LONG != 0
118 # define LLONG long long
123 /* If we're running the test suite, rename snprintf and vsnprintf to
124 avoid conflicts with the system version. */
126 # define snprintf test_snprintf
127 # define vsnprintf test_vsnprintf
130 int snprintf (char *str, size_t count, const char *fmt, ...);
131 int vsnprintf (char *str, size_t count, const char *fmt, va_list arg);
133 static int dopr (char *buffer, size_t maxlen, const char *format,
135 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
136 const char *value, int flags, int min, int max);
137 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
138 LLONG value, int base, int min, int max, int flags);
139 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
140 LDOUBLE fvalue, int min, int max, int flags);
141 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c);
144 * dopr(): poor man's version of doprintf
147 /* format read states */
148 #define DP_S_DEFAULT 0
158 /* format flags - Bits */
159 #define DP_F_MINUS (1 << 0)
160 #define DP_F_PLUS (1 << 1)
161 #define DP_F_SPACE (1 << 2)
162 #define DP_F_NUM (1 << 3)
163 #define DP_F_ZERO (1 << 4)
164 #define DP_F_UP (1 << 5)
165 #define DP_F_UNSIGNED (1 << 6)
166 #define DP_F_FP_G (1 << 7)
168 /* Conversion Flags */
172 #define DP_C_LDOUBLE 4
174 #define char_to_int(p) (p - '0')
175 #define MAX(p,q) ((p >= q) ? p : q)
176 #define MIN(p,q) ((p <= q) ? p : q)
178 static int dopr (char *buffer, size_t maxlen, const char *format, va_list args)
192 state = DP_S_DEFAULT;
193 currlen = flags = cflags = min = 0;
198 while (state != DP_S_DONE)
209 total += dopr_outch (buffer, &currlen, maxlen, ch);
241 if ('0' <= ch && ch <= '9')
243 min = 10*min + char_to_int (ch);
248 min = va_arg (args, int);
265 if ('0' <= ch && ch <= '9')
269 max = 10*max + char_to_int (ch);
274 max = va_arg (args, int);
293 cflags = DP_C_LDOUBLE;
299 if (cflags != DP_C_LONG)
321 if (cflags == DP_C_SHORT)
322 value = (short int) va_arg (args, int);
323 else if (cflags == DP_C_LONG)
324 value = va_arg (args, long int);
325 else if (cflags == DP_C_LLONG)
326 value = va_arg (args, LLONG);
328 value = va_arg (args, int);
329 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
332 flags |= DP_F_UNSIGNED;
333 if (cflags == DP_C_SHORT)
334 value = (unsigned short int) va_arg (args, unsigned int);
335 else if (cflags == DP_C_LONG)
336 value = va_arg (args, unsigned long int);
337 else if (cflags == DP_C_LLONG)
338 value = va_arg (args, unsigned LLONG);
340 value = va_arg (args, unsigned int);
341 total += fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
344 flags |= DP_F_UNSIGNED;
345 if (cflags == DP_C_SHORT)
346 value = (unsigned short int) va_arg (args, unsigned int);
347 else if (cflags == DP_C_LONG)
348 value = va_arg (args, unsigned long int);
349 else if (cflags == DP_C_LLONG)
350 value = va_arg (args, unsigned LLONG);
352 value = va_arg (args, unsigned int);
353 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
358 flags |= DP_F_UNSIGNED;
359 if (cflags == DP_C_SHORT)
360 value = (unsigned short int) va_arg (args, unsigned int);
361 else if (cflags == DP_C_LONG)
362 value = va_arg (args, unsigned long int);
363 else if (cflags == DP_C_LLONG)
364 value = va_arg (args, unsigned LLONG);
366 value = va_arg (args, unsigned int);
367 total += fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
370 if (cflags == DP_C_LDOUBLE)
371 fvalue = va_arg (args, LDOUBLE);
373 fvalue = va_arg (args, double);
374 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
379 if (cflags == DP_C_LDOUBLE)
380 fvalue = va_arg (args, LDOUBLE);
382 fvalue = va_arg (args, double);
383 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
389 if (cflags == DP_C_LDOUBLE)
390 fvalue = va_arg (args, LDOUBLE);
392 fvalue = va_arg (args, double);
394 /* C99 says: if precision [for %g] is zero, it is taken as one */
396 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
399 total += dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
402 strvalue = va_arg (args, char *);
403 total += fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
406 strvalue = va_arg (args, void *);
407 total += fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min,
411 if (cflags == DP_C_SHORT)
414 num = va_arg (args, short int *);
417 else if (cflags == DP_C_LONG)
420 num = va_arg (args, long int *);
423 else if (cflags == DP_C_LLONG)
426 num = va_arg (args, LLONG *);
432 num = va_arg (args, int *);
437 total += 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 */
461 if (currlen < maxlen - 1)
462 buffer[currlen] = '\0';
464 buffer[maxlen - 1] = '\0';
469 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
470 const char *value, int flags, int min, int max)
472 int padlen, strln; /* amount to pad */
482 strln = strlen (value);
484 /* When precision is specified, don't read VALUE past precision. */
485 /*strln = strnlen (value, max);*/
486 for (strln = 0; strln < max && value[strln]; ++strln)
488 padlen = min - strln;
491 if (flags & DP_F_MINUS)
492 padlen = -padlen; /* Left Justify */
496 total += dopr_outch (buffer, currlen, maxlen, ' ');
499 while (*value && ((max < 0) || (cnt < max)))
501 total += dopr_outch (buffer, currlen, maxlen, *value++);
506 total += dopr_outch (buffer, currlen, maxlen, ' ');
512 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
514 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
515 LLONG value, int base, int min, int max, int flags)
518 unsigned LLONG uvalue;
521 int spadlen = 0; /* amount to space pad */
522 int zpadlen = 0; /* amount to zero pad */
531 if(!(flags & DP_F_UNSIGNED))
538 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
541 if (flags & DP_F_SPACE)
546 /* Should characters be upper case? */
547 digits = "0123456789ABCDEF";
549 digits = "0123456789abcdef";
552 convert[place++] = digits[uvalue % (unsigned)base];
553 uvalue = (uvalue / (unsigned)base );
554 } while(uvalue && (place < sizeof (convert)));
555 if (place == sizeof (convert)) place--;
558 zpadlen = max - place;
559 spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
560 if (zpadlen < 0) zpadlen = 0;
561 if (spadlen < 0) spadlen = 0;
562 if (flags & DP_F_ZERO)
564 zpadlen = MAX(zpadlen, spadlen);
567 if (flags & DP_F_MINUS)
568 spadlen = -spadlen; /* Left Justifty */
570 #ifdef DEBUG_SNPRINTF
571 dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
572 zpadlen, spadlen, min, max, place));
578 total += dopr_outch (buffer, currlen, maxlen, ' ');
584 total += dopr_outch (buffer, currlen, maxlen, signvalue);
591 total += dopr_outch (buffer, currlen, maxlen, '0');
598 total += dopr_outch (buffer, currlen, maxlen, convert[--place]);
600 /* Left Justified spaces */
601 while (spadlen < 0) {
602 total += dopr_outch (buffer, currlen, maxlen, ' ');
609 static LDOUBLE abs_val (LDOUBLE value)
611 LDOUBLE result = value;
619 static LDOUBLE pow10_int (int exp)
632 static LLONG round_int (LDOUBLE value)
637 value = value - intpart;
644 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
645 LDOUBLE fvalue, int min, int max, int flags)
653 int padlen = 0; /* amount to pad */
659 int leadingfrac0s = 0; /* zeros at the start of fractional part */
664 * AIX manpage says the default is 0, but Solaris says the default
665 * is 6, and sprintf on AIX defaults to 6
670 ufvalue = abs_val (fvalue);
675 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
678 if (flags & DP_F_SPACE)
682 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
687 /* With %g precision is the number of significant digits, which
688 includes the digits in intpart. */
689 if (flags & DP_F_FP_G)
693 /* For each digit of INTPART, print one less fractional digit. */
694 LLONG temp = intpart;
695 for (temp = intpart; temp != 0; temp /= 10)
702 /* For each leading 0 in fractional part, print one more
706 for (temp = ufvalue; temp < 0.1; temp *= 10)
711 /* C99: trailing zeros are removed from the fractional portion of the
712 result unless the # flag is specified */
713 if ((flags & DP_F_FP_G) && !(flags & DP_F_NUM))
716 #if SIZEOF_LONG_LONG > 0
717 # define MAX_DIGITS 18 /* grok more digits with long long */
719 # define MAX_DIGITS 9 /* just long */
723 * Sorry, we only support several digits past the decimal because of
724 * our conversion method
726 if (max > MAX_DIGITS)
729 /* Factor of 10 with the needed number of digits, e.g. 1000 for max==3 */
730 mask10 = pow10_int (max);
732 /* We "cheat" by converting the fractional part to integer by
733 * multiplying by a factor of 10
735 fracpart = round_int (mask10 * (ufvalue - intpart));
737 if (fracpart >= mask10)
742 else if (fracpart != 0)
743 /* If fracpart has less digits than the 10* mask, we need to
744 manually insert leading 0s. For example 2.01's fractional part
745 requires one leading zero to distinguish it from 2.1. */
746 while (fracpart < mask10 / 10)
752 #ifdef DEBUG_SNPRINTF
753 dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart));
756 /* Convert integer part */
758 iconvert[iplace++] = '0' + intpart % 10;
759 intpart = (intpart / 10);
760 } while(intpart && (iplace < sizeof(iconvert)));
761 if (iplace == sizeof(iconvert)) iplace--;
762 iconvert[iplace] = 0;
764 /* Convert fractional part */
766 fconvert[fplace++] = '0' + fracpart % 10;
767 fracpart = (fracpart / 10);
768 } while(fracpart && (fplace < sizeof(fconvert)));
769 while (leadingfrac0s-- > 0 && fplace < sizeof(fconvert))
770 fconvert[fplace++] = '0';
771 if (fplace == sizeof(fconvert)) fplace--;
772 fconvert[fplace] = 0;
774 while (omitcount < fplace && fconvert[omitcount] == '0')
777 /* -1 for decimal point, another -1 if we are printing a sign */
778 padlen = min - iplace - (max - omitcount) - 1 - ((signvalue) ? 1 : 0);
780 zpadlen = max - fplace;
785 if (flags & DP_F_MINUS)
786 padlen = -padlen; /* Left Justifty */
788 if ((flags & DP_F_ZERO) && (padlen > 0))
792 total += dopr_outch (buffer, currlen, maxlen, signvalue);
798 total += dopr_outch (buffer, currlen, maxlen, '0');
804 total += dopr_outch (buffer, currlen, maxlen, ' ');
808 total += dopr_outch (buffer, currlen, maxlen, signvalue);
811 total += dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
814 * Decimal point. This should probably use locale to find the correct
817 if (max > 0 && (fplace > omitcount || zpadlen > 0))
819 total += dopr_outch (buffer, currlen, maxlen, '.');
821 while (fplace > omitcount)
822 total += dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
827 total += dopr_outch (buffer, currlen, maxlen, '0');
833 total += dopr_outch (buffer, currlen, maxlen, ' ');
840 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c)
842 if (*currlen + 1 < maxlen)
843 buffer[(*currlen)++] = c;
847 #ifndef HAVE_VSNPRINTF
848 int vsnprintf (char *str, size_t count, const char *fmt, va_list args)
852 return dopr(str, count, fmt, args);
854 #endif /* !HAVE_VSNPRINTF */
856 #ifndef HAVE_SNPRINTF
857 int snprintf (char *str, size_t count, const char *fmt,...)
863 total = vsnprintf (str, count, fmt, ap);
867 #endif /* !HAVE_SNPRINTF */
868 #endif /* !HAVE_SNPRINTF || !HAVE_VSNPRINTF */
873 # define LONG_STRING 1024
878 char buf1[LONG_STRING];
879 char buf2[LONG_STRING];
897 #if SIZEOF_LONG_LONG != 0
909 #if SIZEOF_LONG_LONG != 0
915 double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
916 0.9996, 1.996, 4.136, 0.00205, 0.0001, 321.000009,
930 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
931 #if SIZEOF_LONG_LONG != 0
932 char *llong_fmt[] = {
934 "%-1.5lld", "%-1.5llu",
935 "%1.5lld", "%1.5llu",
936 "%123.9lld", "%123.9llu",
937 "%5.5lld", "%5.5llu",
938 "%10.5lld", "%10.5llu",
939 "% 10.5lld", "% 10.5llu",
940 "%+22.33lld", "%+22.33llu",
941 "%01.3lld", "%01.3llu",
945 long long llong_nums[] = {
946 ~(long long)0, /* all-1 bit pattern */
947 (~(unsigned long long)0) >> 1, /* largest signed long long */
949 -150, 134, 91340, 341,
957 printf ("Testing snprintf format codes against system sprintf...\n");
959 for (x = 0; fp_fmt[x] != NULL ; x++)
960 for (y = 0; fp_nums[y] != 0 ; y++)
962 snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]);
963 sprintf (buf2, fp_fmt[x], fp_nums[y]);
964 if (strcmp (buf1, buf2))
966 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
967 fp_fmt[x], buf1, buf2);
973 for (x = 0; int_fmt[x] != NULL ; x++)
974 for (y = 0; int_nums[y] != 0 ; y++)
976 snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]);
977 sprintf (buf2, int_fmt[x], int_nums[y]);
978 if (strcmp (buf1, buf2))
980 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
981 int_fmt[x], buf1, buf2);
987 #if SIZEOF_LONG_LONG != 0
988 for (x = 0; llong_fmt[x] != NULL ; x++)
989 for (y = 0; llong_nums[y] != 0 ; y++)
991 snprintf (buf1, sizeof (buf1), llong_fmt[x], llong_nums[y]);
992 sprintf (buf2, llong_fmt[x], llong_nums[y]);
993 if (strcmp (buf1, buf2))
995 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
996 llong_fmt[x], buf1, buf2);
1003 printf ("%d tests failed out of %d.\n", fail, num);
1006 #endif /* TEST_SNPRINTF */