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 #ifndef SIZEOF_LONG_LONG
42 /* prevents warnings on picky compilers */
43 #define SIZEOF_LONG_LONG 0
45 #ifndef SIZEOF_LONG_DOUBLE
46 #define SIZEOF_LONG_DOUBLE 0
50 /* The last #include file should be: */
55 #define BUFFSIZE 256 /* buffer for long-to-str and float-to-str calcs */
56 #define MAX_PARAMETERS 128 /* lame static limit */
66 # define TRUE ((char)(1 == 1))
67 # define FALSE ((char)(0 == 1))
72 /* Lower-case digits. */
73 static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
75 /* Upper-case digits. */
76 static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
78 #define OUTCHAR(x) done+=(stream(x, (FILE *)data)==-1?0:1)
80 /* Data type to read from the arglist */
91 FORMAT_WIDTH /* For internal use */
94 /* convertion and display flags */
98 FLAGS_SHOWSIGN = 1<<1,
103 FLAGS_LONGLONG = 1<<6,
104 FLAGS_LONGDOUBLE = 1<<7,
105 FLAGS_PAD_NIL = 1<<8,
106 FLAGS_UNSIGNED = 1<<9,
110 FLAGS_WIDTH = 1<<13, /* '*' or '*<num>$' used */
111 FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */
112 FLAGS_PREC = 1<<15, /* precision was specified */
113 FLAGS_PRECPARAM = 1<<16, /* precision PARAMETER was specified */
114 FLAGS_CHAR = 1<<17, /* %c story */
115 FLAGS_FLOATE = 1<<18, /* %e or %E */
116 FLAGS_FLOATG = 1<<19 /* %g or %G */
122 int width; /* width OR width parameter number */
123 int precision; /* precision OR precision parameter number */
128 #if SIZEOF_LONG_LONG /* if this is non-zero */
132 #if SIZEOF_LONG_DOUBLE
145 char *buffer; /* allocated buffer */
146 size_t len; /* length of string */
147 size_t alloc; /* length of alloc */
150 int curl_msprintf(char *buffer, const char *format, ...);
152 static int dprintf_DollarString(char *input, char **end)
155 while(isdigit((int)*input)) {
157 number += *input-'0';
160 if(number && ('$'==*input++)) {
167 static BOOL dprintf_IsQualifierNoDollar(char c)
170 case '-': case '+': case ' ': case '#': case '.':
171 case '0': case '1': case '2': case '3': case '4':
172 case '5': case '6': case '7': case '8': case '9':
173 case 'h': case 'l': case 'L': case 'Z': case 'q':
180 #ifdef DPRINTF_DEBUG2
181 int dprintf_Pass1Report(va_stack_t *vto, int max)
188 for(i=0; i<max; i++) {
190 switch(vto[i].type) {
206 case FORMAT_LONGLONG:
212 case FORMAT_LONGDOUBLE:
213 type = "long double";
220 for(bit=0; bit<31; bit++) {
221 flags = vto[i].flags & (1<<bit);
223 if(flags & FLAGS_SPACE)
224 strcat(buffer, "space ");
225 else if(flags & FLAGS_SHOWSIGN)
226 strcat(buffer, "plus ");
227 else if(flags & FLAGS_LEFT)
228 strcat(buffer, "left ");
229 else if(flags & FLAGS_ALT)
230 strcat(buffer, "alt ");
231 else if(flags & FLAGS_SHORT)
232 strcat(buffer, "short ");
233 else if(flags & FLAGS_LONG)
234 strcat(buffer, "long ");
235 else if(flags & FLAGS_LONGLONG)
236 strcat(buffer, "longlong ");
237 else if(flags & FLAGS_LONGDOUBLE)
238 strcat(buffer, "longdouble ");
239 else if(flags & FLAGS_PAD_NIL)
240 strcat(buffer, "padnil ");
241 else if(flags & FLAGS_UNSIGNED)
242 strcat(buffer, "unsigned ");
243 else if(flags & FLAGS_OCTAL)
244 strcat(buffer, "octal ");
245 else if(flags & FLAGS_HEX)
246 strcat(buffer, "hex ");
247 else if(flags & FLAGS_UPPER)
248 strcat(buffer, "upper ");
249 else if(flags & FLAGS_WIDTH)
250 strcat(buffer, "width ");
251 else if(flags & FLAGS_WIDTHPARAM)
252 strcat(buffer, "widthparam ");
253 else if(flags & FLAGS_PREC)
254 strcat(buffer, "precision ");
255 else if(flags & FLAGS_PRECPARAM)
256 strcat(buffer, "precparam ");
257 else if(flags & FLAGS_CHAR)
258 strcat(buffer, "char ");
259 else if(flags & FLAGS_FLOATE)
260 strcat(buffer, "floate ");
261 else if(flags & FLAGS_FLOATG)
262 strcat(buffer, "floatg ");
264 printf("REPORT: %d. %s [%s]\n", i, type, buffer);
272 /******************************************************************
275 * Create an index with the type of each parameter entry and its
276 * value (may vary in size)
278 ******************************************************************/
280 static int dprintf_Pass1(char *format, va_stack_t *vto, char **endpos, va_list arglist)
295 continue; /* while */
300 /* Handle the positional case (N$) */
304 this_param = dprintf_DollarString(fmt, &fmt);
306 /* we got no positional, get the next counter */
307 this_param = param_num;
309 if (this_param > max_param)
310 max_param = this_param;
313 * The parameter with number 'i' should be used. Next, we need
314 * to get SIZE and TYPE of the parameter. Add the information
321 /* Handle the flags */
323 while (dprintf_IsQualifierNoDollar(*fmt)) {
326 flags |= FLAGS_SPACE;
329 flags |= FLAGS_SHOWSIGN;
333 flags &= ~FLAGS_PAD_NIL;
341 /* The precision is picked from a specified parameter */
343 flags |= FLAGS_PRECPARAM;
347 i = dprintf_DollarString(fmt, &fmt);
351 precision = param_num;
353 if (precision > max_param)
354 max_param = precision;
358 precision = strtol(fmt, &fmt, 10);
362 flags |= FLAGS_SHORT;
365 if (flags & FLAGS_LONG)
366 flags |= FLAGS_LONGLONG;
371 flags |= FLAGS_LONGDOUBLE;
374 flags |= FLAGS_LONGLONG;
377 if (sizeof(size_t) > sizeof(unsigned long int))
378 flags |= FLAGS_LONGLONG;
379 if (sizeof(size_t) > sizeof(unsigned int))
383 if (!(flags & FLAGS_LEFT))
384 flags |= FLAGS_PAD_NIL;
386 case '1': case '2': case '3': case '4':
387 case '5': case '6': case '7': case '8': case '9':
388 flags |= FLAGS_WIDTH;
389 width = strtol(fmt-1, &fmt, 10);
391 case '*': /* Special case */
392 flags |= FLAGS_WIDTHPARAM;
395 i = dprintf_DollarString(fmt, &fmt);
400 if(width > max_param)
408 /* Handle the specifier */
417 vto[i].type = FORMAT_STRING;
420 vto[i].type = FORMAT_INTPTR;
423 vto[i].type = FORMAT_PTR;
426 vto[i].type = FORMAT_INT;
429 vto[i].type = FORMAT_INT;
430 flags |= FLAGS_UNSIGNED;
433 vto[i].type = FORMAT_INT;
434 flags |= FLAGS_OCTAL;
437 vto[i].type = FORMAT_INT;
441 vto[i].type = FORMAT_INT;
442 flags |= FLAGS_HEX|FLAGS_UPPER;
445 vto[i].type = FORMAT_INT;
449 vto[i].type = FORMAT_DOUBLE;
452 vto[i].type = FORMAT_DOUBLE;
453 flags |= FLAGS_FLOATE| (('E' == *fmt)?FLAGS_UPPER:0);
456 vto[i].type = FORMAT_DOUBLE;
457 flags |= FLAGS_FLOATG| (('G' == *fmt)?FLAGS_UPPER:0);
460 vto[i].type = FORMAT_UNKNOWN;
464 vto[i].flags = flags;
465 vto[i].width = width;
466 vto[i].precision = precision;
468 if (flags & FLAGS_WIDTHPARAM) {
469 /* we have the width specified from a parameter, so we make that
470 parameter's info setup properly */
471 vto[i].width = width - 1;
473 vto[i].type = FORMAT_WIDTH;
474 vto[i].flags = FLAGS_NEW;
475 vto[i].precision = vto[i].width = 0; /* can't use width or precision
478 if (flags & FLAGS_PRECPARAM) {
479 /* we have the precision specified from a parameter, so we make that
480 parameter's info setup properly */
481 vto[i].precision = precision - 1;
483 vto[i].type = FORMAT_WIDTH;
484 vto[i].flags = FLAGS_NEW;
485 vto[i].precision = vto[i].width = 0; /* can't use width or precision
488 *endpos++ = fmt + 1; /* end of this sequence */
492 #ifdef DPRINTF_DEBUG2
493 dprintf_Pass1Report(vto, max_param);
496 /* Read the arg list parameters into our data list */
497 for (i=0; i<max_param; i++) {
498 if ((i + 1 < max_param) && (vto[i + 1].type == FORMAT_WIDTH))
500 /* Width/precision arguments must be read before the main argument
501 * they are attached to
503 vto[i + 1].data.num = va_arg(arglist, int);
509 vto[i].data.str = va_arg(arglist, char *);
515 vto[i].data.ptr = va_arg(arglist, void *);
520 if(vto[i].flags & FLAGS_LONGLONG)
521 vto[i].data.lnum = va_arg(arglist, long long);
524 if(vto[i].flags & FLAGS_LONG)
525 vto[i].data.num = va_arg(arglist, long);
527 vto[i].data.num = va_arg(arglist, int);
531 #if SIZEOF_LONG_DOUBLE
532 if(vto[i].flags & FLAGS_LONG)
533 vto[i].data.ldnum = va_arg(arglist, long double);
536 vto[i].data.dnum = va_arg(arglist, double);
540 /* Argument has been read. Silently convert it into an integer
543 vto[i].type = FORMAT_INT;
555 static int dprintf_formatf(
556 void *data, /* untouched by format(), just sent to the
557 stream() function in the first argument */
558 int (*stream)(int, FILE *), /* function pointer called for each
560 const char *format, /* %-formatted string */
561 va_list ap_save) /* list of parameters */
563 /* Base-36 digits for numbers. */
564 const char *digits = lower_digits;
566 /* Pointer into the format string. */
569 /* Number of characters written. */
570 register size_t done = 0;
572 long param; /* current parameter to read */
573 long param_num=0; /* parameter counter */
575 va_stack_t vto[MAX_PARAMETERS];
576 char *endpos[MAX_PARAMETERS];
583 /* Do the actual %-code parsing */
584 dprintf_Pass1((char *)format, vto, endpos, ap_save);
586 end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
591 /* Format spec modifiers. */
594 /* Width of a field. */
596 /* Precision of a field. */
599 /* Decimal integer is negative. */
602 /* Base of a number to be written. */
605 /* Integral values to be written. */
607 unsigned long long num;
614 /* This isn't a format spec, so write everything out until the next one
615 OR end of string is reached. */
618 } while(*++f && ('%' != *f));
624 /* Check for "%%". Note that although the ANSI standard lists
625 '%' as a conversion specifier, it says "The complete format
626 specification shall be `%%'," so we can avoid all the width
627 and precision processing. */
634 /* If this is a positional parameter, the position must follow imediately
635 after the %, thus create a %<num>$ sequence */
636 param=dprintf_DollarString(f, &f);
643 param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
644 third %s will pick the 3rd argument */
648 /* pick up the specified width */
649 if(p->flags & FLAGS_WIDTHPARAM)
650 width = vto[p->width].data.num;
654 /* pick up the specified precision */
655 if(p->flags & FLAGS_PRECPARAM)
656 prec = vto[p->precision].data.num;
657 else if(p->flags & FLAGS_PREC)
662 alt = p->flags & FLAGS_ALT;
667 if(p->flags & FLAGS_CHAR) {
669 if (!(p->flags & FLAGS_LEFT))
673 if (p->flags & FLAGS_LEFT)
678 if(p->flags & FLAGS_UNSIGNED) {
679 /* Decimal unsigned integer. */
681 goto unsigned_number;
683 if(p->flags & FLAGS_OCTAL) {
684 /* Octal unsigned integer. */
686 goto unsigned_number;
688 if(p->flags & FLAGS_HEX) {
689 /* Hexadecimal unsigned integer. */
691 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
693 goto unsigned_number;
696 /* Decimal integer. */
700 if(p->flags & FLAGS_LONGLONG) {
702 is_neg = p->data.lnum < 0;
703 num = is_neg ? (- p->data.lnum) : p->data.lnum;
708 signed_num = (long) num;
710 is_neg = signed_num < 0;
711 num = is_neg ? (- signed_num) : signed_num;
716 /* Unsigned number of base BASE. */
720 /* Number of base BASE. */
722 char *workend = &work[sizeof(work) - 1];
725 /* Supply a default precision if none was given. */
729 /* Put the number in WORK. */
732 *w-- = digits[num % base];
735 width -= workend - w;
738 if (alt && base == 8 && prec <= 0) {
749 if (alt && base == 16)
752 if (is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
755 if (!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
761 else if (p->flags & FLAGS_SHOWSIGN)
763 else if (p->flags & FLAGS_SPACE)
766 if (alt && base == 16) {
768 if(p->flags & FLAGS_UPPER)
774 if (!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
778 /* Write the number. */
779 while (++w <= workend) {
783 if (p->flags & FLAGS_LEFT)
792 static char null[] = "(nil)";
796 str = (char *) p->data.str;
798 /* Write null[] if there's space. */
799 if (prec == -1 || prec >= (long) sizeof(null) - 1) {
801 len = sizeof(null) - 1;
802 /* Disable quotes around (nil) */
803 p->flags &= (~FLAGS_ALT);
813 if (prec != -1 && (size_t) prec < len)
817 if (p->flags & FLAGS_ALT)
820 if (!(p->flags&FLAGS_LEFT))
826 if (p->flags&FLAGS_LEFT)
830 if (p->flags & FLAGS_ALT)
836 /* Generic pointer. */
839 ptr = (void *) p->data.ptr;
841 /* If the pointer is not NULL, write it as a %#x spec. */
843 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
845 num = (unsigned long) ptr;
850 /* Write "(nil)" for a nil pointer. */
851 static char strnil[] = "(nil)";
852 register char *point;
854 width -= sizeof(strnil) - 1;
855 if (p->flags & FLAGS_LEFT)
858 for (point = strnil; *point != '\0'; ++point)
860 if (! (p->flags & FLAGS_LEFT))
869 char formatbuf[32]="%";
873 if (p->flags & FLAGS_WIDTH)
875 else if (p->flags & FLAGS_WIDTHPARAM)
876 width = vto[p->width].data.num;
879 if (p->flags & FLAGS_PREC)
881 else if (p->flags & FLAGS_PRECPARAM)
882 prec = vto[p->precision].data.num;
884 if (p->flags & FLAGS_LEFT)
885 strcat(formatbuf, "-");
886 if (p->flags & FLAGS_SHOWSIGN)
887 strcat(formatbuf, "+");
888 if (p->flags & FLAGS_SPACE)
889 strcat(formatbuf, " ");
890 if (p->flags & FLAGS_ALT)
891 strcat(formatbuf, "#");
893 fptr=&formatbuf[strlen(formatbuf)];
896 /* RECURSIVE USAGE */
897 fptr += curl_msprintf(fptr, "%d", width);
900 /* RECURSIVE USAGE */
901 fptr += curl_msprintf(fptr, ".%d", prec);
903 if (p->flags & FLAGS_LONG)
906 if (p->flags & FLAGS_FLOATE)
907 strcat(fptr, p->flags&FLAGS_UPPER?"E":"e");
908 else if (p->flags & FLAGS_FLOATG)
909 strcat(fptr, (p->flags & FLAGS_UPPER) ? "G" : "g");
913 /* NOTE NOTE NOTE!! Not all sprintf() implementations returns number
914 of output characters */
915 #if SIZEOF_LONG_DOUBLE
916 if (p->flags & FLAGS_LONG)
917 /* This is for support of the 'long double' type */
918 (sprintf)(work, formatbuf, p->data.ldnum);
921 (sprintf)(work, formatbuf, p->data.dnum);
923 for(fptr=work; *fptr; fptr++)
929 /* Answer the count of characters written. */
931 if (p->flags & FLAGS_LONGLONG)
932 *(long long int *) p->data.ptr = done;
935 if (p->flags & FLAGS_LONG)
936 *(long int *) p->data.ptr = done;
937 else if (!(p->flags & FLAGS_SHORT))
938 *(int *) p->data.ptr = done;
940 *(short int *) p->data.ptr = done;
946 f = *end++; /* goto end of %-code */
952 /* fputc() look-alike */
953 static int addbyter(int output, FILE *data)
955 struct nsprintf *infop=(struct nsprintf *)data;
957 if(infop->length < infop->max) {
958 /* only do this if we haven't reached max length yet */
959 infop->buffer[0] = (char)output; /* store */
960 infop->buffer++; /* increase pointer */
961 infop->length++; /* we are now one byte larger */
962 return output; /* fputc() returns like this on success */
967 int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
969 va_list ap_save; /* argument pointer */
971 struct nsprintf info;
973 info.buffer = buffer;
975 info.max = maxlength;
977 va_start(ap_save, format);
978 retcode = dprintf_formatf(&info, addbyter, format, ap_save);
980 info.buffer[0] = 0; /* we terminate this with a zero byte */
982 /* we could even return things like */
987 int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format, va_list ap_save)
990 struct nsprintf info;
992 info.buffer = buffer;
994 info.max = maxlength;
996 retcode = dprintf_formatf(&info, addbyter, format, ap_save);
997 info.buffer[0] = 0; /* we terminate this with a zero byte */
1002 /* fputc() look-alike */
1003 static int alloc_addbyter(int output, FILE *data)
1005 struct asprintf *infop=(struct asprintf *)data;
1007 if(!infop->buffer) {
1008 infop->buffer=(char *)malloc(32);
1010 return -1; /* fail */
1014 else if(infop->len+1 >= infop->alloc) {
1017 newptr = (char *)realloc(infop->buffer, infop->alloc*2);
1022 infop->buffer = newptr;
1026 infop->buffer[ infop->len ] = output;
1030 return output; /* fputc() returns like this on success */
1033 char *curl_maprintf(const char *format, ...)
1035 va_list ap_save; /* argument pointer */
1037 struct asprintf info;
1043 va_start(ap_save, format);
1044 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1052 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1059 char *curl_mvaprintf(const char *format, va_list ap_save)
1062 struct asprintf info;
1068 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1076 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1083 static int storebuffer(int output, FILE *data)
1085 char **buffer = (char **)data;
1086 **buffer = (char)output;
1088 return output; /* act like fputc() ! */
1091 int curl_msprintf(char *buffer, const char *format, ...)
1093 va_list ap_save; /* argument pointer */
1095 va_start(ap_save, format);
1096 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1098 *buffer=0; /* we terminate this with a zero byte */
1102 #ifndef WIN32 /* not needed on win32 */
1103 extern int fputc(int, FILE *);
1106 int curl_mprintf(const char *format, ...)
1109 va_list ap_save; /* argument pointer */
1110 va_start(ap_save, format);
1111 retcode = dprintf_formatf(stdout, fputc, format, ap_save);
1116 int curl_mfprintf(FILE *whereto, const char *format, ...)
1119 va_list ap_save; /* argument pointer */
1120 va_start(ap_save, format);
1121 retcode = dprintf_formatf(whereto, fputc, format, ap_save);
1126 int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
1129 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1130 *buffer=0; /* we terminate this with a zero byte */
1134 int curl_mvprintf(const char *format, va_list ap_save)
1136 return dprintf_formatf(stdout, fputc, format, ap_save);
1139 int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
1141 return dprintf_formatf(whereto, fputc, format, ap_save);
1144 #ifdef DPRINTF_DEBUG
1149 #if SIZEOF_LONG_LONG>0
1151 dprintf("%3$12s %1$s %2$qd %4$d\n", "daniel", hullo, "stenberg", 65);
1154 mprintf("%3d %5d\n", 10, 1998);
1156 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);
1160 memset(ptr, 55, strlen(ptr)+1);
1165 mprintf(buffer, "%s %s %d", "daniel", "stenberg", 19988);
1168 mfprintf(stderr, "%s %#08x\n", "dummy", 65);
1170 printf("%s %#08x\n", "dummy", 65);
1172 double tryout = 3.14156592;
1173 mprintf(buffer, "%.2g %G %f %e %E", tryout, tryout, tryout, tryout, tryout);
1175 printf("%.2g %G %f %e %E\n", tryout, tryout, tryout, tryout, tryout);
1186 * eval: (load-file "../curl-mode.el")
1188 * vim600: fdm=marker
1189 * vim: et sw=2 ts=2 sts=2 tw=78