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 **************************************************************/
94 /* For testing purposes, always compile in the code. */
97 # undef HAVE_VSNPRINTF
98 # ifndef SIZEOF_LONG_LONG
100 # define SIZEOF_LONG_LONG 8
105 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF)
108 #include <sys/types.h>
109 #include <stdio.h> /* for NULL */
113 #ifdef HAVE_LONG_DOUBLE
114 #define LDOUBLE long double
116 #define LDOUBLE double
119 #if SIZEOF_LONG_LONG != 0
120 # define LLONG long long
125 /* If we're running the test suite, rename snprintf and vsnprintf to
126 avoid conflicts with the system version. */
128 # define snprintf test_snprintf
129 # define vsnprintf test_vsnprintf
132 int snprintf (char *str, size_t count, const char *fmt, ...);
133 int vsnprintf (char *str, size_t count, const char *fmt, va_list arg);
135 static int dopr (char *buffer, size_t maxlen, const char *format,
137 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
138 const char *value, int flags, int min, int max);
139 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
140 LLONG value, int base, int min, int max, int flags);
141 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
142 LDOUBLE fvalue, int min, int max, int flags);
143 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c);
146 * dopr(): poor man's version of doprintf
149 /* format read states */
150 #define DP_S_DEFAULT 0
160 /* format flags - Bits */
161 #define DP_F_MINUS (1 << 0)
162 #define DP_F_PLUS (1 << 1)
163 #define DP_F_SPACE (1 << 2)
164 #define DP_F_NUM (1 << 3)
165 #define DP_F_ZERO (1 << 4)
166 #define DP_F_UP (1 << 5)
167 #define DP_F_UNSIGNED (1 << 6)
168 #define DP_F_FP_G (1 << 7)
170 /* Conversion Flags */
174 #define DP_C_LDOUBLE 4
176 #define char_to_int(p) (p - '0')
177 #define MAX(p,q) ((p >= q) ? p : q)
178 #define MIN(p,q) ((p <= q) ? p : q)
180 static int dopr (char *buffer, size_t maxlen, const char *format, va_list args)
194 state = DP_S_DEFAULT;
195 currlen = flags = cflags = min = 0;
200 while (state != DP_S_DONE)
211 total += dopr_outch (buffer, &currlen, maxlen, ch);
243 if ('0' <= ch && ch <= '9')
245 min = 10*min + char_to_int (ch);
250 min = va_arg (args, int);
267 if ('0' <= ch && ch <= '9')
271 max = 10*max + char_to_int (ch);
276 max = va_arg (args, int);
295 cflags = DP_C_LDOUBLE;
301 if (cflags != DP_C_LONG)
323 if (cflags == DP_C_SHORT)
324 value = (short int) 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 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
334 flags |= DP_F_UNSIGNED;
335 if (cflags == DP_C_SHORT)
336 value = (unsigned short int) va_arg (args, unsigned int);
337 else if (cflags == DP_C_LONG)
338 value = va_arg (args, unsigned long int);
339 else if (cflags == DP_C_LLONG)
340 value = va_arg (args, unsigned LLONG);
342 value = va_arg (args, unsigned int);
343 total += fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
346 flags |= DP_F_UNSIGNED;
347 if (cflags == DP_C_SHORT)
348 value = (unsigned short int) va_arg (args, unsigned int);
349 else if (cflags == DP_C_LONG)
350 value = va_arg (args, unsigned long int);
351 else if (cflags == DP_C_LLONG)
352 value = va_arg (args, unsigned LLONG);
354 value = va_arg (args, unsigned int);
355 total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
360 flags |= DP_F_UNSIGNED;
361 if (cflags == DP_C_SHORT)
362 value = (unsigned short int) va_arg (args, unsigned int);
363 else if (cflags == DP_C_LONG)
364 value = va_arg (args, unsigned long int);
365 else if (cflags == DP_C_LLONG)
366 value = va_arg (args, unsigned LLONG);
368 value = va_arg (args, unsigned int);
369 total += 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 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
381 if (cflags == DP_C_LDOUBLE)
382 fvalue = va_arg (args, LDOUBLE);
384 fvalue = va_arg (args, double);
385 total += 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);
396 /* C99 says: if precision [for %g] is zero, it is taken as one */
398 total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
401 total += dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
404 strvalue = va_arg (args, char *);
405 total += fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
408 strvalue = va_arg (args, void *);
409 total += fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min,
413 if (cflags == DP_C_SHORT)
416 num = va_arg (args, short int *);
419 else if (cflags == DP_C_LONG)
422 num = va_arg (args, long int *);
425 else if (cflags == DP_C_LLONG)
428 num = va_arg (args, LLONG *);
434 num = va_arg (args, int *);
439 total += dopr_outch (buffer, &currlen, maxlen, ch);
442 /* not supported yet, treat as next char */
450 state = DP_S_DEFAULT;
451 flags = cflags = min = 0;
458 break; /* some picky compilers need this */
463 if (currlen < maxlen - 1)
464 buffer[currlen] = '\0';
466 buffer[maxlen - 1] = '\0';
471 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
472 const char *value, int flags, int min, int max)
474 int padlen, strln; /* amount to pad */
484 strln = strlen (value);
486 /* When precision is specified, don't read VALUE past precision. */
487 /*strln = strnlen (value, max);*/
488 for (strln = 0; strln < max && value[strln]; ++strln)
490 padlen = min - strln;
493 if (flags & DP_F_MINUS)
494 padlen = -padlen; /* Left Justify */
498 total += dopr_outch (buffer, currlen, maxlen, ' ');
501 while (*value && ((max < 0) || (cnt < max)))
503 total += dopr_outch (buffer, currlen, maxlen, *value++);
508 total += dopr_outch (buffer, currlen, maxlen, ' ');
514 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
516 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
517 LLONG value, int base, int min, int max, int flags)
520 unsigned LLONG uvalue;
523 int spadlen = 0; /* amount to space pad */
524 int zpadlen = 0; /* amount to zero pad */
533 if(!(flags & DP_F_UNSIGNED))
540 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
543 if (flags & DP_F_SPACE)
548 /* Should characters be upper case? */
549 digits = "0123456789ABCDEF";
551 digits = "0123456789abcdef";
554 convert[place++] = digits[uvalue % (unsigned)base];
555 uvalue = (uvalue / (unsigned)base );
556 } while(uvalue && (place < sizeof (convert)));
557 if (place == sizeof (convert)) place--;
560 zpadlen = max - place;
561 spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
562 if (zpadlen < 0) zpadlen = 0;
563 if (spadlen < 0) spadlen = 0;
564 if (flags & DP_F_ZERO)
566 zpadlen = MAX(zpadlen, spadlen);
569 if (flags & DP_F_MINUS)
570 spadlen = -spadlen; /* Left Justifty */
572 #ifdef DEBUG_SNPRINTF
573 dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
574 zpadlen, spadlen, min, max, place));
580 total += dopr_outch (buffer, currlen, maxlen, ' ');
586 total += dopr_outch (buffer, currlen, maxlen, signvalue);
593 total += dopr_outch (buffer, currlen, maxlen, '0');
600 total += dopr_outch (buffer, currlen, maxlen, convert[--place]);
602 /* Left Justified spaces */
603 while (spadlen < 0) {
604 total += dopr_outch (buffer, currlen, maxlen, ' ');
611 static LDOUBLE abs_val (LDOUBLE value)
613 LDOUBLE result = value;
621 static LDOUBLE pow10_int (int exp)
634 static LLONG round_int (LDOUBLE value)
639 value = value - intpart;
646 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
647 LDOUBLE fvalue, int min, int max, int flags)
655 int padlen = 0; /* amount to pad */
661 int leadingfrac0s = 0; /* zeros at the start of fractional part */
666 * AIX manpage says the default is 0, but Solaris says the default
667 * is 6, and sprintf on AIX defaults to 6
672 ufvalue = abs_val (fvalue);
677 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
680 if (flags & DP_F_SPACE)
684 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
689 /* With %g precision is the number of significant digits, which
690 includes the digits in intpart. */
691 if (flags & DP_F_FP_G)
695 /* For each digit of INTPART, print one less fractional digit. */
696 LLONG temp = intpart;
697 for (temp = intpart; temp != 0; temp /= 10)
704 /* For each leading 0 in fractional part, print one more
708 for (temp = ufvalue; temp < 0.1; temp *= 10)
713 /* C99: trailing zeros are removed from the fractional portion of the
714 result unless the # flag is specified */
715 if ((flags & DP_F_FP_G) && !(flags & DP_F_NUM))
718 #if SIZEOF_LONG_LONG > 0
719 # define MAX_DIGITS 18 /* grok more digits with long long */
721 # define MAX_DIGITS 9 /* just long */
725 * Sorry, we only support several digits past the decimal because of
726 * our conversion method
728 if (max > MAX_DIGITS)
731 /* Factor of 10 with the needed number of digits, e.g. 1000 for max==3 */
732 mask10 = pow10_int (max);
734 /* We "cheat" by converting the fractional part to integer by
735 * multiplying by a factor of 10
737 fracpart = round_int (mask10 * (ufvalue - intpart));
739 if (fracpart >= mask10)
744 else if (fracpart != 0)
745 /* If fracpart has less digits than the 10* mask, we need to
746 manually insert leading 0s. For example 2.01's fractional part
747 requires one leading zero to distinguish it from 2.1. */
748 while (fracpart < mask10 / 10)
754 #ifdef DEBUG_SNPRINTF
755 dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart));
758 /* Convert integer part */
760 iconvert[iplace++] = '0' + intpart % 10;
761 intpart = (intpart / 10);
762 } while(intpart && (iplace < sizeof(iconvert)));
763 if (iplace == sizeof(iconvert)) iplace--;
764 iconvert[iplace] = 0;
766 /* Convert fractional part */
768 fconvert[fplace++] = '0' + fracpart % 10;
769 fracpart = (fracpart / 10);
770 } while(fracpart && (fplace < sizeof(fconvert)));
771 while (leadingfrac0s-- > 0 && fplace < sizeof(fconvert))
772 fconvert[fplace++] = '0';
773 if (fplace == sizeof(fconvert)) fplace--;
774 fconvert[fplace] = 0;
776 while (omitcount < fplace && fconvert[omitcount] == '0')
779 /* -1 for decimal point, another -1 if we are printing a sign */
780 padlen = min - iplace - (max - omitcount) - 1 - ((signvalue) ? 1 : 0);
782 zpadlen = max - fplace;
787 if (flags & DP_F_MINUS)
788 padlen = -padlen; /* Left Justifty */
790 if ((flags & DP_F_ZERO) && (padlen > 0))
794 total += dopr_outch (buffer, currlen, maxlen, signvalue);
800 total += dopr_outch (buffer, currlen, maxlen, '0');
806 total += dopr_outch (buffer, currlen, maxlen, ' ');
810 total += dopr_outch (buffer, currlen, maxlen, signvalue);
813 total += dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
816 * Decimal point. This should probably use locale to find the correct
819 if (max > 0 && (fplace > omitcount || zpadlen > 0))
821 total += dopr_outch (buffer, currlen, maxlen, '.');
823 while (fplace > omitcount)
824 total += dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
829 total += dopr_outch (buffer, currlen, maxlen, '0');
835 total += dopr_outch (buffer, currlen, maxlen, ' ');
842 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c)
844 if (*currlen + 1 < maxlen)
845 buffer[(*currlen)++] = c;
849 #ifndef HAVE_VSNPRINTF
850 int vsnprintf (char *str, size_t count, const char *fmt, va_list args)
854 return dopr(str, count, fmt, args);
856 #endif /* !HAVE_VSNPRINTF */
858 #ifndef HAVE_SNPRINTF
859 int snprintf (char *str, size_t count, const char *fmt,...)
865 total = vsnprintf (str, count, fmt, ap);
869 #endif /* !HAVE_SNPRINTF */
870 #endif /* !HAVE_SNPRINTF || !HAVE_VSNPRINTF */
875 # define LONG_STRING 1024
880 char buf1[LONG_STRING];
881 char buf2[LONG_STRING];
899 #if SIZEOF_LONG_LONG != 0
911 #if SIZEOF_LONG_LONG != 0
917 double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
918 0.9996, 1.996, 4.136, 0.00205, 0.0001, 321.000009,
932 long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
933 #if SIZEOF_LONG_LONG != 0
934 char *llong_fmt[] = {
936 "%-1.5lld", "%-1.5llu",
937 "%1.5lld", "%1.5llu",
938 "%123.9lld", "%123.9llu",
939 "%5.5lld", "%5.5llu",
940 "%10.5lld", "%10.5llu",
941 "% 10.5lld", "% 10.5llu",
942 "%+22.33lld", "%+22.33llu",
943 "%01.3lld", "%01.3llu",
947 long long llong_nums[] = {
948 ~(long long)0, /* all-1 bit pattern */
949 (~(unsigned long long)0) >> 1, /* largest signed long long */
951 -150, 134, 91340, 341,
959 printf ("Testing snprintf format codes against system sprintf...\n");
961 for (x = 0; fp_fmt[x] != NULL ; x++)
962 for (y = 0; fp_nums[y] != 0 ; y++)
964 snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]);
965 sprintf (buf2, fp_fmt[x], fp_nums[y]);
966 if (strcmp (buf1, buf2))
968 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
969 fp_fmt[x], buf1, buf2);
975 for (x = 0; int_fmt[x] != NULL ; x++)
976 for (y = 0; int_nums[y] != 0 ; y++)
978 snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]);
979 sprintf (buf2, int_fmt[x], int_nums[y]);
980 if (strcmp (buf1, buf2))
982 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
983 int_fmt[x], buf1, buf2);
989 #if SIZEOF_LONG_LONG != 0
990 for (x = 0; llong_fmt[x] != NULL ; x++)
991 for (y = 0; llong_nums[y] != 0 ; y++)
993 snprintf (buf1, sizeof (buf1), llong_fmt[x], llong_nums[y]);
994 sprintf (buf2, llong_fmt[x], llong_nums[y]);
995 if (strcmp (buf1, buf2))
997 printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n",
998 llong_fmt[x], buf1, buf2);
1005 printf ("%d tests failed out of %d.\n", fail, num);
1008 #endif /* TEST_SNPRINTF */