GSS_S_PROMPTING_NEEDED is a bit
[cyrus-sasl.git] / lib / snprintf.c
1 /**************************************************************
2  * Original:
3  * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
4  * A bombproof version of doprnt (dopr) included.
5  * Sigh.  This sort of thing is always nasty do deal with.  Note that
6  * the version here does not include floating point...
7  *
8  * snprintf() is used instead of sprintf() as it does limit checks
9  * for string length.  This covers a nasty loophole.
10  *
11  * The other functions are there to prevent NULL pointers from
12  * causing nast effects.
13  *
14  * More Recently:
15  *  Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43
16  *  This was ugly.  It is still ugly.  I opted out of floating point
17  *  numbers, but the formatter understands just about everything
18  *  from the normal C string format, at least as far as I can tell from
19  *  the Solaris 2.5 printf(3S) man page.
20  *
21  *  Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1
22  *    Ok, added some minimal floating point support, which means this
23  *    probably requires libm on most operating systems.  Don't yet
24  *    support the exponent (e,E) and sigfig (g,G).  Also, fmtint()
25  *    was pretty badly broken, it just wasn't being exercised in ways
26  *    which showed it, so that's been fixed.  Also, formated the code
27  *    to mutt conventions, and removed dead code left over from the
28  *    original.  Also, there is now a builtin-test, just compile with:
29  *           gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm
30  *    and run snprintf for results.
31  * 
32  *  Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i
33  *    The PGP code was using unsigned hexadecimal formats. 
34  *    Unfortunately, unsigned formats simply didn't work.
35  *
36  *  Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8
37  *    The original code assumed that both snprintf() and vsnprintf() were
38  *    missing.  Some systems only have snprintf() but not vsnprintf(), so
39  *    the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
40  *
41  **************************************************************/
42
43 #include <config.h>
44
45 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF)
46
47 #include <string.h>
48 # include <ctype.h>
49 #include <sys/types.h>
50
51 /* varargs declarations: */
52
53 #if defined(HAVE_STDARG_H)
54 # include <stdarg.h>
55 # define HAVE_STDARGS    /* let's hope that works everywhere (mj) */
56 # define VA_LOCAL_DECL   va_list ap
57 # define VA_START(f)     va_start(ap, f)
58 # define VA_SHIFT(v,t)  ;   /* no-op for ANSI */
59 # define VA_END          va_end(ap)
60 #else
61 # if defined(HAVE_VARARGS_H)
62 #  include <varargs.h>
63 #  undef HAVE_STDARGS
64 #  define VA_LOCAL_DECL   va_list ap
65 #  define VA_START(f)     va_start(ap)      /* f is ignored! */
66 #  define VA_SHIFT(v,t) v = va_arg(ap,t)
67 #  define VA_END        va_end(ap)
68 # else
69 /*XX ** NO VARARGS ** XX*/
70 # endif
71 #endif
72
73 /*int snprintf (char *str, size_t count, const char *fmt, ...);*/
74 /*int vsnprintf (char *str, size_t count, const char *fmt, va_list arg);*/
75
76 static void dopr (char *buffer, size_t maxlen, const char *format, 
77                   va_list args);
78 static void fmtstr (char *buffer, size_t *currlen, size_t maxlen,
79                     char *value, int flags, int min, int max);
80 static void fmtint (char *buffer, size_t *currlen, size_t maxlen,
81                     long value, int base, int min, int max, int flags);
82 static void fmtfp (char *buffer, size_t *currlen, size_t maxlen,
83                    long double fvalue, int min, int max, int flags);
84 static void dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c );
85
86 /*
87  * dopr(): poor man's version of doprintf
88  */
89
90 /* format read states */
91 #define DP_S_DEFAULT 0
92 #define DP_S_FLAGS   1
93 #define DP_S_MIN     2
94 #define DP_S_DOT     3
95 #define DP_S_MAX     4
96 #define DP_S_MOD     5
97 #define DP_S_CONV    6
98 #define DP_S_DONE    7
99
100 /* format flags - Bits */
101 #define DP_F_MINUS      (1 << 0)
102 #define DP_F_PLUS       (1 << 1)
103 #define DP_F_SPACE      (1 << 2)
104 #define DP_F_NUM        (1 << 3)
105 #define DP_F_ZERO       (1 << 4)
106 #define DP_F_UP         (1 << 5)
107 #define DP_F_UNSIGNED   (1 << 6)
108
109 /* Conversion Flags */
110 #define DP_C_SHORT   1
111 #define DP_C_LONG    2
112 #define DP_C_LDOUBLE 3
113
114 #define char_to_int(p) (p - '0')
115 #define MAX(p,q) ((p >= q) ? p : q)
116
117 static void dopr (char *buffer, size_t maxlen, const char *format, va_list args)
118 {
119   char ch;
120   long value;
121   long double fvalue;
122   char *strvalue;
123   int min;
124   int max;
125   int state;
126   int flags;
127   int cflags;
128   size_t currlen;
129   
130   state = DP_S_DEFAULT;
131   currlen = flags = cflags = min = 0;
132   max = -1;
133   ch = *format++;
134
135   while (state != DP_S_DONE)
136   {
137     if ((ch == '\0') || (currlen >= maxlen)) 
138       state = DP_S_DONE;
139
140     switch(state) 
141     {
142     case DP_S_DEFAULT:
143       if (ch == '%') 
144         state = DP_S_FLAGS;
145       else 
146         dopr_outch (buffer, &currlen, maxlen, ch);
147       ch = *format++;
148       break;
149     case DP_S_FLAGS:
150       switch (ch) 
151       {
152       case '-':
153         flags |= DP_F_MINUS;
154         ch = *format++;
155         break;
156       case '+':
157         flags |= DP_F_PLUS;
158         ch = *format++;
159         break;
160       case ' ':
161         flags |= DP_F_SPACE;
162         ch = *format++;
163         break;
164       case '#':
165         flags |= DP_F_NUM;
166         ch = *format++;
167         break;
168       case '0':
169         flags |= DP_F_ZERO;
170         ch = *format++;
171         break;
172       default:
173         state = DP_S_MIN;
174         break;
175       }
176       break;
177     case DP_S_MIN:
178       if (isdigit((unsigned char)ch)) 
179       {
180         min = 10*min + char_to_int (ch);
181         ch = *format++;
182       } 
183       else if (ch == '*') 
184       {
185         min = va_arg (args, int);
186         ch = *format++;
187         state = DP_S_DOT;
188       } 
189       else 
190         state = DP_S_DOT;
191       break;
192     case DP_S_DOT:
193       if (ch == '.') 
194       {
195         state = DP_S_MAX;
196         ch = *format++;
197       } 
198       else 
199         state = DP_S_MOD;
200       break;
201     case DP_S_MAX:
202       if (isdigit((unsigned char)ch)) 
203       {
204         if (max < 0)
205           max = 0;
206         max = 10*max + char_to_int (ch);
207         ch = *format++;
208       } 
209       else if (ch == '*') 
210       {
211         max = va_arg (args, int);
212         ch = *format++;
213         state = DP_S_MOD;
214       } 
215       else 
216         state = DP_S_MOD;
217       break;
218     case DP_S_MOD:
219       /* Currently, we don't support Long Long, bummer */
220       switch (ch) 
221       {
222       case 'h':
223         cflags = DP_C_SHORT;
224         ch = *format++;
225         break;
226       case 'l':
227         cflags = DP_C_LONG;
228         ch = *format++;
229         break;
230       case 'L':
231         cflags = DP_C_LDOUBLE;
232         ch = *format++;
233         break;
234       default:
235         break;
236       }
237       state = DP_S_CONV;
238       break;
239     case DP_S_CONV:
240       switch (ch) 
241       {
242       case 'd':
243       case 'i':
244         if (cflags == DP_C_SHORT) 
245           value = va_arg (args, short int);
246         else if (cflags == DP_C_LONG)
247           value = va_arg (args, long int);
248         else
249           value = va_arg (args, int);
250         fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
251         break;
252       case 'o':
253         flags |= DP_F_UNSIGNED;
254         if (cflags == DP_C_SHORT)
255           value = va_arg (args, unsigned short int);
256         else if (cflags == DP_C_LONG)
257           value = va_arg (args, unsigned long int);
258         else
259           value = va_arg (args, unsigned int);
260         fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
261         break;
262       case 'u':
263         flags |= DP_F_UNSIGNED;
264         if (cflags == DP_C_SHORT)
265           value = va_arg (args, unsigned short int);
266         else if (cflags == DP_C_LONG)
267           value = va_arg (args, unsigned long int);
268         else
269           value = va_arg (args, unsigned int);
270         fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
271         break;
272       case 'X':
273         flags |= DP_F_UP;
274       case 'x':
275         flags |= DP_F_UNSIGNED;
276         if (cflags == DP_C_SHORT)
277           value = va_arg (args, unsigned short int);
278         else if (cflags == DP_C_LONG)
279           value = va_arg (args, unsigned long int);
280         else
281           value = va_arg (args, unsigned int);
282         fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
283         break;
284       case 'f':
285         if (cflags == DP_C_LDOUBLE)
286           fvalue = va_arg (args, long double);
287         else
288           fvalue = va_arg (args, double);
289         /* um, floating point? */
290         fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
291         break;
292       case 'E':
293         flags |= DP_F_UP;
294       case 'e':
295         if (cflags == DP_C_LDOUBLE)
296           fvalue = va_arg (args, long double);
297         else
298           fvalue = va_arg (args, double);
299         break;
300       case 'G':
301         flags |= DP_F_UP;
302       case 'g':
303         if (cflags == DP_C_LDOUBLE)
304           fvalue = va_arg (args, long double);
305         else
306           fvalue = va_arg (args, double);
307         break;
308       case 'c':
309         dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
310         break;
311       case 's':
312         strvalue = va_arg (args, char *);
313         if (max < 0) 
314           max = maxlen; /* ie, no max */
315         fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
316         break;
317       case 'p':
318         strvalue = va_arg (args, void *);
319         fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min, max, flags);
320         break;
321       case 'n':
322         if (cflags == DP_C_SHORT) 
323         {
324           short int *num;
325           num = va_arg (args, short int *);
326           *num = currlen;
327         } 
328         else if (cflags == DP_C_LONG) 
329         {
330           long int *num;
331           num = va_arg (args, long int *);
332           *num = currlen;
333         } 
334         else 
335         {
336           int *num;
337           num = va_arg (args, int *);
338           *num = currlen;
339         }
340         break;
341       case '%':
342         dopr_outch (buffer, &currlen, maxlen, ch);
343         break;
344       case 'w':
345         /* not supported yet, treat as next char */
346         ch = *format++;
347         break;
348       default:
349         /* Unknown, skip */
350         break;
351       }
352       ch = *format++;
353       state = DP_S_DEFAULT;
354       flags = cflags = min = 0;
355       max = -1;
356       break;
357     case DP_S_DONE:
358       break;
359     default:
360       /* hmm? */
361       break; /* some picky compilers need this */
362     }
363   }
364   if (currlen < maxlen - 1) 
365     buffer[currlen] = '\0';
366   else 
367     buffer[maxlen - 1] = '\0';
368 }
369
370 static void fmtstr (char *buffer, size_t *currlen, size_t maxlen,
371                     char *value, int flags, int min, int max)
372 {
373   int padlen, strln;     /* amount to pad */
374   int cnt = 0;
375   
376   if (value == 0)
377   {
378     value = "<NULL>";
379   }
380
381   for (strln = 0; value[strln]; ++strln); /* strlen */
382   padlen = min - strln;
383   if (padlen < 0) 
384     padlen = 0;
385   if (flags & DP_F_MINUS) 
386     padlen = -padlen; /* Left Justify */
387
388   while ((padlen > 0) && (cnt < max)) 
389   {
390     dopr_outch (buffer, currlen, maxlen, ' ');
391     --padlen;
392     ++cnt;
393   }
394   while (*value && (cnt < max)) 
395   {
396     dopr_outch (buffer, currlen, maxlen, *value++);
397     ++cnt;
398   }
399   while ((padlen < 0) && (cnt < max)) 
400   {
401     dopr_outch (buffer, currlen, maxlen, ' ');
402     ++padlen;
403     ++cnt;
404   }
405 }
406
407 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
408
409 static void fmtint (char *buffer, size_t *currlen, size_t maxlen,
410                     long value, int base, int min, int max, int flags)
411 {
412   int signvalue = 0;
413   unsigned long uvalue;
414   char convert[20];
415   int place = 0;
416   int spadlen = 0; /* amount to space pad */
417   int zpadlen = 0; /* amount to zero pad */
418   int caps = 0;
419   
420   if (max < 0)
421     max = 0;
422
423   uvalue = value;
424
425   if(!(flags & DP_F_UNSIGNED))
426   {
427     if( value < 0 ) {
428       signvalue = '-';
429       uvalue = -value;
430     }
431     else
432       if (flags & DP_F_PLUS)  /* Do a sign (+/i) */
433         signvalue = '+';
434     else
435       if (flags & DP_F_SPACE)
436         signvalue = ' ';
437   }
438   
439   if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
440
441   do {
442     convert[place++] =
443       (caps? "0123456789ABCDEF":"0123456789abcdef")
444       [uvalue % (unsigned)base  ];
445     uvalue = (uvalue / (unsigned)base );
446   } while(uvalue && (place < 20));
447   if (place == 20) place--;
448   convert[place] = 0;
449
450   zpadlen = max - place;
451   spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
452   if (zpadlen < 0) zpadlen = 0;
453   if (spadlen < 0) spadlen = 0;
454   if (flags & DP_F_ZERO)
455   {
456     zpadlen = MAX(zpadlen, spadlen);
457     spadlen = 0;
458   }
459   if (flags & DP_F_MINUS) 
460     spadlen = -spadlen; /* Left Justifty */
461
462 #ifdef DEBUG_SNPRINTF
463   dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
464       zpadlen, spadlen, min, max, place));
465 #endif
466
467   /* Spaces */
468   while (spadlen > 0) 
469   {
470     dopr_outch (buffer, currlen, maxlen, ' ');
471     --spadlen;
472   }
473
474   /* Sign */
475   if (signvalue) 
476     dopr_outch (buffer, currlen, maxlen, signvalue);
477
478   /* Zeros */
479   if (zpadlen > 0) 
480   {
481     while (zpadlen > 0)
482     {
483       dopr_outch (buffer, currlen, maxlen, '0');
484       --zpadlen;
485     }
486   }
487
488   /* Digits */
489   while (place > 0) 
490     dopr_outch (buffer, currlen, maxlen, convert[--place]);
491   
492   /* Left Justified spaces */
493   while (spadlen < 0) {
494     dopr_outch (buffer, currlen, maxlen, ' ');
495     ++spadlen;
496   }
497 }
498
499 static long double abs_val (long double value)
500 {
501   long double result = value;
502
503   if (value < 0)
504     result = -value;
505
506   return result;
507 }
508
509 static long double pow10 (int exp)
510 {
511   long double result = 1;
512
513   while (exp)
514   {
515     result *= 10;
516     exp--;
517   }
518   
519   return result;
520 }
521
522 static long round (long double value)
523 {
524   long intpart;
525
526   intpart = value;
527   value = value - intpart;
528   if (value >= 0.5)
529     intpart++;
530
531   return intpart;
532 }
533
534 static void fmtfp (char *buffer, size_t *currlen, size_t maxlen,
535                    long double fvalue, int min, int max, int flags)
536 {
537   int signvalue = 0;
538   long double ufvalue;
539   char iconvert[20];
540   char fconvert[20];
541   int iplace = 0;
542   int fplace = 0;
543   int padlen = 0; /* amount to pad */
544   int zpadlen = 0; 
545   int caps = 0;
546   long intpart;
547   long fracpart;
548   
549   /* 
550    * AIX manpage says the default is 0, but Solaris says the default
551    * is 6, and sprintf on AIX defaults to 6
552    */
553   if (max < 0)
554     max = 6;
555
556   ufvalue = abs_val (fvalue);
557
558   if (fvalue < 0)
559     signvalue = '-';
560   else
561     if (flags & DP_F_PLUS)  /* Do a sign (+/i) */
562       signvalue = '+';
563     else
564       if (flags & DP_F_SPACE)
565         signvalue = ' ';
566
567 #if 0
568   if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
569 #endif
570
571   intpart = ufvalue;
572
573   /* 
574    * Sorry, we only support 9 digits past the decimal because of our 
575    * conversion method
576    */
577   if (max > 9)
578     max = 9;
579
580   /* We "cheat" by converting the fractional part to integer by
581    * multiplying by a factor of 10
582    */
583   fracpart = round ((pow10 (max)) * (ufvalue - intpart));
584
585   if (fracpart >= pow10 (max))
586   {
587     intpart++;
588     fracpart -= pow10 (max);
589   }
590
591 #ifdef DEBUG_SNPRINTF
592   dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart));
593 #endif
594
595   /* Convert integer part */
596   do {
597     iconvert[iplace++] =
598       (caps? "0123456789ABCDEF":"0123456789abcdef")[intpart % 10];
599     intpart = (intpart / 10);
600   } while(intpart && (iplace < 20));
601   if (iplace == 20) iplace--;
602   iconvert[iplace] = 0;
603
604   /* Convert fractional part */
605   do {
606     fconvert[fplace++] =
607       (caps? "0123456789ABCDEF":"0123456789abcdef")[fracpart % 10];
608     fracpart = (fracpart / 10);
609   } while(fracpart && (fplace < 20));
610   if (fplace == 20) fplace--;
611   fconvert[fplace] = 0;
612
613   /* -1 for decimal point, another -1 if we are printing a sign */
614   padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0); 
615   zpadlen = max - fplace;
616   if (zpadlen < 0)
617     zpadlen = 0;
618   if (padlen < 0) 
619     padlen = 0;
620   if (flags & DP_F_MINUS) 
621     padlen = -padlen; /* Left Justifty */
622
623   if ((flags & DP_F_ZERO) && (padlen > 0)) 
624   {
625     if (signvalue) 
626     {
627       dopr_outch (buffer, currlen, maxlen, signvalue);
628       --padlen;
629       signvalue = 0;
630     }
631     while (padlen > 0)
632     {
633       dopr_outch (buffer, currlen, maxlen, '0');
634       --padlen;
635     }
636   }
637   while (padlen > 0)
638   {
639     dopr_outch (buffer, currlen, maxlen, ' ');
640     --padlen;
641   }
642   if (signvalue) 
643     dopr_outch (buffer, currlen, maxlen, signvalue);
644
645   while (iplace > 0) 
646     dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
647
648   /*
649    * Decimal point.  This should probably use locale to find the correct
650    * char to print out.
651    */
652   dopr_outch (buffer, currlen, maxlen, '.');
653
654   while (fplace > 0) 
655     dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
656
657   while (zpadlen > 0)
658   {
659     dopr_outch (buffer, currlen, maxlen, '0');
660     --zpadlen;
661   }
662
663   while (padlen < 0) 
664   {
665     dopr_outch (buffer, currlen, maxlen, ' ');
666     ++padlen;
667   }
668 }
669
670 static void dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c)
671 {
672   if (*currlen < maxlen)
673     buffer[(*currlen)++] = c;
674 }
675 #endif /* !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF) */
676
677 #ifndef HAVE_VSNPRINTF
678 int vsnprintf (char *str, size_t count, const char *fmt, va_list args)
679 {
680   str[0] = 0;
681   dopr(str, count, fmt, args);
682   return(strlen(str));
683 }
684 #endif /* !HAVE_VSNPRINTF */
685
686 #ifndef HAVE_SNPRINTF
687 /* VARARGS3 */
688 #ifdef HAVE_STDARGS
689 int snprintf (char *str,size_t count,const char *fmt,...)
690 #else
691 int snprintf (va_alist) va_dcl
692 #endif
693 {
694 #ifndef HAVE_STDARGS
695   char *str;
696   size_t count;
697   char *fmt;
698 #endif
699   VA_LOCAL_DECL;
700     
701   VA_START (fmt);
702   VA_SHIFT (str, char *);
703   VA_SHIFT (count, size_t );
704   VA_SHIFT (fmt, char *);
705   (void) vsnprintf(str, count, fmt, ap);
706   VA_END;
707   return(strlen(str));
708 }
709
710 #ifdef TEST_SNPRINTF
711 #ifndef LONG_STRING
712 #define LONG_STRING 1024
713 #endif
714 int main (void)
715 {
716   char buf1[LONG_STRING];
717   char buf2[LONG_STRING];
718   char *fp_fmt[] = {
719     "%-1.5f",
720     "%1.5f",
721     "%123.9f",
722     "%10.5f",
723     "% 10.5f",
724     "%+22.9f",
725     "%+4.9f",
726     "%01.3f",
727     "%4f",
728     "%3.1f",
729     "%3.2f",
730     NULL
731   };
732   double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996, 
733     0.9996, 1.996, 4.136, 0};
734   char *int_fmt[] = {
735     "%-1.5d",
736     "%1.5d",
737     "%123.9d",
738     "%5.5d",
739     "%10.5d",
740     "% 10.5d",
741     "%+22.33d",
742     "%01.3d",
743     "%4d",
744     NULL
745   };
746   long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
747   int x, y;
748   int fail = 0;
749   int num = 0;
750
751   printf ("Testing snprintf format codes against system sprintf...\n");
752
753   for (x = 0; fp_fmt[x] != NULL ; x++)
754     for (y = 0; fp_nums[y] != 0 ; y++)
755     {
756       snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]);
757       sprintf (buf2, fp_fmt[x], fp_nums[y]);
758       if (strcmp (buf1, buf2))
759       {
760         printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf  = %s\n", 
761             fp_fmt[x], buf1, buf2);
762         fail++;
763       }
764       num++;
765     }
766
767   for (x = 0; int_fmt[x] != NULL ; x++)
768     for (y = 0; int_nums[y] != 0 ; y++)
769     {
770       snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]);
771       sprintf (buf2, int_fmt[x], int_nums[y]);
772       if (strcmp (buf1, buf2))
773       {
774         printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf  = %s\n", 
775             int_fmt[x], buf1, buf2);
776         fail++;
777       }
778       num++;
779     }
780   printf ("%d tests failed out of %d.\n", fail, num);
781 }
782 #endif /* SNPRINTF_TEST */
783
784 #endif /* !HAVE_SNPRINTF */