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
48 /* default to 4 bytes for size_t unless defined in the config.h */
49 #define SIZEOF_SIZE_T 4
54 #define LONG_LONG long long
59 /* The last #include file should be: */
62 #define BUFFSIZE 256 /* buffer for long-to-str and float-to-str calcs */
63 #define MAX_PARAMETERS 128 /* lame static limit */
73 # define TRUE ((char)(1 == 1))
74 # define FALSE ((char)(0 == 1))
79 /* Lower-case digits. */
80 static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
82 /* Upper-case digits. */
83 static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
87 if(stream((unsigned char)(x), (FILE *)data) != -1) \
90 return done; /* return immediately on failure */ \
93 /* Data type to read from the arglist */
104 FORMAT_WIDTH /* For internal use */
107 /* convertion and display flags */
111 FLAGS_SHOWSIGN = 1<<1,
116 FLAGS_LONGLONG = 1<<6,
117 FLAGS_LONGDOUBLE = 1<<7,
118 FLAGS_PAD_NIL = 1<<8,
119 FLAGS_UNSIGNED = 1<<9,
123 FLAGS_WIDTH = 1<<13, /* '*' or '*<num>$' used */
124 FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */
125 FLAGS_PREC = 1<<15, /* precision was specified */
126 FLAGS_PRECPARAM = 1<<16, /* precision PARAMETER was specified */
127 FLAGS_CHAR = 1<<17, /* %c story */
128 FLAGS_FLOATE = 1<<18, /* %e or %E */
129 FLAGS_FLOATG = 1<<19 /* %g or %G */
135 long width; /* width OR width parameter number */
136 long precision; /* precision OR precision parameter number */
155 char *buffer; /* allocated buffer */
156 size_t len; /* length of string */
157 size_t alloc; /* length of alloc */
158 bool fail; /* TRUE if an alloc has failed and thus the output is not
162 int curl_msprintf(char *buffer, const char *format, ...);
164 static long dprintf_DollarString(char *input, char **end)
167 while(isdigit((int)*input)) {
169 number += *input-'0';
172 if(number && ('$'==*input++)) {
179 static BOOL dprintf_IsQualifierNoDollar(char c)
182 case '-': case '+': case ' ': case '#': case '.':
183 case '0': case '1': case '2': case '3': case '4':
184 case '5': case '6': case '7': case '8': case '9':
185 case 'h': case 'l': case 'L': case 'z': case 'q':
193 #ifdef DPRINTF_DEBUG2
194 int dprintf_Pass1Report(va_stack_t *vto, int max)
201 for(i=0; i<max; i++) {
203 switch(vto[i].type) {
219 case FORMAT_LONGLONG:
225 case FORMAT_LONGDOUBLE:
226 type = "long double";
233 for(bit=0; bit<31; bit++) {
234 flags = vto[i].flags & (1<<bit);
236 if(flags & FLAGS_SPACE)
237 strcat(buffer, "space ");
238 else if(flags & FLAGS_SHOWSIGN)
239 strcat(buffer, "plus ");
240 else if(flags & FLAGS_LEFT)
241 strcat(buffer, "left ");
242 else if(flags & FLAGS_ALT)
243 strcat(buffer, "alt ");
244 else if(flags & FLAGS_SHORT)
245 strcat(buffer, "short ");
246 else if(flags & FLAGS_LONG)
247 strcat(buffer, "long ");
248 else if(flags & FLAGS_LONGLONG)
249 strcat(buffer, "longlong ");
250 else if(flags & FLAGS_LONGDOUBLE)
251 strcat(buffer, "longdouble ");
252 else if(flags & FLAGS_PAD_NIL)
253 strcat(buffer, "padnil ");
254 else if(flags & FLAGS_UNSIGNED)
255 strcat(buffer, "unsigned ");
256 else if(flags & FLAGS_OCTAL)
257 strcat(buffer, "octal ");
258 else if(flags & FLAGS_HEX)
259 strcat(buffer, "hex ");
260 else if(flags & FLAGS_UPPER)
261 strcat(buffer, "upper ");
262 else if(flags & FLAGS_WIDTH)
263 strcat(buffer, "width ");
264 else if(flags & FLAGS_WIDTHPARAM)
265 strcat(buffer, "widthparam ");
266 else if(flags & FLAGS_PREC)
267 strcat(buffer, "precision ");
268 else if(flags & FLAGS_PRECPARAM)
269 strcat(buffer, "precparam ");
270 else if(flags & FLAGS_CHAR)
271 strcat(buffer, "char ");
272 else if(flags & FLAGS_FLOATE)
273 strcat(buffer, "floate ");
274 else if(flags & FLAGS_FLOATG)
275 strcat(buffer, "floatg ");
277 printf("REPORT: %d. %s [%s]\n", i, type, buffer);
285 /******************************************************************
288 * Create an index with the type of each parameter entry and its
289 * value (may vary in size)
291 ******************************************************************/
293 static long dprintf_Pass1(char *format, va_stack_t *vto, char **endpos,
309 continue; /* while */
314 /* Handle the positional case (N$) */
318 this_param = dprintf_DollarString(fmt, &fmt);
320 /* we got no positional, get the next counter */
321 this_param = param_num;
323 if (this_param > max_param)
324 max_param = this_param;
327 * The parameter with number 'i' should be used. Next, we need
328 * to get SIZE and TYPE of the parameter. Add the information
335 /* Handle the flags */
337 while (dprintf_IsQualifierNoDollar(*fmt)) {
340 flags |= FLAGS_SPACE;
343 flags |= FLAGS_SHOWSIGN;
347 flags &= ~FLAGS_PAD_NIL;
355 /* The precision is picked from a specified parameter */
357 flags |= FLAGS_PRECPARAM;
361 i = dprintf_DollarString(fmt, &fmt);
365 precision = param_num;
367 if (precision > max_param)
368 max_param = precision;
372 precision = strtol(fmt, &fmt, 10);
376 flags |= FLAGS_SHORT;
379 if (flags & FLAGS_LONG)
380 flags |= FLAGS_LONGLONG;
385 flags |= FLAGS_LONGDOUBLE;
388 flags |= FLAGS_LONGLONG;
391 /* the code below generates a warning if -Wunreachable-code is
394 flags |= FLAGS_LONGLONG;
400 #if SIZEOF_CURL_OFF_T > 4
401 flags |= FLAGS_LONGLONG;
407 if (!(flags & FLAGS_LEFT))
408 flags |= FLAGS_PAD_NIL;
410 case '1': case '2': case '3': case '4':
411 case '5': case '6': case '7': case '8': case '9':
412 flags |= FLAGS_WIDTH;
413 width = strtol(fmt-1, &fmt, 10);
415 case '*': /* Special case */
416 flags |= FLAGS_WIDTHPARAM;
419 i = dprintf_DollarString(fmt, &fmt);
424 if(width > max_param)
432 /* Handle the specifier */
441 vto[i].type = FORMAT_STRING;
444 vto[i].type = FORMAT_INTPTR;
447 vto[i].type = FORMAT_PTR;
450 vto[i].type = FORMAT_INT;
453 vto[i].type = FORMAT_INT;
454 flags |= FLAGS_UNSIGNED;
457 vto[i].type = FORMAT_INT;
458 flags |= FLAGS_OCTAL;
461 vto[i].type = FORMAT_INT;
465 vto[i].type = FORMAT_INT;
466 flags |= FLAGS_HEX|FLAGS_UPPER;
469 vto[i].type = FORMAT_INT;
473 vto[i].type = FORMAT_DOUBLE;
476 vto[i].type = FORMAT_DOUBLE;
477 flags |= FLAGS_FLOATE;
480 vto[i].type = FORMAT_DOUBLE;
481 flags |= FLAGS_FLOATE|FLAGS_UPPER;
484 vto[i].type = FORMAT_DOUBLE;
485 flags |= FLAGS_FLOATG;
488 vto[i].type = FORMAT_DOUBLE;
489 flags |= FLAGS_FLOATG|FLAGS_UPPER;
492 vto[i].type = FORMAT_UNKNOWN;
496 vto[i].flags = flags;
497 vto[i].width = width;
498 vto[i].precision = precision;
500 if (flags & FLAGS_WIDTHPARAM) {
501 /* we have the width specified from a parameter, so we make that
502 parameter's info setup properly */
503 vto[i].width = width - 1;
505 vto[i].type = FORMAT_WIDTH;
506 vto[i].flags = FLAGS_NEW;
507 vto[i].precision = vto[i].width = 0; /* can't use width or precision
510 if (flags & FLAGS_PRECPARAM) {
511 /* we have the precision specified from a parameter, so we make that
512 parameter's info setup properly */
513 vto[i].precision = precision - 1;
515 vto[i].type = FORMAT_WIDTH;
516 vto[i].flags = FLAGS_NEW;
517 vto[i].precision = vto[i].width = 0; /* can't use width or precision
520 *endpos++ = fmt + 1; /* end of this sequence */
524 #ifdef DPRINTF_DEBUG2
525 dprintf_Pass1Report(vto, max_param);
528 /* Read the arg list parameters into our data list */
529 for (i=0; i<max_param; i++) {
530 if ((i + 1 < max_param) && (vto[i + 1].type == FORMAT_WIDTH))
532 /* Width/precision arguments must be read before the main argument
533 * they are attached to
535 vto[i + 1].data.num = va_arg(arglist, int);
541 vto[i].data.str = va_arg(arglist, char *);
547 vto[i].data.ptr = va_arg(arglist, void *);
552 if(vto[i].flags & FLAGS_LONGLONG)
553 vto[i].data.lnum = va_arg(arglist, LONG_LONG);
556 if(vto[i].flags & FLAGS_LONG)
557 vto[i].data.num = va_arg(arglist, long);
559 vto[i].data.num = va_arg(arglist, int);
563 vto[i].data.dnum = va_arg(arglist, double);
567 /* Argument has been read. Silently convert it into an integer
570 vto[i].type = FORMAT_INT;
582 static int dprintf_formatf(
583 void *data, /* untouched by format(), just sent to the stream() function in
584 the second argument */
585 /* function pointer called for each output character */
586 int (*stream)(int, FILE *),
587 const char *format, /* %-formatted string */
588 va_list ap_save) /* list of parameters */
590 /* Base-36 digits for numbers. */
591 const char *digits = lower_digits;
593 /* Pointer into the format string. */
596 /* Number of characters written. */
599 long param; /* current parameter to read */
600 long param_num=0; /* parameter counter */
602 va_stack_t vto[MAX_PARAMETERS];
603 char *endpos[MAX_PARAMETERS];
610 /* Do the actual %-code parsing */
611 dprintf_Pass1((char *)format, vto, endpos, ap_save);
613 end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
618 /* Format spec modifiers. */
621 /* Width of a field. */
624 /* Precision of a field. */
627 /* Decimal integer is negative. */
630 /* Base of a number to be written. */
633 /* Integral values to be written. */
635 unsigned LONG_LONG num;
642 /* This isn't a format spec, so write everything out until the next one
643 OR end of string is reached. */
646 } while(*++f && ('%' != *f));
652 /* Check for "%%". Note that although the ANSI standard lists
653 '%' as a conversion specifier, it says "The complete format
654 specification shall be `%%'," so we can avoid all the width
655 and precision processing. */
662 /* If this is a positional parameter, the position must follow imediately
663 after the %, thus create a %<num>$ sequence */
664 param=dprintf_DollarString(f, &f);
671 param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
672 third %s will pick the 3rd argument */
676 /* pick up the specified width */
677 if(p->flags & FLAGS_WIDTHPARAM)
678 width = vto[p->width].data.num;
682 /* pick up the specified precision */
683 if(p->flags & FLAGS_PRECPARAM)
684 prec = vto[p->precision].data.num;
685 else if(p->flags & FLAGS_PREC)
690 alt = (p->flags & FLAGS_ALT)?TRUE:FALSE;
695 if(p->flags & FLAGS_CHAR) {
697 if (!(p->flags & FLAGS_LEFT))
701 if (p->flags & FLAGS_LEFT)
706 if(p->flags & FLAGS_UNSIGNED) {
707 /* Decimal unsigned integer. */
709 goto unsigned_number;
711 if(p->flags & FLAGS_OCTAL) {
712 /* Octal unsigned integer. */
714 goto unsigned_number;
716 if(p->flags & FLAGS_HEX) {
717 /* Hexadecimal unsigned integer. */
719 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
721 goto unsigned_number;
724 /* Decimal integer. */
728 if(p->flags & FLAGS_LONGLONG) {
730 is_neg = p->data.lnum < 0;
731 num = is_neg ? (- p->data.lnum) : p->data.lnum;
736 signed_num = (long) num;
737 is_neg = signed_num < 0;
738 num = is_neg ? (- signed_num) : signed_num;
743 /* Unsigned number of base BASE. */
747 /* Number of base BASE. */
749 char *workend = &work[sizeof(work) - 1];
752 /* Supply a default precision if none was given. */
756 /* Put the number in WORK. */
759 *w-- = digits[num % base];
762 width -= workend - w;
765 if (alt && base == 8 && prec <= 0) {
776 if (alt && base == 16)
779 if (is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
782 if (!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
788 else if (p->flags & FLAGS_SHOWSIGN)
790 else if (p->flags & FLAGS_SPACE)
793 if (alt && base == 16) {
795 if(p->flags & FLAGS_UPPER)
801 if (!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
805 /* Write the number. */
806 while (++w <= workend) {
810 if (p->flags & FLAGS_LEFT)
819 static char null[] = "(nil)";
823 str = (char *) p->data.str;
825 /* Write null[] if there's space. */
826 if (prec == -1 || prec >= (long) sizeof(null) - 1) {
828 len = sizeof(null) - 1;
829 /* Disable quotes around (nil) */
830 p->flags &= (~FLAGS_ALT);
840 if (prec != -1 && (size_t) prec < len)
844 if (p->flags & FLAGS_ALT)
847 if (!(p->flags&FLAGS_LEFT))
853 if (p->flags&FLAGS_LEFT)
857 if (p->flags & FLAGS_ALT)
863 /* Generic pointer. */
866 ptr = (void *) p->data.ptr;
868 /* If the pointer is not NULL, write it as a %#x spec. */
870 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
872 num = (unsigned long) ptr;
877 /* Write "(nil)" for a nil pointer. */
878 static char strnil[] = "(nil)";
881 width -= sizeof(strnil) - 1;
882 if (p->flags & FLAGS_LEFT)
885 for (point = strnil; *point != '\0'; ++point)
887 if (! (p->flags & FLAGS_LEFT))
896 char formatbuf[32]="%";
898 size_t left = sizeof(formatbuf)-strlen(formatbuf);
902 if (p->flags & FLAGS_WIDTH)
904 else if (p->flags & FLAGS_WIDTHPARAM)
905 width = vto[p->width].data.num;
908 if (p->flags & FLAGS_PREC)
910 else if (p->flags & FLAGS_PRECPARAM)
911 prec = vto[p->precision].data.num;
913 if (p->flags & FLAGS_LEFT)
914 strcat(formatbuf, "-");
915 if (p->flags & FLAGS_SHOWSIGN)
916 strcat(formatbuf, "+");
917 if (p->flags & FLAGS_SPACE)
918 strcat(formatbuf, " ");
919 if (p->flags & FLAGS_ALT)
920 strcat(formatbuf, "#");
922 fptr=&formatbuf[strlen(formatbuf)];
925 /* RECURSIVE USAGE */
926 len = curl_msnprintf(fptr, left, "%ld", width);
931 /* RECURSIVE USAGE */
932 len = curl_msnprintf(fptr, left, ".%ld", prec);
936 if (p->flags & FLAGS_LONG)
939 if (p->flags & FLAGS_FLOATE)
940 *fptr++ = p->flags&FLAGS_UPPER ? 'E':'e';
941 else if (p->flags & FLAGS_FLOATG)
942 *fptr++ = p->flags & FLAGS_UPPER ? 'G' : 'g';
946 *fptr = 0; /* and a final zero termination */
948 /* NOTE NOTE NOTE!! Not all sprintf() implementations returns number
949 of output characters */
950 (sprintf)(work, formatbuf, p->data.dnum);
952 for(fptr=work; *fptr; fptr++)
958 /* Answer the count of characters written. */
960 if (p->flags & FLAGS_LONGLONG)
961 *(LONG_LONG *) p->data.ptr = (LONG_LONG)done;
964 if (p->flags & FLAGS_LONG)
965 *(long *) p->data.ptr = (long)done;
966 else if (!(p->flags & FLAGS_SHORT))
967 *(int *) p->data.ptr = (int)done;
969 *(short *) p->data.ptr = (short)done;
975 f = *end++; /* goto end of %-code */
981 /* fputc() look-alike */
982 static int addbyter(int output, FILE *data)
984 struct nsprintf *infop=(struct nsprintf *)data;
985 unsigned char outc = (unsigned char)output;
987 if(infop->length < infop->max) {
988 /* only do this if we haven't reached max length yet */
989 infop->buffer[0] = outc; /* store */
990 infop->buffer++; /* increase pointer */
991 infop->length++; /* we are now one byte larger */
992 return outc; /* fputc() returns like this on success */
997 int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
1001 struct nsprintf info;
1003 info.buffer = buffer;
1005 info.max = maxlength;
1007 retcode = dprintf_formatf(&info, addbyter, format, ap_save);
1009 /* we terminate this with a zero byte */
1010 if(info.max == info.length)
1011 /* we're at maximum, scrap the last letter */
1012 info.buffer[-1] = 0;
1019 int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
1022 va_list ap_save; /* argument pointer */
1023 va_start(ap_save, format);
1024 retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
1029 /* fputc() look-alike */
1030 static int alloc_addbyter(int output, FILE *data)
1032 struct asprintf *infop=(struct asprintf *)data;
1033 unsigned char outc = (unsigned char)output;
1035 if(!infop->buffer) {
1036 infop->buffer=(char *)malloc(32);
1037 if(!infop->buffer) {
1039 return -1; /* fail */
1044 else if(infop->len+1 >= infop->alloc) {
1047 newptr = (char *)realloc(infop->buffer, infop->alloc*2);
1053 infop->buffer = newptr;
1057 infop->buffer[ infop->len ] = outc;
1061 return outc; /* fputc() returns like this on success */
1064 char *curl_maprintf(const char *format, ...)
1066 va_list ap_save; /* argument pointer */
1068 struct asprintf info;
1075 va_start(ap_save, format);
1076 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1078 if((-1 == retcode) || info.fail) {
1084 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1091 char *curl_mvaprintf(const char *format, va_list ap_save)
1094 struct asprintf info;
1101 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1102 if((-1 == retcode) || info.fail) {
1109 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1116 static int storebuffer(int output, FILE *data)
1118 char **buffer = (char **)data;
1119 unsigned char outc = (unsigned char)output;
1122 return outc; /* act like fputc() ! */
1125 int curl_msprintf(char *buffer, const char *format, ...)
1127 va_list ap_save; /* argument pointer */
1129 va_start(ap_save, format);
1130 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1132 *buffer=0; /* we terminate this with a zero byte */
1136 #ifndef WIN32 /* not needed on win32 */
1137 extern int fputc(int, FILE *);
1140 int curl_mprintf(const char *format, ...)
1143 va_list ap_save; /* argument pointer */
1144 va_start(ap_save, format);
1146 retcode = dprintf_formatf(stdout, fputc, format, ap_save);
1151 int curl_mfprintf(FILE *whereto, const char *format, ...)
1154 va_list ap_save; /* argument pointer */
1155 va_start(ap_save, format);
1156 retcode = dprintf_formatf(whereto, fputc, format, ap_save);
1161 int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
1164 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1165 *buffer=0; /* we terminate this with a zero byte */
1169 int curl_mvprintf(const char *format, va_list ap_save)
1171 return dprintf_formatf(stdout, fputc, format, ap_save);
1174 int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
1176 return dprintf_formatf(whereto, fputc, format, ap_save);
1179 #ifdef DPRINTF_DEBUG
1187 long long test = 0x1000000000LL;
1188 curl_mprintf("%lld %lld %lld\n", one, two, test);
1191 curl_mprintf("%3d %5d\n", 10, 1998);
1193 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);
1197 memset(ptr, 55, strlen(ptr)+1);
1202 curl_mprintf(buffer, "%s %s %d", "daniel", "stenberg", 19988);
1205 curl_mfprintf(stderr, "%s %#08x\n", "dummy", 65);
1207 printf("%s %#08x\n", "dummy", 65);
1209 double tryout = 3.14156592;
1210 curl_mprintf(buffer, "%.2g %G %f %e %E", tryout, tryout, tryout, tryout, tryout);
1212 printf("%.2g %G %f %e %E\n", tryout, tryout, tryout, tryout, tryout);