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 **************************************************************/
90 #define USE_GNULIB_ALLOC
96 /* For testing purposes, always compile in the code. */
99 # undef HAVE_VSNPRINTF
100 # ifndef SIZEOF_LONG_LONG
102 # define SIZEOF_LONG_LONG 8
107 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF)
110 #include <sys/types.h>
111 #include <stdio.h> /* for NULL */
115 #ifdef HAVE_LONG_DOUBLE
116 #define LDOUBLE long double
118 #define LDOUBLE double
121 #if SIZEOF_LONG_LONG != 0
122 # define LLONG long long
127 /* If we're running the test suite, rename snprintf and vsnprintf to
128 avoid conflicts with the system version. */
130 # define snprintf test_snprintf
131 # define vsnprintf test_vsnprintf
134 int snprintf (char *str, size_t count, const char *fmt, ...);
135 int vsnprintf (char *str, size_t count, const char *fmt, va_list arg);
137 static int dopr (char *buffer, size_t maxlen, const char *format,
139 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
140 const char *value, int flags, int min, int max);
141 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
142 LLONG value, int base, int min, int max, int flags);
143 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
144 LDOUBLE fvalue, int min, int max, int flags);
145 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c);
148 * dopr(): poor man's version of doprintf
151 /* format read states */
152 #define DP_S_DEFAULT 0
162 /* format flags - Bits */
163 #define DP_F_MINUS (1 << 0)
164 #define DP_F_PLUS (1 << 1)
165 #define DP_F_SPACE (1 << 2)
166 #define DP_F_NUM (1 << 3)
167 #define DP_F_ZERO (1 << 4)
168 #define DP_F_UP (1 << 5)
169 #define DP_F_UNSIGNED (1 << 6)
170 #define DP_F_FP_G (1 << 7)
172 /* Conversion Flags */
176 #define DP_C_LDOUBLE 4
178 #define char_to_int(p) (p - '0')
179 #define MAX(p,q) ((p >= q) ? p : q)
180 #define MIN(p,q) ((p <= q) ? p : q)
182 static int dopr (char *buffer, size_t maxlen, const char *format, va_list args)
196 state = DP_S_DEFAULT;
197 currlen = flags = cflags = min = 0;
202 while (state != DP_S_DONE)
213 total += dopr_outch (buffer, &currlen, maxlen, ch);
245 if ('0' <= ch && ch <= '9')
247 min = 10*min + char_to_int (ch);
252 min = va_arg (args, int);
269 if ('0' <= ch && ch <= '9')
273 max = 10*max + char_to_int (ch);
278 max = va_arg (args, int);
297 cflags = DP_C_LDOUBLE;
303 if (cflags != DP_C_LONG)
325 if (cflags == DP_C_SHORT)
326 value = (short int) va_arg (args, int);
327 else if (cflags == DP_C_LONG)
328 value = va_arg (args, long int);
329 else if (cflags == DP_C_LLONG)
330 value = va_arg (args, LLONG);
332 value = va_arg (args, int);
333 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
336 flags |= DP_F_UNSIGNED;
337 if (cflags == DP_C_SHORT)
338 value = (unsigned short int) va_arg (args, unsigned int);
339 else if (cflags == DP_C_LONG)
340 value = va_arg (args, unsigned long int);
341 else if (cflags == DP_C_LLONG)
342 value = va_arg (args, unsigned LLONG);
344 value = va_arg (args, unsigned int);
345 total += fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
348 flags |= DP_F_UNSIGNED;
349 if (cflags == DP_C_SHORT)
350 value = (unsigned short int) va_arg (args, unsigned int);
351 else if (cflags == DP_C_LONG)
352 value = va_arg (args, unsigned long int);
353 else if (cflags == DP_C_LLONG)
354 value = va_arg (args, unsigned LLONG);
356 value = va_arg (args, unsigned int);
357 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
362 flags |= DP_F_UNSIGNED;
363 if (cflags == DP_C_SHORT)
364 value = (unsigned short int) va_arg (args, unsigned int);
365 else if (cflags == DP_C_LONG)
366 value = va_arg (args, unsigned long int);
367 else if (cflags == DP_C_LLONG)
368 value = va_arg (args, unsigned LLONG);
370 value = va_arg (args, unsigned int);
371 total += fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
374 if (cflags == DP_C_LDOUBLE)
375 fvalue = va_arg (args, LDOUBLE);
377 fvalue = va_arg (args, double);
378 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
383 if (cflags == DP_C_LDOUBLE)
384 fvalue = va_arg (args, LDOUBLE);
386 fvalue = va_arg (args, double);
387 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
393 if (cflags == DP_C_LDOUBLE)
394 fvalue = va_arg (args, LDOUBLE);
396 fvalue = va_arg (args, double);
398 /* C99 says: if precision [for %g] is zero, it is taken as one */
400 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
403 total += dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
406 strvalue = va_arg (args, char *);
407 total += fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
410 strvalue = va_arg (args, void *);
411 total += fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min,
415 if (cflags == DP_C_SHORT)
418 num = va_arg (args, short int *);
421 else if (cflags == DP_C_LONG)
424 num = va_arg (args, long int *);
427 else if (cflags == DP_C_LLONG)
430 num = va_arg (args, LLONG *);
436 num = va_arg (args, int *);
441 total += dopr_outch (buffer, &currlen, maxlen, ch);
444 /* not supported yet, treat as next char */
452 state = DP_S_DEFAULT;
453 flags = cflags = min = 0;
460 break; /* some picky compilers need this */
465 if (currlen < maxlen - 1)
466 buffer[currlen] = '\0';
468 buffer[maxlen - 1] = '\0';
473 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
474 const char *value, int flags, int min, int max)
476 int padlen, strln; /* amount to pad */
486 strln = strlen (value);
488 /* When precision is specified, don't read VALUE past precision. */
489 /*strln = strnlen (value, max);*/
490 for (strln = 0; strln < max && value[strln]; ++strln)
492 padlen = min - strln;
495 if (flags & DP_F_MINUS)
496 padlen = -padlen; /* Left Justify */
500 total += dopr_outch (buffer, currlen, maxlen, ' ');
503 while (*value && ((max < 0) || (cnt < max)))
505 total += dopr_outch (buffer, currlen, maxlen, *value++);
510 total += dopr_outch (buffer, currlen, maxlen, ' ');
516 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
518 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
519 LLONG value, int base, int min, int max, int flags)
522 unsigned LLONG uvalue;
525 int spadlen = 0; /* amount to space pad */
526 int zpadlen = 0; /* amount to zero pad */
535 if(!(flags & DP_F_UNSIGNED))
542 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
545 if (flags & DP_F_SPACE)
550 /* Should characters be upper case? */
551 digits = "0123456789ABCDEF";
553 digits = "0123456789abcdef";
556 convert[place++] = digits[uvalue % (unsigned)base];
557 uvalue = (uvalue / (unsigned)base );
558 } while(uvalue && (place < sizeof (convert)));
559 if (place == sizeof (convert)) place--;
562 zpadlen = max - place;
563 spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
564 if (zpadlen < 0) zpadlen = 0;
565 if (spadlen < 0) spadlen = 0;
566 if (flags & DP_F_ZERO)
568 zpadlen = MAX(zpadlen, spadlen);
571 if (flags & DP_F_MINUS)
572 spadlen = -spadlen; /* Left Justifty */
574 #ifdef DEBUG_SNPRINTF
575 dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
576 zpadlen, spadlen, min, max, place));
582 total += dopr_outch (buffer, currlen, maxlen, ' ');
588 total += dopr_outch (buffer, currlen, maxlen, signvalue);
595 total += dopr_outch (buffer, currlen, maxlen, '0');
602 total += dopr_outch (buffer, currlen, maxlen, convert[--place]);
604 /* Left Justified spaces */
605 while (spadlen < 0) {
606 total += dopr_outch (buffer, currlen, maxlen, ' ');
613 static LDOUBLE abs_val (LDOUBLE value)
615 LDOUBLE result = value;
623 static LDOUBLE pow10_int (int exp)
636 static LLONG round_int (LDOUBLE value)
641 value = value - intpart;
648 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
649 LDOUBLE fvalue, int min, int max, int flags)
657 int padlen = 0; /* amount to pad */
663 int leadingfrac0s = 0; /* zeros at the start of fractional part */
668 * AIX manpage says the default is 0, but Solaris says the default
669 * is 6, and sprintf on AIX defaults to 6
674 ufvalue = abs_val (fvalue);
679 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
682 if (flags & DP_F_SPACE)
686 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
691 /* With %g precision is the number of significant digits, which
692 includes the digits in intpart. */
693 if (flags & DP_F_FP_G)
697 /* For each digit of INTPART, print one less fractional digit. */
698 LLONG temp = intpart;
699 for (temp = intpart; temp != 0; temp /= 10)
706 /* For each leading 0 in fractional part, print one more
710 for (temp = ufvalue; temp < 0.1; temp *= 10)
715 /* C99: trailing zeros are removed from the fractional portion of the
716 result unless the # flag is specified */
717 if ((flags & DP_F_FP_G) && !(flags & DP_F_NUM))
720 #if SIZEOF_LONG_LONG > 0
721 # define MAX_DIGITS 18 /* grok more digits with long long */
723 # define MAX_DIGITS 9 /* just long */
727 * Sorry, we only support several digits past the decimal because of
728 * our conversion method
730 if (max > MAX_DIGITS)
733 /* Factor of 10 with the needed number of digits, e.g. 1000 for max==3 */
734 mask10 = pow10_int (max);
736 /* We "cheat" by converting the fractional part to integer by
737 * multiplying by a factor of 10
739 fracpart = round_int (mask10 * (ufvalue - intpart));
741 if (fracpart >= mask10)
746 else if (fracpart != 0)
747 /* If fracpart has less digits than the 10* mask, we need to
748 manually insert leading 0s. For example 2.01's fractional part
749 requires one leading zero to distinguish it from 2.1. */
750 while (fracpart < mask10 / 10)
756 #ifdef DEBUG_SNPRINTF
757 dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart));
760 /* Convert integer part */
762 iconvert[iplace++] = '0' + intpart % 10;
763 intpart = (intpart / 10);
764 } while(intpart && (iplace < sizeof(iconvert)));
765 if (iplace == sizeof(iconvert)) iplace--;
766 iconvert[iplace] = 0;
768 /* Convert fractional part */
770 fconvert[fplace++] = '0' + fracpart % 10;
771 fracpart = (fracpart / 10);
772 } while(fracpart && (fplace < sizeof(fconvert)));
773 while (leadingfrac0s-- > 0 && fplace < sizeof(fconvert))
774 fconvert[fplace++] = '0';
775 if (fplace == sizeof(fconvert)) fplace--;
776 fconvert[fplace] = 0;
778 while (omitcount < fplace && fconvert[omitcount] == '0')
781 /* -1 for decimal point, another -1 if we are printing a sign */
782 padlen = min - iplace - (max - omitcount) - 1 - ((signvalue) ? 1 : 0);
784 zpadlen = max - fplace;
789 if (flags & DP_F_MINUS)
790 padlen = -padlen; /* Left Justifty */
792 if ((flags & DP_F_ZERO) && (padlen > 0))
796 total += dopr_outch (buffer, currlen, maxlen, signvalue);
802 total += dopr_outch (buffer, currlen, maxlen, '0');
808 total += dopr_outch (buffer, currlen, maxlen, ' ');
812 total += dopr_outch (buffer, currlen, maxlen, signvalue);
815 total += dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
818 * Decimal point. This should probably use locale to find the correct
821 if (max > 0 && (fplace > omitcount || zpadlen > 0))
823 total += dopr_outch (buffer, currlen, maxlen, '.');
825 while (fplace > omitcount)
826 total += dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
831 total += dopr_outch (buffer, currlen, maxlen, '0');
837 total += dopr_outch (buffer, currlen, maxlen, ' ');
844 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c)
846 if (*currlen + 1 < maxlen)
847 buffer[(*currlen)++] = c;
851 #ifndef HAVE_VSNPRINTF
852 int vsnprintf (char *str, size_t count, const char *fmt, va_list args)
856 return dopr(str, count, fmt, args);
858 #endif /* !HAVE_VSNPRINTF */
860 #ifndef HAVE_SNPRINTF
861 int snprintf (char *str, size_t count, const char *fmt,...)
867 total = vsnprintf (str, count, fmt, ap);
871 #endif /* !HAVE_SNPRINTF */
872 #endif /* !HAVE_SNPRINTF || !HAVE_VSNPRINTF */
877 # define LONG_STRING 1024
882 char buf1[LONG_STRING];
883 char buf2[LONG_STRING];
901 #if SIZEOF_LONG_LONG != 0
913 #if SIZEOF_LONG_LONG != 0
919 double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
920 0.9996, 1.996, 4.136, 0.00205, 0.0001, 321.000009,
934 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
935 #if SIZEOF_LONG_LONG != 0
936 char *llong_fmt[] = {
938 "%-1.5lld", "%-1.5llu",
939 "%1.5lld", "%1.5llu",
940 "%123.9lld", "%123.9llu",
941 "%5.5lld", "%5.5llu",
942 "%10.5lld", "%10.5llu",
943 "% 10.5lld", "% 10.5llu",
944 "%+22.33lld", "%+22.33llu",
945 "%01.3lld", "%01.3llu",
949 long long llong_nums[] = {
950 ~(long long)0, /* all-1 bit pattern */
951 (~(unsigned long long)0) >> 1, /* largest signed long long */
953 -150, 134, 91340, 341,
961 printf ("Testing snprintf format codes against system sprintf...\n");
963 for (x = 0; fp_fmt[x] != NULL ; x++)
964 for (y = 0; fp_nums[y] != 0 ; y++)
966 snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]);
967 sprintf (buf2, fp_fmt[x], fp_nums[y]);
968 if (strcmp (buf1, buf2))
970 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
971 fp_fmt[x], buf1, buf2);
977 for (x = 0; int_fmt[x] != NULL ; x++)
978 for (y = 0; int_nums[y] != 0 ; y++)
980 snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]);
981 sprintf (buf2, int_fmt[x], int_nums[y]);
982 if (strcmp (buf1, buf2))
984 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
985 int_fmt[x], buf1, buf2);
991 #if SIZEOF_LONG_LONG != 0
992 for (x = 0; llong_fmt[x] != NULL ; x++)
993 for (y = 0; llong_nums[y] != 0 ; y++)
995 snprintf (buf1, sizeof (buf1), llong_fmt[x], llong_nums[y]);
996 sprintf (buf2, llong_fmt[x], llong_nums[y]);
997 if (strcmp (buf1, buf2))
999 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
1000 llong_fmt[x], buf1, buf2);
1007 printf ("%d tests failed out of %d.\n", fail, num);
1010 #endif /* TEST_SNPRINTF */