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/curl.h> /* for the curl_off_t type */
43 #include <curl/mprintf.h>
45 #ifndef SIZEOF_LONG_DOUBLE
46 #define SIZEOF_LONG_DOUBLE 0
50 #define LONG_LONG long long
54 #define LONG_LONG __int64
57 #endif /* HAVE_LONGLONG */
59 /* The last #include file should be: */
64 #define BUFFSIZE 256 /* buffer for long-to-str and float-to-str calcs */
65 #define MAX_PARAMETERS 128 /* lame static limit */
75 # define TRUE ((char)(1 == 1))
76 # define FALSE ((char)(0 == 1))
81 /* Lower-case digits. */
82 static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
84 /* Upper-case digits. */
85 static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
87 #define OUTCHAR(x) done+=(stream(x, (FILE *)data)==-1?0:1)
89 /* Data type to read from the arglist */
100 FORMAT_WIDTH /* For internal use */
103 /* convertion and display flags */
107 FLAGS_SHOWSIGN = 1<<1,
112 FLAGS_LONGLONG = 1<<6,
113 FLAGS_LONGDOUBLE = 1<<7,
114 FLAGS_PAD_NIL = 1<<8,
115 FLAGS_UNSIGNED = 1<<9,
119 FLAGS_WIDTH = 1<<13, /* '*' or '*<num>$' used */
120 FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */
121 FLAGS_PREC = 1<<15, /* precision was specified */
122 FLAGS_PRECPARAM = 1<<16, /* precision PARAMETER was specified */
123 FLAGS_CHAR = 1<<17, /* %c story */
124 FLAGS_FLOATE = 1<<18, /* %e or %E */
125 FLAGS_FLOATG = 1<<19 /* %g or %G */
131 int width; /* width OR width parameter number */
132 int precision; /* precision OR precision parameter number */
141 #if 0 /*SIZEOF_LONG_DOUBLE */
154 char *buffer; /* allocated buffer */
155 size_t len; /* length of string */
156 size_t alloc; /* length of alloc */
159 int curl_msprintf(char *buffer, const char *format, ...);
161 static int dprintf_DollarString(char *input, char **end)
164 while(isdigit((int)*input)) {
166 number += *input-'0';
169 if(number && ('$'==*input++)) {
176 static BOOL dprintf_IsQualifierNoDollar(char c)
179 case '-': case '+': case ' ': case '#': case '.':
180 case '0': case '1': case '2': case '3': case '4':
181 case '5': case '6': case '7': case '8': case '9':
182 case 'h': case 'l': case 'L': case 'z': case 'q':
190 #ifdef DPRINTF_DEBUG2
191 int dprintf_Pass1Report(va_stack_t *vto, int max)
198 for(i=0; i<max; i++) {
200 switch(vto[i].type) {
216 case FORMAT_LONGLONG:
222 case FORMAT_LONGDOUBLE:
223 type = "long double";
230 for(bit=0; bit<31; bit++) {
231 flags = vto[i].flags & (1<<bit);
233 if(flags & FLAGS_SPACE)
234 strcat(buffer, "space ");
235 else if(flags & FLAGS_SHOWSIGN)
236 strcat(buffer, "plus ");
237 else if(flags & FLAGS_LEFT)
238 strcat(buffer, "left ");
239 else if(flags & FLAGS_ALT)
240 strcat(buffer, "alt ");
241 else if(flags & FLAGS_SHORT)
242 strcat(buffer, "short ");
243 else if(flags & FLAGS_LONG)
244 strcat(buffer, "long ");
245 else if(flags & FLAGS_LONGLONG)
246 strcat(buffer, "longlong ");
247 else if(flags & FLAGS_LONGDOUBLE)
248 strcat(buffer, "longdouble ");
249 else if(flags & FLAGS_PAD_NIL)
250 strcat(buffer, "padnil ");
251 else if(flags & FLAGS_UNSIGNED)
252 strcat(buffer, "unsigned ");
253 else if(flags & FLAGS_OCTAL)
254 strcat(buffer, "octal ");
255 else if(flags & FLAGS_HEX)
256 strcat(buffer, "hex ");
257 else if(flags & FLAGS_UPPER)
258 strcat(buffer, "upper ");
259 else if(flags & FLAGS_WIDTH)
260 strcat(buffer, "width ");
261 else if(flags & FLAGS_WIDTHPARAM)
262 strcat(buffer, "widthparam ");
263 else if(flags & FLAGS_PREC)
264 strcat(buffer, "precision ");
265 else if(flags & FLAGS_PRECPARAM)
266 strcat(buffer, "precparam ");
267 else if(flags & FLAGS_CHAR)
268 strcat(buffer, "char ");
269 else if(flags & FLAGS_FLOATE)
270 strcat(buffer, "floate ");
271 else if(flags & FLAGS_FLOATG)
272 strcat(buffer, "floatg ");
274 printf("REPORT: %d. %s [%s]\n", i, type, buffer);
282 /******************************************************************
285 * Create an index with the type of each parameter entry and its
286 * value (may vary in size)
288 ******************************************************************/
290 static int dprintf_Pass1(char *format, va_stack_t *vto, char **endpos, va_list arglist)
305 continue; /* while */
310 /* Handle the positional case (N$) */
314 this_param = dprintf_DollarString(fmt, &fmt);
316 /* we got no positional, get the next counter */
317 this_param = param_num;
319 if (this_param > max_param)
320 max_param = this_param;
323 * The parameter with number 'i' should be used. Next, we need
324 * to get SIZE and TYPE of the parameter. Add the information
331 /* Handle the flags */
333 while (dprintf_IsQualifierNoDollar(*fmt)) {
336 flags |= FLAGS_SPACE;
339 flags |= FLAGS_SHOWSIGN;
343 flags &= ~FLAGS_PAD_NIL;
351 /* The precision is picked from a specified parameter */
353 flags |= FLAGS_PRECPARAM;
357 i = dprintf_DollarString(fmt, &fmt);
361 precision = param_num;
363 if (precision > max_param)
364 max_param = precision;
368 precision = strtol(fmt, &fmt, 10);
372 flags |= FLAGS_SHORT;
375 if (flags & FLAGS_LONG)
376 flags |= FLAGS_LONGLONG;
381 flags |= FLAGS_LONGDOUBLE;
384 flags |= FLAGS_LONGLONG;
387 /* the code below generates a warning if -Wunreachable-code is
389 if (sizeof(size_t) > sizeof(unsigned long))
390 flags |= FLAGS_LONGLONG;
391 if (sizeof(size_t) > sizeof(unsigned int))
396 #if SIZEOF_CURL_OFF_T > 4
397 flags |= FLAGS_LONGLONG;
403 if (!(flags & FLAGS_LEFT))
404 flags |= FLAGS_PAD_NIL;
406 case '1': case '2': case '3': case '4':
407 case '5': case '6': case '7': case '8': case '9':
408 flags |= FLAGS_WIDTH;
409 width = strtol(fmt-1, &fmt, 10);
411 case '*': /* Special case */
412 flags |= FLAGS_WIDTHPARAM;
415 i = dprintf_DollarString(fmt, &fmt);
420 if(width > max_param)
428 /* Handle the specifier */
437 vto[i].type = FORMAT_STRING;
440 vto[i].type = FORMAT_INTPTR;
443 vto[i].type = FORMAT_PTR;
446 vto[i].type = FORMAT_INT;
449 vto[i].type = FORMAT_INT;
450 flags |= FLAGS_UNSIGNED;
453 vto[i].type = FORMAT_INT;
454 flags |= FLAGS_OCTAL;
457 vto[i].type = FORMAT_INT;
461 vto[i].type = FORMAT_INT;
462 flags |= FLAGS_HEX|FLAGS_UPPER;
465 vto[i].type = FORMAT_INT;
469 vto[i].type = FORMAT_DOUBLE;
472 vto[i].type = FORMAT_DOUBLE;
473 flags |= FLAGS_FLOATE| (('E' == *fmt)?FLAGS_UPPER:0);
476 vto[i].type = FORMAT_DOUBLE;
477 flags |= FLAGS_FLOATG| (('G' == *fmt)?FLAGS_UPPER:0);
480 vto[i].type = FORMAT_UNKNOWN;
484 vto[i].flags = flags;
485 vto[i].width = width;
486 vto[i].precision = precision;
488 if (flags & FLAGS_WIDTHPARAM) {
489 /* we have the width specified from a parameter, so we make that
490 parameter's info setup properly */
491 vto[i].width = width - 1;
493 vto[i].type = FORMAT_WIDTH;
494 vto[i].flags = FLAGS_NEW;
495 vto[i].precision = vto[i].width = 0; /* can't use width or precision
498 if (flags & FLAGS_PRECPARAM) {
499 /* we have the precision specified from a parameter, so we make that
500 parameter's info setup properly */
501 vto[i].precision = precision - 1;
503 vto[i].type = FORMAT_WIDTH;
504 vto[i].flags = FLAGS_NEW;
505 vto[i].precision = vto[i].width = 0; /* can't use width or precision
508 *endpos++ = fmt + 1; /* end of this sequence */
512 #ifdef DPRINTF_DEBUG2
513 dprintf_Pass1Report(vto, max_param);
516 /* Read the arg list parameters into our data list */
517 for (i=0; i<max_param; i++) {
518 if ((i + 1 < max_param) && (vto[i + 1].type == FORMAT_WIDTH))
520 /* Width/precision arguments must be read before the main argument
521 * they are attached to
523 vto[i + 1].data.num = va_arg(arglist, int);
529 vto[i].data.str = va_arg(arglist, char *);
535 vto[i].data.ptr = va_arg(arglist, void *);
540 if(vto[i].flags & FLAGS_LONGLONG)
541 vto[i].data.lnum = va_arg(arglist, LONG_LONG);
544 if(vto[i].flags & FLAGS_LONG)
545 vto[i].data.num = va_arg(arglist, long);
547 vto[i].data.num = va_arg(arglist, int);
551 #if 0 /*SIZEOF_LONG_DOUBLE */
552 if(vto[i].flags & FLAGS_LONG)
553 vto[i].data.ldnum = va_arg(arglist, long double);
556 vto[i].data.dnum = va_arg(arglist, double);
560 /* Argument has been read. Silently convert it into an integer
563 vto[i].type = FORMAT_INT;
575 static int dprintf_formatf(
576 void *data, /* untouched by format(), just sent to the
577 stream() function in the first argument */
578 int (*stream)(int, FILE *), /* function pointer called for each
580 const char *format, /* %-formatted string */
581 va_list ap_save) /* list of parameters */
583 /* Base-36 digits for numbers. */
584 const char *digits = lower_digits;
586 /* Pointer into the format string. */
589 /* Number of characters written. */
590 register size_t done = 0;
592 long param; /* current parameter to read */
593 long param_num=0; /* parameter counter */
595 va_stack_t vto[MAX_PARAMETERS];
596 char *endpos[MAX_PARAMETERS];
603 /* Do the actual %-code parsing */
604 dprintf_Pass1((char *)format, vto, endpos, ap_save);
606 end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
611 /* Format spec modifiers. */
614 /* Width of a field. */
617 /* Precision of a field. */
620 /* Decimal integer is negative. */
623 /* Base of a number to be written. */
626 /* Integral values to be written. */
628 unsigned LONG_LONG num;
635 /* This isn't a format spec, so write everything out until the next one
636 OR end of string is reached. */
639 } while(*++f && ('%' != *f));
645 /* Check for "%%". Note that although the ANSI standard lists
646 '%' as a conversion specifier, it says "The complete format
647 specification shall be `%%'," so we can avoid all the width
648 and precision processing. */
655 /* If this is a positional parameter, the position must follow imediately
656 after the %, thus create a %<num>$ sequence */
657 param=dprintf_DollarString(f, &f);
664 param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
665 third %s will pick the 3rd argument */
669 /* pick up the specified width */
670 if(p->flags & FLAGS_WIDTHPARAM)
671 width = vto[p->width].data.num;
675 /* pick up the specified precision */
676 if(p->flags & FLAGS_PRECPARAM)
677 prec = vto[p->precision].data.num;
678 else if(p->flags & FLAGS_PREC)
683 alt = p->flags & FLAGS_ALT;
688 if(p->flags & FLAGS_CHAR) {
690 if (!(p->flags & FLAGS_LEFT))
694 if (p->flags & FLAGS_LEFT)
699 if(p->flags & FLAGS_UNSIGNED) {
700 /* Decimal unsigned integer. */
702 goto unsigned_number;
704 if(p->flags & FLAGS_OCTAL) {
705 /* Octal unsigned integer. */
707 goto unsigned_number;
709 if(p->flags & FLAGS_HEX) {
710 /* Hexadecimal unsigned integer. */
712 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
714 goto unsigned_number;
717 /* Decimal integer. */
721 if(p->flags & FLAGS_LONGLONG) {
723 is_neg = p->data.lnum < 0;
724 num = is_neg ? (- p->data.lnum) : p->data.lnum;
729 signed_num = (long) num;
731 is_neg = signed_num < 0;
732 num = is_neg ? (- signed_num) : signed_num;
737 /* Unsigned number of base BASE. */
741 /* Number of base BASE. */
743 char *workend = &work[sizeof(work) - 1];
746 /* Supply a default precision if none was given. */
750 /* Put the number in WORK. */
753 *w-- = digits[num % base];
756 width -= workend - w;
759 if (alt && base == 8 && prec <= 0) {
770 if (alt && base == 16)
773 if (is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
776 if (!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
782 else if (p->flags & FLAGS_SHOWSIGN)
784 else if (p->flags & FLAGS_SPACE)
787 if (alt && base == 16) {
789 if(p->flags & FLAGS_UPPER)
795 if (!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
799 /* Write the number. */
800 while (++w <= workend) {
804 if (p->flags & FLAGS_LEFT)
813 static char null[] = "(nil)";
817 str = (char *) p->data.str;
819 /* Write null[] if there's space. */
820 if (prec == -1 || prec >= (long) sizeof(null) - 1) {
822 len = sizeof(null) - 1;
823 /* Disable quotes around (nil) */
824 p->flags &= (~FLAGS_ALT);
834 if (prec != -1 && (size_t) prec < len)
838 if (p->flags & FLAGS_ALT)
841 if (!(p->flags&FLAGS_LEFT))
847 if (p->flags&FLAGS_LEFT)
851 if (p->flags & FLAGS_ALT)
857 /* Generic pointer. */
860 ptr = (void *) p->data.ptr;
862 /* If the pointer is not NULL, write it as a %#x spec. */
864 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
866 num = (unsigned long) ptr;
871 /* Write "(nil)" for a nil pointer. */
872 static char strnil[] = "(nil)";
873 register char *point;
875 width -= sizeof(strnil) - 1;
876 if (p->flags & FLAGS_LEFT)
879 for (point = strnil; *point != '\0'; ++point)
881 if (! (p->flags & FLAGS_LEFT))
890 char formatbuf[32]="%";
894 if (p->flags & FLAGS_WIDTH)
896 else if (p->flags & FLAGS_WIDTHPARAM)
897 width = vto[p->width].data.num;
900 if (p->flags & FLAGS_PREC)
902 else if (p->flags & FLAGS_PRECPARAM)
903 prec = vto[p->precision].data.num;
905 if (p->flags & FLAGS_LEFT)
906 strcat(formatbuf, "-");
907 if (p->flags & FLAGS_SHOWSIGN)
908 strcat(formatbuf, "+");
909 if (p->flags & FLAGS_SPACE)
910 strcat(formatbuf, " ");
911 if (p->flags & FLAGS_ALT)
912 strcat(formatbuf, "#");
914 fptr=&formatbuf[strlen(formatbuf)];
917 /* RECURSIVE USAGE */
918 fptr += curl_msprintf(fptr, "%ld", width);
921 /* RECURSIVE USAGE */
922 fptr += curl_msprintf(fptr, ".%ld", prec);
924 if (p->flags & FLAGS_LONG)
927 if (p->flags & FLAGS_FLOATE)
928 strcat(fptr, p->flags&FLAGS_UPPER?"E":"e");
929 else if (p->flags & FLAGS_FLOATG)
930 strcat(fptr, (p->flags & FLAGS_UPPER) ? "G" : "g");
934 /* NOTE NOTE NOTE!! Not all sprintf() implementations returns number
935 of output characters */
936 #if 0 /*SIZEOF_LONG_DOUBLE*/
937 if (p->flags & FLAGS_LONG)
938 /* This is for support of the 'long double' type */
939 (sprintf)(work, formatbuf, p->data.ldnum);
942 (sprintf)(work, formatbuf, p->data.dnum);
944 for(fptr=work; *fptr; fptr++)
950 /* Answer the count of characters written. */
952 if (p->flags & FLAGS_LONGLONG)
953 *(LONG_LONG *) p->data.ptr = (LONG_LONG)done;
956 if (p->flags & FLAGS_LONG)
957 *(long *) p->data.ptr = (long)done;
958 else if (!(p->flags & FLAGS_SHORT))
959 *(int *) p->data.ptr = (int)done;
961 *(short *) p->data.ptr = (short)done;
967 f = *end++; /* goto end of %-code */
973 /* fputc() look-alike */
974 static int addbyter(int output, FILE *data)
976 struct nsprintf *infop=(struct nsprintf *)data;
978 if(infop->length < infop->max) {
979 /* only do this if we haven't reached max length yet */
980 infop->buffer[0] = (char)output; /* store */
981 infop->buffer++; /* increase pointer */
982 infop->length++; /* we are now one byte larger */
983 return output; /* fputc() returns like this on success */
988 int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
992 struct nsprintf info;
994 info.buffer = buffer;
996 info.max = maxlength;
998 retcode = dprintf_formatf(&info, addbyter, format, ap_save);
1000 /* we terminate this with a zero byte */
1001 if(info.max == info.length)
1002 /* we're at maximum, scrap the last letter */
1003 info.buffer[-1] = 0;
1010 int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
1013 va_list ap_save; /* argument pointer */
1014 va_start(ap_save, format);
1015 retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
1020 /* fputc() look-alike */
1021 static int alloc_addbyter(int output, FILE *data)
1023 struct asprintf *infop=(struct asprintf *)data;
1025 if(!infop->buffer) {
1026 infop->buffer=(char *)malloc(32);
1028 return -1; /* fail */
1032 else if(infop->len+1 >= infop->alloc) {
1035 newptr = (char *)realloc(infop->buffer, infop->alloc*2);
1040 infop->buffer = newptr;
1044 infop->buffer[ infop->len ] = output;
1048 return output; /* fputc() returns like this on success */
1051 char *curl_maprintf(const char *format, ...)
1053 va_list ap_save; /* argument pointer */
1055 struct asprintf info;
1061 va_start(ap_save, format);
1062 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1070 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1077 char *curl_mvaprintf(const char *format, va_list ap_save)
1080 struct asprintf info;
1086 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1094 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1101 static int storebuffer(int output, FILE *data)
1103 char **buffer = (char **)data;
1104 **buffer = (char)output;
1106 return output; /* act like fputc() ! */
1109 int curl_msprintf(char *buffer, const char *format, ...)
1111 va_list ap_save; /* argument pointer */
1113 va_start(ap_save, format);
1114 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1116 *buffer=0; /* we terminate this with a zero byte */
1120 #ifndef WIN32 /* not needed on win32 */
1121 extern int fputc(int, FILE *);
1124 int curl_mprintf(const char *format, ...)
1127 va_list ap_save; /* argument pointer */
1128 va_start(ap_save, format);
1129 retcode = dprintf_formatf(stdout, fputc, format, ap_save);
1134 int curl_mfprintf(FILE *whereto, const char *format, ...)
1137 va_list ap_save; /* argument pointer */
1138 va_start(ap_save, format);
1139 retcode = dprintf_formatf(whereto, fputc, format, ap_save);
1144 int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
1147 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1148 *buffer=0; /* we terminate this with a zero byte */
1152 int curl_mvprintf(const char *format, va_list ap_save)
1154 return dprintf_formatf(stdout, fputc, format, ap_save);
1157 int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
1159 return dprintf_formatf(whereto, fputc, format, ap_save);
1162 #ifdef DPRINTF_DEBUG
1169 dprintf("%3$12s %1$s %2$qd %4$d\n", "daniel", hullo, "stenberg", 65);
1172 mprintf("%3d %5d\n", 10, 1998);
1174 ptr=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);
1178 memset(ptr, 55, strlen(ptr)+1);
1183 mprintf(buffer, "%s %s %d", "daniel", "stenberg", 19988);
1186 mfprintf(stderr, "%s %#08x\n", "dummy", 65);
1188 printf("%s %#08x\n", "dummy", 65);
1190 double tryout = 3.14156592;
1191 mprintf(buffer, "%.2g %G %f %e %E", tryout, tryout, tryout, tryout, tryout);
1193 printf("%.2g %G %f %e %E\n", tryout, tryout, tryout, tryout, tryout);