1 /****************************************************************************
3 * $Id: mprintf.c,v 1.38 2004/03/08 11:28:14 bagder Exp $
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 long 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;
469 vto[i].type = FORMAT_DOUBLE;
470 flags |= FLAGS_FLOATE|FLAGS_UPPER;
473 vto[i].type = FORMAT_DOUBLE;
474 flags |= FLAGS_FLOATG;
477 vto[i].type = FORMAT_DOUBLE;
478 flags |= FLAGS_FLOATG|FLAGS_UPPER;
481 vto[i].type = FORMAT_UNKNOWN;
485 vto[i].flags = flags;
486 vto[i].width = width;
487 vto[i].precision = precision;
489 if (flags & FLAGS_WIDTHPARAM) {
490 /* we have the width specified from a parameter, so we make that
491 parameter's info setup properly */
492 vto[i].width = width - 1;
494 vto[i].type = FORMAT_WIDTH;
495 vto[i].flags = FLAGS_NEW;
496 vto[i].precision = vto[i].width = 0; /* can't use width or precision
499 if (flags & FLAGS_PRECPARAM) {
500 /* we have the precision specified from a parameter, so we make that
501 parameter's info setup properly */
502 vto[i].precision = precision - 1;
504 vto[i].type = FORMAT_WIDTH;
505 vto[i].flags = FLAGS_NEW;
506 vto[i].precision = vto[i].width = 0; /* can't use width or precision
509 *endpos++ = fmt + 1; /* end of this sequence */
513 #ifdef DPRINTF_DEBUG2
514 dprintf_Pass1Report(vto, max_param);
517 /* Read the arg list parameters into our data list */
518 for (i=0; i<max_param; i++) {
519 if ((i + 1 < max_param) && (vto[i + 1].type == FORMAT_WIDTH))
521 /* Width/precision arguments must be read before the main argument
522 * they are attached to
524 vto[i + 1].data.num = va_arg(arglist, int);
530 vto[i].data.str = va_arg(arglist, char *);
536 vto[i].data.ptr = va_arg(arglist, void *);
541 if(vto[i].flags & FLAGS_LONGLONG)
542 vto[i].data.lnum = va_arg(arglist, LONG_LONG);
545 if(vto[i].flags & FLAGS_LONG)
546 vto[i].data.num = va_arg(arglist, long);
548 vto[i].data.num = va_arg(arglist, int);
552 #if 0 /*SIZEOF_LONG_DOUBLE */
553 if(vto[i].flags & FLAGS_LONG)
554 vto[i].data.ldnum = va_arg(arglist, long double);
557 vto[i].data.dnum = va_arg(arglist, double);
561 /* Argument has been read. Silently convert it into an integer
564 vto[i].type = FORMAT_INT;
576 static int dprintf_formatf(
577 void *data, /* untouched by format(), just sent to the
578 stream() function in the first argument */
579 int (*stream)(int, FILE *), /* function pointer called for each
581 const char *format, /* %-formatted string */
582 va_list ap_save) /* list of parameters */
584 /* Base-36 digits for numbers. */
585 const char *digits = lower_digits;
587 /* Pointer into the format string. */
590 /* Number of characters written. */
593 long param; /* current parameter to read */
594 long param_num=0; /* parameter counter */
596 va_stack_t vto[MAX_PARAMETERS];
597 char *endpos[MAX_PARAMETERS];
604 /* Do the actual %-code parsing */
605 dprintf_Pass1((char *)format, vto, endpos, ap_save);
607 end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
612 /* Format spec modifiers. */
615 /* Width of a field. */
618 /* Precision of a field. */
621 /* Decimal integer is negative. */
624 /* Base of a number to be written. */
627 /* Integral values to be written. */
629 unsigned LONG_LONG num;
636 /* This isn't a format spec, so write everything out until the next one
637 OR end of string is reached. */
640 } while(*++f && ('%' != *f));
646 /* Check for "%%". Note that although the ANSI standard lists
647 '%' as a conversion specifier, it says "The complete format
648 specification shall be `%%'," so we can avoid all the width
649 and precision processing. */
656 /* If this is a positional parameter, the position must follow imediately
657 after the %, thus create a %<num>$ sequence */
658 param=dprintf_DollarString(f, &f);
665 param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
666 third %s will pick the 3rd argument */
670 /* pick up the specified width */
671 if(p->flags & FLAGS_WIDTHPARAM)
672 width = vto[p->width].data.num;
676 /* pick up the specified precision */
677 if(p->flags & FLAGS_PRECPARAM)
678 prec = vto[p->precision].data.num;
679 else if(p->flags & FLAGS_PREC)
684 alt = p->flags & FLAGS_ALT;
689 if(p->flags & FLAGS_CHAR) {
691 if (!(p->flags & FLAGS_LEFT))
695 if (p->flags & FLAGS_LEFT)
700 if(p->flags & FLAGS_UNSIGNED) {
701 /* Decimal unsigned integer. */
703 goto unsigned_number;
705 if(p->flags & FLAGS_OCTAL) {
706 /* Octal unsigned integer. */
708 goto unsigned_number;
710 if(p->flags & FLAGS_HEX) {
711 /* Hexadecimal unsigned integer. */
713 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
715 goto unsigned_number;
718 /* Decimal integer. */
722 if(p->flags & FLAGS_LONGLONG) {
724 is_neg = p->data.lnum < 0;
725 num = is_neg ? (- p->data.lnum) : p->data.lnum;
730 signed_num = (long) num;
732 is_neg = signed_num < 0;
733 num = is_neg ? (- signed_num) : signed_num;
738 /* Unsigned number of base BASE. */
742 /* Number of base BASE. */
744 char *workend = &work[sizeof(work) - 1];
747 /* Supply a default precision if none was given. */
751 /* Put the number in WORK. */
754 *w-- = digits[num % base];
757 width -= workend - w;
760 if (alt && base == 8 && prec <= 0) {
771 if (alt && base == 16)
774 if (is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
777 if (!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
783 else if (p->flags & FLAGS_SHOWSIGN)
785 else if (p->flags & FLAGS_SPACE)
788 if (alt && base == 16) {
790 if(p->flags & FLAGS_UPPER)
796 if (!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
800 /* Write the number. */
801 while (++w <= workend) {
805 if (p->flags & FLAGS_LEFT)
814 static char null[] = "(nil)";
818 str = (char *) p->data.str;
820 /* Write null[] if there's space. */
821 if (prec == -1 || prec >= (long) sizeof(null) - 1) {
823 len = sizeof(null) - 1;
824 /* Disable quotes around (nil) */
825 p->flags &= (~FLAGS_ALT);
835 if (prec != -1 && (size_t) prec < len)
839 if (p->flags & FLAGS_ALT)
842 if (!(p->flags&FLAGS_LEFT))
848 if (p->flags&FLAGS_LEFT)
852 if (p->flags & FLAGS_ALT)
858 /* Generic pointer. */
861 ptr = (void *) p->data.ptr;
863 /* If the pointer is not NULL, write it as a %#x spec. */
865 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
867 num = (unsigned long) ptr;
872 /* Write "(nil)" for a nil pointer. */
873 static char strnil[] = "(nil)";
876 width -= sizeof(strnil) - 1;
877 if (p->flags & FLAGS_LEFT)
880 for (point = strnil; *point != '\0'; ++point)
882 if (! (p->flags & FLAGS_LEFT))
891 char formatbuf[32]="%";
895 if (p->flags & FLAGS_WIDTH)
897 else if (p->flags & FLAGS_WIDTHPARAM)
898 width = vto[p->width].data.num;
901 if (p->flags & FLAGS_PREC)
903 else if (p->flags & FLAGS_PRECPARAM)
904 prec = vto[p->precision].data.num;
906 if (p->flags & FLAGS_LEFT)
907 strcat(formatbuf, "-");
908 if (p->flags & FLAGS_SHOWSIGN)
909 strcat(formatbuf, "+");
910 if (p->flags & FLAGS_SPACE)
911 strcat(formatbuf, " ");
912 if (p->flags & FLAGS_ALT)
913 strcat(formatbuf, "#");
915 fptr=&formatbuf[strlen(formatbuf)];
918 /* RECURSIVE USAGE */
919 fptr += curl_msprintf(fptr, "%ld", width);
922 /* RECURSIVE USAGE */
923 fptr += curl_msprintf(fptr, ".%ld", prec);
925 if (p->flags & FLAGS_LONG)
928 if (p->flags & FLAGS_FLOATE)
929 strcat(fptr, p->flags&FLAGS_UPPER?"E":"e");
930 else if (p->flags & FLAGS_FLOATG)
931 strcat(fptr, (p->flags & FLAGS_UPPER) ? "G" : "g");
935 /* NOTE NOTE NOTE!! Not all sprintf() implementations returns number
936 of output characters */
937 #if 0 /*SIZEOF_LONG_DOUBLE*/
938 if (p->flags & FLAGS_LONG)
939 /* This is for support of the 'long double' type */
940 (sprintf)(work, formatbuf, p->data.ldnum);
943 (sprintf)(work, formatbuf, p->data.dnum);
945 for(fptr=work; *fptr; fptr++)
951 /* Answer the count of characters written. */
953 if (p->flags & FLAGS_LONGLONG)
954 *(LONG_LONG *) p->data.ptr = (LONG_LONG)done;
957 if (p->flags & FLAGS_LONG)
958 *(long *) p->data.ptr = (long)done;
959 else if (!(p->flags & FLAGS_SHORT))
960 *(int *) p->data.ptr = (int)done;
962 *(short *) p->data.ptr = (short)done;
968 f = *end++; /* goto end of %-code */
974 /* fputc() look-alike */
975 static int addbyter(int output, FILE *data)
977 struct nsprintf *infop=(struct nsprintf *)data;
979 if(infop->length < infop->max) {
980 /* only do this if we haven't reached max length yet */
981 infop->buffer[0] = (char)output; /* store */
982 infop->buffer++; /* increase pointer */
983 infop->length++; /* we are now one byte larger */
984 return output; /* fputc() returns like this on success */
989 int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
993 struct nsprintf info;
995 info.buffer = buffer;
997 info.max = maxlength;
999 retcode = dprintf_formatf(&info, addbyter, format, ap_save);
1001 /* we terminate this with a zero byte */
1002 if(info.max == info.length)
1003 /* we're at maximum, scrap the last letter */
1004 info.buffer[-1] = 0;
1011 int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
1014 va_list ap_save; /* argument pointer */
1015 va_start(ap_save, format);
1016 retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
1021 /* fputc() look-alike */
1022 static int alloc_addbyter(int output, FILE *data)
1024 struct asprintf *infop=(struct asprintf *)data;
1026 if(!infop->buffer) {
1027 infop->buffer=(char *)malloc(32);
1029 return -1; /* fail */
1033 else if(infop->len+1 >= infop->alloc) {
1036 newptr = (char *)realloc(infop->buffer, infop->alloc*2);
1041 infop->buffer = newptr;
1045 infop->buffer[ infop->len ] = output;
1049 return output; /* fputc() returns like this on success */
1052 char *curl_maprintf(const char *format, ...)
1054 va_list ap_save; /* argument pointer */
1056 struct asprintf info;
1062 va_start(ap_save, format);
1063 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1071 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1078 char *curl_mvaprintf(const char *format, va_list ap_save)
1081 struct asprintf info;
1087 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1095 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1102 static int storebuffer(int output, FILE *data)
1104 char **buffer = (char **)data;
1105 **buffer = (char)output;
1107 return output; /* act like fputc() ! */
1110 int curl_msprintf(char *buffer, const char *format, ...)
1112 va_list ap_save; /* argument pointer */
1114 va_start(ap_save, format);
1115 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1117 *buffer=0; /* we terminate this with a zero byte */
1121 #ifndef WIN32 /* not needed on win32 */
1122 extern int fputc(int, FILE *);
1125 int curl_mprintf(const char *format, ...)
1128 va_list ap_save; /* argument pointer */
1129 va_start(ap_save, format);
1130 retcode = dprintf_formatf(stdout, fputc, format, ap_save);
1135 int curl_mfprintf(FILE *whereto, const char *format, ...)
1138 va_list ap_save; /* argument pointer */
1139 va_start(ap_save, format);
1140 retcode = dprintf_formatf(whereto, fputc, format, ap_save);
1145 int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
1148 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1149 *buffer=0; /* we terminate this with a zero byte */
1153 int curl_mvprintf(const char *format, va_list ap_save)
1155 return dprintf_formatf(stdout, fputc, format, ap_save);
1158 int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
1160 return dprintf_formatf(whereto, fputc, format, ap_save);
1163 #ifdef DPRINTF_DEBUG
1171 long long test = 0x1000000000LL;
1172 curl_mprintf("%lld %lld %lld\n", one, two, test);
1175 curl_mprintf("%3d %5d\n", 10, 1998);
1177 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);
1181 memset(ptr, 55, strlen(ptr)+1);
1186 curl_mprintf(buffer, "%s %s %d", "daniel", "stenberg", 19988);
1189 curl_mfprintf(stderr, "%s %#08x\n", "dummy", 65);
1191 printf("%s %#08x\n", "dummy", 65);
1193 double tryout = 3.14156592;
1194 curl_mprintf(buffer, "%.2g %G %f %e %E", tryout, tryout, tryout, tryout, tryout);
1196 printf("%.2g %G %f %e %E\n", tryout, tryout, tryout, tryout, tryout);