]> sjero.net Git - wget/blob - src/snprintf.c
bb98bd0b1c129e707bb875d9860af2e741483f5a
[wget] / src / snprintf.c
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.
5
6    My changes are documented at the bottom, along with other changes.
7    I hereby place my modifications to this file under the public
8    domain.  */
9
10 /*
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
15  */
16
17 /**************************************************************
18  * Original:
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...
23  *
24  * snprintf() is used instead of sprintf() as it does limit checks
25  * for string length.  This covers a nasty loophole.
26  *
27  * The other functions are there to prevent NULL pointers from
28  * causing nast effects.
29  *
30  * More Recently:
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.
36  *
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.
47  *
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.
51  *
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.
56  *
57  *  Andrew Tridgell (tridge@samba.org) Oct 1998
58  *    fixed handling of %.0f
59  *    added test for HAVE_LONG_DOUBLE
60  *
61  *  Russ Allbery <rra@stanford.edu> 2000-08-26
62  *    fixed return value to comply with C99
63  *    fixed handling of snprintf(NULL, ...)
64  *
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.
72  *
73  *  alexk (INN) 2002-08-21
74  *    use LLONG in fmtfp to handle more characters during floating
75  *    point conversion.
76  *
77  *  herb (Samba) 2002-12-19
78  *    actually print args for %g and %e
79  *
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
87  *
88  **************************************************************/
89
90 #include "wget.h"
91
92 /* For testing purposes, always compile in the code. */
93 #ifdef TEST_SNPRINTF
94 # undef HAVE_SNPRINTF
95 # undef HAVE_VSNPRINTF
96 # ifndef SIZEOF_LONG_LONG
97 #  ifdef __GNUC__
98 #   define SIZEOF_LONG_LONG 8
99 #  endif
100 # endif
101 #endif
102
103 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF)
104
105 #include <string.h>
106 #include <sys/types.h>
107 #include <stdio.h>              /* for NULL */
108
109 #include <stdarg.h>
110
111 #ifdef HAVE_LONG_DOUBLE
112 #define LDOUBLE long double
113 #else
114 #define LDOUBLE double
115 #endif
116
117 #if SIZEOF_LONG_LONG != 0
118 # define LLONG long long
119 #else
120 # define LLONG long
121 #endif
122
123 /* If we're running the test suite, rename snprintf and vsnprintf to
124    avoid conflicts with the system version.  */
125 #ifdef TEST_SNPRINTF
126 # define snprintf test_snprintf
127 # define vsnprintf test_vsnprintf
128 #endif
129
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);
132
133 static int dopr (char *buffer, size_t maxlen, const char *format,
134                  va_list args);
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);
142
143 /*
144  * dopr(): poor man's version of doprintf
145  */
146
147 /* format read states */
148 #define DP_S_DEFAULT 0
149 #define DP_S_FLAGS   1
150 #define DP_S_MIN     2
151 #define DP_S_DOT     3
152 #define DP_S_MAX     4
153 #define DP_S_MOD     5
154 #define DP_S_MOD_L   6
155 #define DP_S_CONV    7
156 #define DP_S_DONE    8
157
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)
167
168 /* Conversion Flags */
169 #define DP_C_SHORT   1
170 #define DP_C_LONG    2
171 #define DP_C_LLONG   3
172 #define DP_C_LDOUBLE 4
173
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)
177
178 static int dopr (char *buffer, size_t maxlen, const char *format, va_list args)
179 {
180   char ch;
181   LLONG value;
182   LDOUBLE fvalue;
183   char *strvalue;
184   int min;
185   int max;
186   int state;
187   int flags;
188   int cflags;
189   int total;
190   size_t currlen;
191
192   state = DP_S_DEFAULT;
193   currlen = flags = cflags = min = 0;
194   max = -1;
195   ch = *format++;
196   total = 0;
197
198   while (state != DP_S_DONE)
199   {
200     if (ch == '\0')
201       state = DP_S_DONE;
202
203     switch(state)
204     {
205     case DP_S_DEFAULT:
206       if (ch == '%')
207         state = DP_S_FLAGS;
208       else
209         total += dopr_outch (buffer, &currlen, maxlen, ch);
210       ch = *format++;
211       break;
212     case DP_S_FLAGS:
213       switch (ch)
214       {
215       case '-':
216         flags |= DP_F_MINUS;
217         ch = *format++;
218         break;
219       case '+':
220         flags |= DP_F_PLUS;
221         ch = *format++;
222         break;
223       case ' ':
224         flags |= DP_F_SPACE;
225         ch = *format++;
226         break;
227       case '#':
228         flags |= DP_F_NUM;
229         ch = *format++;
230         break;
231       case '0':
232         flags |= DP_F_ZERO;
233         ch = *format++;
234         break;
235       default:
236         state = DP_S_MIN;
237         break;
238       }
239       break;
240     case DP_S_MIN:
241       if ('0' <= ch && ch <= '9')
242       {
243         min = 10*min + char_to_int (ch);
244         ch = *format++;
245       }
246       else if (ch == '*')
247       {
248         min = va_arg (args, int);
249         ch = *format++;
250         state = DP_S_DOT;
251       }
252       else
253         state = DP_S_DOT;
254       break;
255     case DP_S_DOT:
256       if (ch == '.')
257       {
258         state = DP_S_MAX;
259         ch = *format++;
260       }
261       else
262         state = DP_S_MOD;
263       break;
264     case DP_S_MAX:
265       if ('0' <= ch && ch <= '9')
266       {
267         if (max < 0)
268           max = 0;
269         max = 10*max + char_to_int (ch);
270         ch = *format++;
271       }
272       else if (ch == '*')
273       {
274         max = va_arg (args, int);
275         ch = *format++;
276         state = DP_S_MOD;
277       }
278       else
279         state = DP_S_MOD;
280       break;
281     case DP_S_MOD:
282       switch (ch)
283       {
284       case 'h':
285         cflags = DP_C_SHORT;
286         ch = *format++;
287         break;
288       case 'l':
289         cflags = DP_C_LONG;
290         ch = *format++;
291         break;
292       case 'L':
293         cflags = DP_C_LDOUBLE;
294         ch = *format++;
295         break;
296       default:
297         break;
298       }
299       if (cflags != DP_C_LONG)
300         state = DP_S_CONV;
301       else
302         state = DP_S_MOD_L;
303       break;
304     case DP_S_MOD_L:
305       switch (ch)
306         {
307         case 'l':
308           cflags = DP_C_LLONG;
309           ch = *format++;
310           break;
311         default:
312           break;
313         }
314       state = DP_S_CONV;
315       break;
316     case DP_S_CONV:
317       switch (ch)
318       {
319       case 'd':
320       case 'i':
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);
327         else
328           value = va_arg (args, int);
329         total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
330         break;
331       case 'o':
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);
339         else
340           value = va_arg (args, unsigned int);
341         total += fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
342         break;
343       case 'u':
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);
351         else
352           value = va_arg (args, unsigned int);
353         total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
354         break;
355       case 'X':
356         flags |= DP_F_UP;
357       case 'x':
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);
365         else
366           value = va_arg (args, unsigned int);
367         total += fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
368         break;
369       case 'f':
370         if (cflags == DP_C_LDOUBLE)
371           fvalue = va_arg (args, LDOUBLE);
372         else
373           fvalue = va_arg (args, double);
374         total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
375         break;
376       case 'E':
377         flags |= DP_F_UP;
378       case 'e':
379         if (cflags == DP_C_LDOUBLE)
380           fvalue = va_arg (args, LDOUBLE);
381         else
382           fvalue = va_arg (args, double);
383         total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
384         break;
385       case 'G':
386         flags |= DP_F_UP;
387       case 'g':
388         flags |= DP_F_FP_G;
389         if (cflags == DP_C_LDOUBLE)
390           fvalue = va_arg (args, LDOUBLE);
391         else
392           fvalue = va_arg (args, double);
393         if (max == 0)
394           /* C99 says: if precision [for %g] is zero, it is taken as one */
395           max = 1;
396         total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
397         break;
398       case 'c':
399         total += dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
400         break;
401       case 's':
402         strvalue = va_arg (args, char *);
403         total += fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
404         break;
405       case 'p':
406         flags |= DP_F_UNSIGNED;
407         strvalue = va_arg (args, void *);
408         total += fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min,
409                          max, flags);
410         break;
411       case 'n':
412         if (cflags == DP_C_SHORT)
413         {
414           short int *num;
415           num = va_arg (args, short int *);
416           *num = currlen;
417         }
418         else if (cflags == DP_C_LONG)
419         {
420           long int *num;
421           num = va_arg (args, long int *);
422           *num = currlen;
423         }
424         else if (cflags == DP_C_LLONG)
425         {
426           LLONG *num;
427           num = va_arg (args, LLONG *);
428           *num = currlen;
429         }
430         else
431         {
432           int *num;
433           num = va_arg (args, int *);
434           *num = currlen;
435         }
436         break;
437       case '%':
438         total += dopr_outch (buffer, &currlen, maxlen, ch);
439         break;
440       case 'w':
441         /* not supported yet, treat as next char */
442         ch = *format++;
443         break;
444       default:
445         /* Unknown, skip */
446         break;
447       }
448       ch = *format++;
449       state = DP_S_DEFAULT;
450       flags = cflags = min = 0;
451       max = -1;
452       break;
453     case DP_S_DONE:
454       break;
455     default:
456       /* hmm? */
457       break; /* some picky compilers need this */
458     }
459   }
460   if (buffer != NULL)
461   {
462     if (currlen < maxlen - 1)
463       buffer[currlen] = '\0';
464     else
465       buffer[maxlen - 1] = '\0';
466   }
467   return total;
468 }
469
470 static int fmtstr (char *buffer, size_t *currlen, size_t maxlen,
471                    const char *value, int flags, int min, int max)
472 {
473   int padlen, strln;     /* amount to pad */
474   int cnt = 0;
475   int total = 0;
476
477   if (value == 0)
478   {
479     value = "(null)";
480   }
481
482   if (max < 0)
483     strln = strlen (value);
484   else
485     /* When precision is specified, don't read VALUE past precision. */
486     /*strln = strnlen (value, max);*/
487     for (strln = 0; strln < max && value[strln]; ++strln)
488       ;
489   padlen = min - strln;
490   if (padlen < 0)
491     padlen = 0;
492   if (flags & DP_F_MINUS)
493     padlen = -padlen; /* Left Justify */
494
495   while (padlen > 0)
496   {
497     total += dopr_outch (buffer, currlen, maxlen, ' ');
498     --padlen;
499   }
500   while (*value && ((max < 0) || (cnt < max)))
501   {
502     total += dopr_outch (buffer, currlen, maxlen, *value++);
503     ++cnt;
504   }
505   while (padlen < 0)
506   {
507     total += dopr_outch (buffer, currlen, maxlen, ' ');
508     ++padlen;
509   }
510   return total;
511 }
512
513 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
514
515 static int fmtint (char *buffer, size_t *currlen, size_t maxlen,
516                    LLONG value, int base, int min, int max, int flags)
517 {
518   int signvalue = 0;
519   unsigned LLONG uvalue;
520   char convert[24];
521   int place = 0;
522   int spadlen = 0; /* amount to space pad */
523   int zpadlen = 0; /* amount to zero pad */
524   const char *digits;
525   int total = 0;
526
527   if (max < 0)
528     max = 0;
529
530   uvalue = value;
531
532   if(!(flags & DP_F_UNSIGNED))
533   {
534     if( value < 0 ) {
535       signvalue = '-';
536       uvalue = -value;
537     }
538     else
539       if (flags & DP_F_PLUS)  /* Do a sign (+/i) */
540         signvalue = '+';
541     else
542       if (flags & DP_F_SPACE)
543         signvalue = ' ';
544   }
545
546   if (flags & DP_F_UP)
547     /* Should characters be upper case? */
548     digits = "0123456789ABCDEF";
549   else
550     digits = "0123456789abcdef";
551
552   do {
553     convert[place++] = digits[uvalue % (unsigned)base];
554     uvalue = (uvalue / (unsigned)base );
555   } while(uvalue && (place < sizeof (convert)));
556   if (place == sizeof (convert)) place--;
557   convert[place] = 0;
558
559   zpadlen = max - place;
560   spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
561   if (zpadlen < 0) zpadlen = 0;
562   if (spadlen < 0) spadlen = 0;
563   if (flags & DP_F_ZERO)
564   {
565     zpadlen = MAX(zpadlen, spadlen);
566     spadlen = 0;
567   }
568   if (flags & DP_F_MINUS)
569     spadlen = -spadlen; /* Left Justifty */
570
571 #ifdef DEBUG_SNPRINTF
572   dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
573       zpadlen, spadlen, min, max, place));
574 #endif
575
576   /* Spaces */
577   while (spadlen > 0)
578   {
579     total += dopr_outch (buffer, currlen, maxlen, ' ');
580     --spadlen;
581   }
582
583   /* Sign */
584   if (signvalue)
585     total += dopr_outch (buffer, currlen, maxlen, signvalue);
586
587   /* Zeros */
588   if (zpadlen > 0)
589   {
590     while (zpadlen > 0)
591     {
592       total += dopr_outch (buffer, currlen, maxlen, '0');
593       --zpadlen;
594     }
595   }
596
597   /* Digits */
598   while (place > 0)
599     total += dopr_outch (buffer, currlen, maxlen, convert[--place]);
600
601   /* Left Justified spaces */
602   while (spadlen < 0) {
603     total += dopr_outch (buffer, currlen, maxlen, ' ');
604     ++spadlen;
605   }
606
607   return total;
608 }
609
610 static LDOUBLE abs_val (LDOUBLE value)
611 {
612   LDOUBLE result = value;
613
614   if (value < 0)
615     result = -value;
616
617   return result;
618 }
619
620 static LDOUBLE pow10_int (int exp)
621 {
622   LDOUBLE result = 1;
623
624   while (exp)
625   {
626     result *= 10;
627     exp--;
628   }
629
630   return result;
631 }
632
633 static LLONG round_int (LDOUBLE value)
634 {
635   LLONG intpart;
636
637   intpart = value;
638   value = value - intpart;
639   if (value >= 0.5)
640     intpart++;
641
642   return intpart;
643 }
644
645 static int fmtfp (char *buffer, size_t *currlen, size_t maxlen,
646                   LDOUBLE fvalue, int min, int max, int flags)
647 {
648   int signvalue = 0;
649   LDOUBLE ufvalue;
650   char iconvert[24];
651   char fconvert[24];
652   int iplace = 0;
653   int fplace = 0;
654   int padlen = 0; /* amount to pad */
655   int zpadlen = 0;
656   int total = 0;
657   LLONG intpart;
658   LLONG fracpart;
659   LLONG mask10;
660   int leadingfrac0s = 0; /* zeros at the start of fractional part */
661   int omitzeros = 0;
662   int omitcount = 0;
663
664   /*
665    * AIX manpage says the default is 0, but Solaris says the default
666    * is 6, and sprintf on AIX defaults to 6
667    */
668   if (max < 0)
669     max = 6;
670
671   ufvalue = abs_val (fvalue);
672
673   if (fvalue < 0)
674     signvalue = '-';
675   else
676     if (flags & DP_F_PLUS)  /* Do a sign (+/i) */
677       signvalue = '+';
678     else
679       if (flags & DP_F_SPACE)
680         signvalue = ' ';
681
682 #if 0
683   if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
684 #endif
685
686   intpart = ufvalue;
687
688   /* With %g precision is the number of significant digits, which
689      includes the digits in intpart. */
690   if (flags & DP_F_FP_G)
691     {
692       if (intpart != 0)
693         {
694           /* For each digit of INTPART, print one less fractional digit. */
695           LLONG temp = intpart;
696           for (temp = intpart; temp != 0; temp /= 10)
697             --max;
698           if (max < 0)
699             max = 0;
700         }
701       else
702         {
703           /* For each leading 0 in fractional part, print one more
704              fractional digit. */
705           LDOUBLE temp;
706           if (ufvalue != 0)
707             for (temp = ufvalue; temp < 0.1; temp *= 10)
708               ++max;
709         }
710     }
711
712   /* C99: trailing zeros are removed from the fractional portion of the
713      result unless the # flag is specified */
714   if ((flags & DP_F_FP_G) && !(flags & DP_F_NUM))
715     omitzeros = 1;
716
717 #if SIZEOF_LONG_LONG > 0
718 # define MAX_DIGITS 18          /* grok more digits with long long */
719 #else
720 # define MAX_DIGITS 9           /* just long */
721 #endif
722
723   /*
724    * Sorry, we only support several digits past the decimal because of
725    * our conversion method
726    */
727   if (max > MAX_DIGITS)
728     max = MAX_DIGITS;
729
730   /* Factor of 10 with the needed number of digits, e.g. 1000 for max==3 */
731   mask10 = pow10_int (max);
732
733   /* We "cheat" by converting the fractional part to integer by
734    * multiplying by a factor of 10
735    */
736   fracpart = round_int (mask10 * (ufvalue - intpart));
737
738   if (fracpart >= mask10)
739   {
740     intpart++;
741     fracpart -= mask10;
742   }
743   else if (fracpart != 0)
744     /* If fracpart has less digits than the 10* mask, we need to
745        manually insert leading 0s.  For example 2.01's fractional part
746        requires one leading zero to distinguish it from 2.1. */
747     while (fracpart < mask10 / 10)
748       {
749         ++leadingfrac0s;
750         mask10 /= 10;
751       }
752
753 #ifdef DEBUG_SNPRINTF
754   dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart));
755 #endif
756
757   /* Convert integer part */
758   do {
759     iconvert[iplace++] = '0' + intpart % 10;
760     intpart = (intpart / 10);
761   } while(intpart && (iplace < sizeof(iconvert)));
762   if (iplace == sizeof(iconvert)) iplace--;
763   iconvert[iplace] = 0;
764
765   /* Convert fractional part */
766   do {
767     fconvert[fplace++] = '0' + fracpart % 10;
768     fracpart = (fracpart / 10);
769   } while(fracpart && (fplace < sizeof(fconvert)));
770   while (leadingfrac0s-- > 0 && fplace < sizeof(fconvert))
771     fconvert[fplace++] = '0';
772   if (fplace == sizeof(fconvert)) fplace--;
773   fconvert[fplace] = 0;
774   if (omitzeros)
775     while (omitcount < fplace && fconvert[omitcount] == '0')
776       ++omitcount;
777
778   /* -1 for decimal point, another -1 if we are printing a sign */
779   padlen = min - iplace - (max - omitcount) - 1 - ((signvalue) ? 1 : 0);
780   if (!omitzeros)
781     zpadlen = max - fplace;
782   if (zpadlen < 0)
783     zpadlen = 0;
784   if (padlen < 0)
785     padlen = 0;
786   if (flags & DP_F_MINUS)
787     padlen = -padlen; /* Left Justifty */
788
789   if ((flags & DP_F_ZERO) && (padlen > 0))
790   {
791     if (signvalue)
792     {
793       total += dopr_outch (buffer, currlen, maxlen, signvalue);
794       --padlen;
795       signvalue = 0;
796     }
797     while (padlen > 0)
798     {
799       total += dopr_outch (buffer, currlen, maxlen, '0');
800       --padlen;
801     }
802   }
803   while (padlen > 0)
804   {
805     total += dopr_outch (buffer, currlen, maxlen, ' ');
806     --padlen;
807   }
808   if (signvalue)
809     total += dopr_outch (buffer, currlen, maxlen, signvalue);
810
811   while (iplace > 0)
812     total += dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
813
814   /*
815    * Decimal point.  This should probably use locale to find the correct
816    * char to print out.
817    */
818   if (max > 0 && (fplace > omitcount || zpadlen > 0))
819   {
820     total += dopr_outch (buffer, currlen, maxlen, '.');
821
822     while (fplace > omitcount)
823       total += dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
824   }
825
826   while (zpadlen > 0)
827   {
828     total += dopr_outch (buffer, currlen, maxlen, '0');
829     --zpadlen;
830   }
831
832   while (padlen < 0)
833   {
834     total += dopr_outch (buffer, currlen, maxlen, ' ');
835     ++padlen;
836   }
837
838   return total;
839 }
840
841 static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c)
842 {
843   if (*currlen + 1 < maxlen)
844     buffer[(*currlen)++] = c;
845   return 1;
846 }
847
848 #ifndef HAVE_VSNPRINTF
849 int vsnprintf (char *str, size_t count, const char *fmt, va_list args)
850 {
851   if (str != NULL)
852     str[0] = 0;
853   return dopr(str, count, fmt, args);
854 }
855 #endif /* !HAVE_VSNPRINTF */
856
857 #ifndef HAVE_SNPRINTF
858 int snprintf (char *str, size_t count, const char *fmt,...)
859 {
860   va_list ap;
861   int total;
862
863   va_start (ap, fmt);
864   total = vsnprintf (str, count, fmt, ap);
865   va_end (ap);
866   return total;
867 }
868 #endif /* !HAVE_SNPRINTF */
869 #endif /* !HAVE_SNPRINTF || !HAVE_VSNPRINTF */
870
871 #ifdef TEST_SNPRINTF
872
873 # ifndef LONG_STRING
874 #  define LONG_STRING 1024
875 # endif
876
877 int main (void)
878 {
879   char buf1[LONG_STRING];
880   char buf2[LONG_STRING];
881   char *fp_fmt[] = {
882     /* %f formats */
883     "%f",
884     "%-1.5f",
885     "%1.5f",
886     "%123.9f",
887     "%10.5f",
888     "% 10.5f",
889     "%+22.9f",
890     "%+4.9f",
891     "%01.3f",
892     "%4f",
893     "%3.1f",
894     "%3.2f",
895     "%.0f",
896     "%.1f",
897     "%#10.1f",
898 #if SIZEOF_LONG_LONG != 0
899     "%.16f",
900     "%18.16f",
901     "%-16.16f",
902 #endif
903     /* %g formats */
904     "%g",
905     "%1.5g",
906     "%-1.5g",
907     "%.9g",
908     "%123.9g",
909     "%#123.9g",
910 #if SIZEOF_LONG_LONG != 0
911     "%.16g",
912     "%20.16g",
913 #endif
914     NULL
915   };
916   double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996,
917                        0.9996, 1.996, 4.136, 0.00205, 0.0001, 321.000009,
918                        0};
919   char *int_fmt[] = {
920     "%-1.5d",
921     "%1.5d",
922     "%123.9d",
923     "%5.5d",
924     "%10.5d",
925     "% 10.5d",
926     "%+22.33d",
927     "%01.3d",
928     "%4d",
929     NULL
930   };
931   long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
932 #if SIZEOF_LONG_LONG != 0
933   char *llong_fmt[] = {
934     "%lld",             "%llu",
935     "%-1.5lld",         "%-1.5llu",
936     "%1.5lld",          "%1.5llu",
937     "%123.9lld",        "%123.9llu",
938     "%5.5lld",          "%5.5llu",
939     "%10.5lld",         "%10.5llu",
940     "% 10.5lld",        "% 10.5llu",
941     "%+22.33lld",       "%+22.33llu",
942     "%01.3lld",         "%01.3llu",
943     "%4lld",            "%4llu",
944     NULL
945   };
946   long long llong_nums[] = {
947     ~(long long)0,              /* all-1 bit pattern */
948     (~(unsigned long long)0) >> 1, /* largest signed long long */
949     /* random... */
950     -150, 134, 91340, 341,
951     0
952   };
953 #endif
954   int x, y;
955   int fail = 0;
956   int num = 0;
957
958   printf ("Testing snprintf format codes against system sprintf...\n");
959
960   for (x = 0; fp_fmt[x] != NULL ; x++)
961     for (y = 0; fp_nums[y] != 0 ; y++)
962     {
963       snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]);
964       sprintf (buf2, fp_fmt[x], fp_nums[y]);
965       if (strcmp (buf1, buf2))
966       {
967         printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf  = %s\n",
968             fp_fmt[x], buf1, buf2);
969         fail++;
970       }
971       num++;
972     }
973
974   for (x = 0; int_fmt[x] != NULL ; x++)
975     for (y = 0; int_nums[y] != 0 ; y++)
976     {
977       snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]);
978       sprintf (buf2, int_fmt[x], int_nums[y]);
979       if (strcmp (buf1, buf2))
980       {
981         printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf  = %s\n",
982             int_fmt[x], buf1, buf2);
983         fail++;
984       }
985       num++;
986     }
987
988 #if SIZEOF_LONG_LONG != 0
989   for (x = 0; llong_fmt[x] != NULL ; x++)
990     for (y = 0; llong_nums[y] != 0 ; y++)
991     {
992       snprintf (buf1, sizeof (buf1), llong_fmt[x], llong_nums[y]);
993       sprintf (buf2, llong_fmt[x], llong_nums[y]);
994       if (strcmp (buf1, buf2))
995       {
996         printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf  = %s\n",
997             llong_fmt[x], buf1, buf2);
998         fail++;
999       }
1000       num++;
1001     }
1002 #endif
1003
1004   printf ("%d tests failed out of %d.\n", fail, num);
1005   return 0;
1006 }
1007 #endif /* TEST_SNPRINTF */