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