1 /****************************************************************************
5 *************************************************************************
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
12 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
13 * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND
14 * CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER.
17 * A merge of Bjorn Reese's format() function and Daniel's dsprintf()
18 * 1.0. A full blooded printf() clone with full support for <num>$
19 * everywhere (parameters, widths and precisions) including variabled
20 * sized parameters (like doubles, long longs, long doubles and even
21 * void * in 64-bit architectures).
23 * Current restrictions:
24 * - Max 128 parameters
25 * - No 'long double' support.
27 * If you ever want truly portable and good *printf() clones, the project that
28 * took on from here is named 'Trio' and you find more details on the trio web
29 * page at http://daniel.haxx.se/trio/
34 #include <sys/types.h>
41 #include <curl/mprintf.h>
43 #ifndef SIZEOF_LONG_DOUBLE
44 #define SIZEOF_LONG_DOUBLE 0
49 #define LONG_LONG long long
53 /* The last #include file should be: */
58 #define BUFFSIZE 256 /* buffer for long-to-str and float-to-str calcs */
59 #define MAX_PARAMETERS 128 /* lame static limit */
69 # define TRUE ((char)(1 == 1))
70 # define FALSE ((char)(0 == 1))
75 /* Lower-case digits. */
76 static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
78 /* Upper-case digits. */
79 static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
81 #define OUTCHAR(x) done+=(stream(x, (FILE *)data)==-1?0:1)
83 /* Data type to read from the arglist */
94 FORMAT_WIDTH /* For internal use */
97 /* convertion and display flags */
101 FLAGS_SHOWSIGN = 1<<1,
106 FLAGS_LONGLONG = 1<<6,
107 FLAGS_LONGDOUBLE = 1<<7,
108 FLAGS_PAD_NIL = 1<<8,
109 FLAGS_UNSIGNED = 1<<9,
113 FLAGS_WIDTH = 1<<13, /* '*' or '*<num>$' used */
114 FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */
115 FLAGS_PREC = 1<<15, /* precision was specified */
116 FLAGS_PRECPARAM = 1<<16, /* precision PARAMETER was specified */
117 FLAGS_CHAR = 1<<17, /* %c story */
118 FLAGS_FLOATE = 1<<18, /* %e or %E */
119 FLAGS_FLOATG = 1<<19 /* %g or %G */
125 int width; /* width OR width parameter number */
126 int precision; /* precision OR precision parameter number */
135 #if 0 /*SIZEOF_LONG_DOUBLE */
148 char *buffer; /* allocated buffer */
149 size_t len; /* length of string */
150 size_t alloc; /* length of alloc */
153 int curl_msprintf(char *buffer, const char *format, ...);
155 static int dprintf_DollarString(char *input, char **end)
158 while(isdigit((int)*input)) {
160 number += *input-'0';
163 if(number && ('$'==*input++)) {
170 static BOOL dprintf_IsQualifierNoDollar(char c)
173 case '-': case '+': case ' ': case '#': case '.':
174 case '0': case '1': case '2': case '3': case '4':
175 case '5': case '6': case '7': case '8': case '9':
176 case 'h': case 'l': case 'L': case 'z': case 'q':
184 #ifdef DPRINTF_DEBUG2
185 int dprintf_Pass1Report(va_stack_t *vto, int max)
192 for(i=0; i<max; i++) {
194 switch(vto[i].type) {
210 case FORMAT_LONGLONG:
216 case FORMAT_LONGDOUBLE:
217 type = "long double";
224 for(bit=0; bit<31; bit++) {
225 flags = vto[i].flags & (1<<bit);
227 if(flags & FLAGS_SPACE)
228 strcat(buffer, "space ");
229 else if(flags & FLAGS_SHOWSIGN)
230 strcat(buffer, "plus ");
231 else if(flags & FLAGS_LEFT)
232 strcat(buffer, "left ");
233 else if(flags & FLAGS_ALT)
234 strcat(buffer, "alt ");
235 else if(flags & FLAGS_SHORT)
236 strcat(buffer, "short ");
237 else if(flags & FLAGS_LONG)
238 strcat(buffer, "long ");
239 else if(flags & FLAGS_LONGLONG)
240 strcat(buffer, "longlong ");
241 else if(flags & FLAGS_LONGDOUBLE)
242 strcat(buffer, "longdouble ");
243 else if(flags & FLAGS_PAD_NIL)
244 strcat(buffer, "padnil ");
245 else if(flags & FLAGS_UNSIGNED)
246 strcat(buffer, "unsigned ");
247 else if(flags & FLAGS_OCTAL)
248 strcat(buffer, "octal ");
249 else if(flags & FLAGS_HEX)
250 strcat(buffer, "hex ");
251 else if(flags & FLAGS_UPPER)
252 strcat(buffer, "upper ");
253 else if(flags & FLAGS_WIDTH)
254 strcat(buffer, "width ");
255 else if(flags & FLAGS_WIDTHPARAM)
256 strcat(buffer, "widthparam ");
257 else if(flags & FLAGS_PREC)
258 strcat(buffer, "precision ");
259 else if(flags & FLAGS_PRECPARAM)
260 strcat(buffer, "precparam ");
261 else if(flags & FLAGS_CHAR)
262 strcat(buffer, "char ");
263 else if(flags & FLAGS_FLOATE)
264 strcat(buffer, "floate ");
265 else if(flags & FLAGS_FLOATG)
266 strcat(buffer, "floatg ");
268 printf("REPORT: %d. %s [%s]\n", i, type, buffer);
276 /******************************************************************
279 * Create an index with the type of each parameter entry and its
280 * value (may vary in size)
282 ******************************************************************/
284 static int dprintf_Pass1(char *format, va_stack_t *vto, char **endpos, va_list arglist)
299 continue; /* while */
304 /* Handle the positional case (N$) */
308 this_param = dprintf_DollarString(fmt, &fmt);
310 /* we got no positional, get the next counter */
311 this_param = param_num;
313 if (this_param > max_param)
314 max_param = this_param;
317 * The parameter with number 'i' should be used. Next, we need
318 * to get SIZE and TYPE of the parameter. Add the information
325 /* Handle the flags */
327 while (dprintf_IsQualifierNoDollar(*fmt)) {
330 flags |= FLAGS_SPACE;
333 flags |= FLAGS_SHOWSIGN;
337 flags &= ~FLAGS_PAD_NIL;
345 /* The precision is picked from a specified parameter */
347 flags |= FLAGS_PRECPARAM;
351 i = dprintf_DollarString(fmt, &fmt);
355 precision = param_num;
357 if (precision > max_param)
358 max_param = precision;
362 precision = strtol(fmt, &fmt, 10);
366 flags |= FLAGS_SHORT;
369 if (flags & FLAGS_LONG)
370 flags |= FLAGS_LONGLONG;
375 flags |= FLAGS_LONGDOUBLE;
378 flags |= FLAGS_LONGLONG;
381 /* the code below generates a warning if -Wunreachable-code is
383 if (sizeof(size_t) > sizeof(unsigned long))
384 flags |= FLAGS_LONGLONG;
385 if (sizeof(size_t) > sizeof(unsigned int))
389 #if SIZEOF_CURL_OFF_T > 4
390 flags |= FLAGS_LONGLONG;
396 if (!(flags & FLAGS_LEFT))
397 flags |= FLAGS_PAD_NIL;
399 case '1': case '2': case '3': case '4':
400 case '5': case '6': case '7': case '8': case '9':
401 flags |= FLAGS_WIDTH;
402 width = strtol(fmt-1, &fmt, 10);
404 case '*': /* Special case */
405 flags |= FLAGS_WIDTHPARAM;
408 i = dprintf_DollarString(fmt, &fmt);
413 if(width > max_param)
421 /* Handle the specifier */
430 vto[i].type = FORMAT_STRING;
433 vto[i].type = FORMAT_INTPTR;
436 vto[i].type = FORMAT_PTR;
439 vto[i].type = FORMAT_INT;
442 vto[i].type = FORMAT_INT;
443 flags |= FLAGS_UNSIGNED;
446 vto[i].type = FORMAT_INT;
447 flags |= FLAGS_OCTAL;
450 vto[i].type = FORMAT_INT;
454 vto[i].type = FORMAT_INT;
455 flags |= FLAGS_HEX|FLAGS_UPPER;
458 vto[i].type = FORMAT_INT;
462 vto[i].type = FORMAT_DOUBLE;
465 vto[i].type = FORMAT_DOUBLE;
466 flags |= FLAGS_FLOATE| (('E' == *fmt)?FLAGS_UPPER:0);
469 vto[i].type = FORMAT_DOUBLE;
470 flags |= FLAGS_FLOATG| (('G' == *fmt)?FLAGS_UPPER:0);
473 vto[i].type = FORMAT_UNKNOWN;
477 vto[i].flags = flags;
478 vto[i].width = width;
479 vto[i].precision = precision;
481 if (flags & FLAGS_WIDTHPARAM) {
482 /* we have the width specified from a parameter, so we make that
483 parameter's info setup properly */
484 vto[i].width = width - 1;
486 vto[i].type = FORMAT_WIDTH;
487 vto[i].flags = FLAGS_NEW;
488 vto[i].precision = vto[i].width = 0; /* can't use width or precision
491 if (flags & FLAGS_PRECPARAM) {
492 /* we have the precision specified from a parameter, so we make that
493 parameter's info setup properly */
494 vto[i].precision = precision - 1;
496 vto[i].type = FORMAT_WIDTH;
497 vto[i].flags = FLAGS_NEW;
498 vto[i].precision = vto[i].width = 0; /* can't use width or precision
501 *endpos++ = fmt + 1; /* end of this sequence */
505 #ifdef DPRINTF_DEBUG2
506 dprintf_Pass1Report(vto, max_param);
509 /* Read the arg list parameters into our data list */
510 for (i=0; i<max_param; i++) {
511 if ((i + 1 < max_param) && (vto[i + 1].type == FORMAT_WIDTH))
513 /* Width/precision arguments must be read before the main argument
514 * they are attached to
516 vto[i + 1].data.num = va_arg(arglist, int);
522 vto[i].data.str = va_arg(arglist, char *);
528 vto[i].data.ptr = va_arg(arglist, void *);
533 if(vto[i].flags & FLAGS_LONGLONG)
534 vto[i].data.lnum = va_arg(arglist, LONG_LONG);
537 if(vto[i].flags & FLAGS_LONG)
538 vto[i].data.num = va_arg(arglist, long);
540 vto[i].data.num = va_arg(arglist, int);
544 #if 0 /*SIZEOF_LONG_DOUBLE */
545 if(vto[i].flags & FLAGS_LONG)
546 vto[i].data.ldnum = va_arg(arglist, long double);
549 vto[i].data.dnum = va_arg(arglist, double);
553 /* Argument has been read. Silently convert it into an integer
556 vto[i].type = FORMAT_INT;
568 static int dprintf_formatf(
569 void *data, /* untouched by format(), just sent to the
570 stream() function in the first argument */
571 int (*stream)(int, FILE *), /* function pointer called for each
573 const char *format, /* %-formatted string */
574 va_list ap_save) /* list of parameters */
576 /* Base-36 digits for numbers. */
577 const char *digits = lower_digits;
579 /* Pointer into the format string. */
582 /* Number of characters written. */
583 register size_t done = 0;
585 long param; /* current parameter to read */
586 long param_num=0; /* parameter counter */
588 va_stack_t vto[MAX_PARAMETERS];
589 char *endpos[MAX_PARAMETERS];
596 /* Do the actual %-code parsing */
597 dprintf_Pass1((char *)format, vto, endpos, ap_save);
599 end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
604 /* Format spec modifiers. */
607 /* Width of a field. */
610 /* Precision of a field. */
613 /* Decimal integer is negative. */
616 /* Base of a number to be written. */
619 /* Integral values to be written. */
621 unsigned LONG_LONG num;
628 /* This isn't a format spec, so write everything out until the next one
629 OR end of string is reached. */
632 } while(*++f && ('%' != *f));
638 /* Check for "%%". Note that although the ANSI standard lists
639 '%' as a conversion specifier, it says "The complete format
640 specification shall be `%%'," so we can avoid all the width
641 and precision processing. */
648 /* If this is a positional parameter, the position must follow imediately
649 after the %, thus create a %<num>$ sequence */
650 param=dprintf_DollarString(f, &f);
657 param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
658 third %s will pick the 3rd argument */
662 /* pick up the specified width */
663 if(p->flags & FLAGS_WIDTHPARAM)
664 width = vto[p->width].data.num;
668 /* pick up the specified precision */
669 if(p->flags & FLAGS_PRECPARAM)
670 prec = vto[p->precision].data.num;
671 else if(p->flags & FLAGS_PREC)
676 alt = p->flags & FLAGS_ALT;
681 if(p->flags & FLAGS_CHAR) {
683 if (!(p->flags & FLAGS_LEFT))
687 if (p->flags & FLAGS_LEFT)
692 if(p->flags & FLAGS_UNSIGNED) {
693 /* Decimal unsigned integer. */
695 goto unsigned_number;
697 if(p->flags & FLAGS_OCTAL) {
698 /* Octal unsigned integer. */
700 goto unsigned_number;
702 if(p->flags & FLAGS_HEX) {
703 /* Hexadecimal unsigned integer. */
705 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
707 goto unsigned_number;
710 /* Decimal integer. */
714 if(p->flags & FLAGS_LONGLONG) {
716 is_neg = p->data.lnum < 0;
717 num = is_neg ? (- p->data.lnum) : p->data.lnum;
722 signed_num = (long) num;
724 is_neg = signed_num < 0;
725 num = is_neg ? (- signed_num) : signed_num;
730 /* Unsigned number of base BASE. */
734 /* Number of base BASE. */
736 char *workend = &work[sizeof(work) - 1];
739 /* Supply a default precision if none was given. */
743 /* Put the number in WORK. */
746 *w-- = digits[num % base];
749 width -= workend - w;
752 if (alt && base == 8 && prec <= 0) {
763 if (alt && base == 16)
766 if (is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
769 if (!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
775 else if (p->flags & FLAGS_SHOWSIGN)
777 else if (p->flags & FLAGS_SPACE)
780 if (alt && base == 16) {
782 if(p->flags & FLAGS_UPPER)
788 if (!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
792 /* Write the number. */
793 while (++w <= workend) {
797 if (p->flags & FLAGS_LEFT)
806 static char null[] = "(nil)";
810 str = (char *) p->data.str;
812 /* Write null[] if there's space. */
813 if (prec == -1 || prec >= (long) sizeof(null) - 1) {
815 len = sizeof(null) - 1;
816 /* Disable quotes around (nil) */
817 p->flags &= (~FLAGS_ALT);
827 if (prec != -1 && (size_t) prec < len)
831 if (p->flags & FLAGS_ALT)
834 if (!(p->flags&FLAGS_LEFT))
840 if (p->flags&FLAGS_LEFT)
844 if (p->flags & FLAGS_ALT)
850 /* Generic pointer. */
853 ptr = (void *) p->data.ptr;
855 /* If the pointer is not NULL, write it as a %#x spec. */
857 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
859 num = (unsigned long) ptr;
864 /* Write "(nil)" for a nil pointer. */
865 static char strnil[] = "(nil)";
866 register char *point;
868 width -= sizeof(strnil) - 1;
869 if (p->flags & FLAGS_LEFT)
872 for (point = strnil; *point != '\0'; ++point)
874 if (! (p->flags & FLAGS_LEFT))
883 char formatbuf[32]="%";
887 if (p->flags & FLAGS_WIDTH)
889 else if (p->flags & FLAGS_WIDTHPARAM)
890 width = vto[p->width].data.num;
893 if (p->flags & FLAGS_PREC)
895 else if (p->flags & FLAGS_PRECPARAM)
896 prec = vto[p->precision].data.num;
898 if (p->flags & FLAGS_LEFT)
899 strcat(formatbuf, "-");
900 if (p->flags & FLAGS_SHOWSIGN)
901 strcat(formatbuf, "+");
902 if (p->flags & FLAGS_SPACE)
903 strcat(formatbuf, " ");
904 if (p->flags & FLAGS_ALT)
905 strcat(formatbuf, "#");
907 fptr=&formatbuf[strlen(formatbuf)];
910 /* RECURSIVE USAGE */
911 fptr += curl_msprintf(fptr, "%ld", width);
914 /* RECURSIVE USAGE */
915 fptr += curl_msprintf(fptr, ".%ld", prec);
917 if (p->flags & FLAGS_LONG)
920 if (p->flags & FLAGS_FLOATE)
921 strcat(fptr, p->flags&FLAGS_UPPER?"E":"e");
922 else if (p->flags & FLAGS_FLOATG)
923 strcat(fptr, (p->flags & FLAGS_UPPER) ? "G" : "g");
927 /* NOTE NOTE NOTE!! Not all sprintf() implementations returns number
928 of output characters */
929 #if 0 /*SIZEOF_LONG_DOUBLE*/
930 if (p->flags & FLAGS_LONG)
931 /* This is for support of the 'long double' type */
932 (sprintf)(work, formatbuf, p->data.ldnum);
935 (sprintf)(work, formatbuf, p->data.dnum);
937 for(fptr=work; *fptr; fptr++)
943 /* Answer the count of characters written. */
945 if (p->flags & FLAGS_LONGLONG)
946 *(LONG_LONG *) p->data.ptr = (LONG_LONG)done;
949 if (p->flags & FLAGS_LONG)
950 *(long *) p->data.ptr = (long)done;
951 else if (!(p->flags & FLAGS_SHORT))
952 *(int *) p->data.ptr = (int)done;
954 *(short *) p->data.ptr = (short)done;
960 f = *end++; /* goto end of %-code */
966 /* fputc() look-alike */
967 static int addbyter(int output, FILE *data)
969 struct nsprintf *infop=(struct nsprintf *)data;
971 if(infop->length < infop->max) {
972 /* only do this if we haven't reached max length yet */
973 infop->buffer[0] = (char)output; /* store */
974 infop->buffer++; /* increase pointer */
975 infop->length++; /* we are now one byte larger */
976 return output; /* fputc() returns like this on success */
981 int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
985 struct nsprintf info;
987 info.buffer = buffer;
989 info.max = maxlength;
991 retcode = dprintf_formatf(&info, addbyter, format, ap_save);
993 /* we terminate this with a zero byte */
994 if(info.max == info.length)
995 /* we're at maximum, scrap the last letter */
1003 int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
1006 va_list ap_save; /* argument pointer */
1007 va_start(ap_save, format);
1008 retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
1013 /* fputc() look-alike */
1014 static int alloc_addbyter(int output, FILE *data)
1016 struct asprintf *infop=(struct asprintf *)data;
1018 if(!infop->buffer) {
1019 infop->buffer=(char *)malloc(32);
1021 return -1; /* fail */
1025 else if(infop->len+1 >= infop->alloc) {
1028 newptr = (char *)realloc(infop->buffer, infop->alloc*2);
1033 infop->buffer = newptr;
1037 infop->buffer[ infop->len ] = output;
1041 return output; /* fputc() returns like this on success */
1044 char *curl_maprintf(const char *format, ...)
1046 va_list ap_save; /* argument pointer */
1048 struct asprintf info;
1054 va_start(ap_save, format);
1055 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1063 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1070 char *curl_mvaprintf(const char *format, va_list ap_save)
1073 struct asprintf info;
1079 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1087 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1094 static int storebuffer(int output, FILE *data)
1096 char **buffer = (char **)data;
1097 **buffer = (char)output;
1099 return output; /* act like fputc() ! */
1102 int curl_msprintf(char *buffer, const char *format, ...)
1104 va_list ap_save; /* argument pointer */
1106 va_start(ap_save, format);
1107 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1109 *buffer=0; /* we terminate this with a zero byte */
1113 #ifndef WIN32 /* not needed on win32 */
1114 extern int fputc(int, FILE *);
1117 int curl_mprintf(const char *format, ...)
1120 va_list ap_save; /* argument pointer */
1121 va_start(ap_save, format);
1122 retcode = dprintf_formatf(stdout, fputc, format, ap_save);
1127 int curl_mfprintf(FILE *whereto, const char *format, ...)
1130 va_list ap_save; /* argument pointer */
1131 va_start(ap_save, format);
1132 retcode = dprintf_formatf(whereto, fputc, format, ap_save);
1137 int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
1140 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1141 *buffer=0; /* we terminate this with a zero byte */
1145 int curl_mvprintf(const char *format, va_list ap_save)
1147 return dprintf_formatf(stdout, fputc, format, ap_save);
1150 int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
1152 return dprintf_formatf(whereto, fputc, format, ap_save);
1155 #ifdef DPRINTF_DEBUG
1163 long long test = 0x1000000000LL;
1164 curl_mprintf("%lld %lld %lld\n", one, two, test);
1167 curl_mprintf("%3d %5d\n", 10, 1998);
1169 ptr=curl_maprintf("test this then baby %s%s%s%s%s%s %d %d %d loser baby get a hit in yer face now!", "", "pretty long string pretty long string pretty long string pretty long string pretty long string", "/", "/", "/", "pretty long string", 1998, 1999, 2001);
1173 memset(ptr, 55, strlen(ptr)+1);
1178 curl_mprintf(buffer, "%s %s %d", "daniel", "stenberg", 19988);
1181 curl_mfprintf(stderr, "%s %#08x\n", "dummy", 65);
1183 printf("%s %#08x\n", "dummy", 65);
1185 double tryout = 3.14156592;
1186 curl_mprintf(buffer, "%.2g %G %f %e %E", tryout, tryout, tryout, tryout, tryout);
1188 printf("%.2g %G %f %e %E\n", tryout, tryout, tryout, tryout, tryout);