1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1999 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
23 * A merge of Bjorn Reese's format() function and Daniel's dsprintf()
24 * 1.0. A full blooded printf() clone with full support for <num>$
25 * everywhere (parameters, widths and precisions) including variabled
26 * sized parameters (like doubles, long longs, long doubles and even
27 * void * in 64-bit architectures).
29 * Current restrictions:
30 * - Max 128 parameters
31 * - No 'long double' support.
33 * If you ever want truly portable and good *printf() clones, the project that
34 * took on from here is named 'Trio' and you find more details on the trio web
35 * page at http://daniel.haxx.se/trio/
38 #include "curl_setup.h"
40 #if defined(DJGPP) && (DJGPP_MINOR < 4)
41 #undef _MPRINTF_REPLACE /* don't use x_was_used() here */
44 #include <curl/mprintf.h>
46 #include "curl_memory.h"
47 /* The last #include file should be: */
50 #ifndef SIZEOF_LONG_DOUBLE
51 #define SIZEOF_LONG_DOUBLE 0
55 * If SIZEOF_SIZE_T has not been defined, default to the size of long.
59 # define SIZEOF_SIZE_T CURL_SIZEOF_LONG
63 # define LONG_LONG_TYPE long long
64 # define HAVE_LONG_LONG_TYPE
66 # if defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
67 # define LONG_LONG_TYPE __int64
68 # define HAVE_LONG_LONG_TYPE
70 # undef LONG_LONG_TYPE
71 # undef HAVE_LONG_LONG_TYPE
76 * Max integer data types that mprintf.c is capable
79 #ifdef HAVE_LONG_LONG_TYPE
80 # define mp_intmax_t LONG_LONG_TYPE
81 # define mp_uintmax_t unsigned LONG_LONG_TYPE
83 # define mp_intmax_t long
84 # define mp_uintmax_t unsigned long
87 #define BUFFSIZE 256 /* buffer for long-to-str and float-to-str calcs */
88 #define MAX_PARAMETERS 128 /* lame static limit */
94 /* Lower-case digits. */
95 static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
97 /* Upper-case digits. */
98 static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
102 if(stream((unsigned char)(x), (FILE *)data) != -1) \
105 return done; /* return immediately on failure */ \
108 /* Data type to read from the arglist */
119 FORMAT_WIDTH /* For internal use */
122 /* conversion and display flags */
126 FLAGS_SHOWSIGN = 1<<1,
131 FLAGS_LONGLONG = 1<<6,
132 FLAGS_LONGDOUBLE = 1<<7,
133 FLAGS_PAD_NIL = 1<<8,
134 FLAGS_UNSIGNED = 1<<9,
138 FLAGS_WIDTH = 1<<13, /* '*' or '*<num>$' used */
139 FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */
140 FLAGS_PREC = 1<<15, /* precision was specified */
141 FLAGS_PRECPARAM = 1<<16, /* precision PARAMETER was specified */
142 FLAGS_CHAR = 1<<17, /* %c story */
143 FLAGS_FLOATE = 1<<18, /* %e or %E */
144 FLAGS_FLOATG = 1<<19 /* %g or %G */
150 long width; /* width OR width parameter number */
151 long precision; /* precision OR precision parameter number */
156 mp_intmax_t as_signed;
157 mp_uintmax_t as_unsigned;
170 char *buffer; /* allocated buffer */
171 size_t len; /* length of string */
172 size_t alloc; /* length of alloc */
173 int fail; /* (!= 0) if an alloc has failed and thus
174 the output is not the complete data */
177 static long dprintf_DollarString(char *input, char **end)
180 while(ISDIGIT(*input)) {
182 number += *input-'0';
185 if(number && ('$'==*input++)) {
192 static int dprintf_IsQualifierNoDollar(char c)
195 case '-': case '+': case ' ': case '#': case '.':
196 case '0': case '1': case '2': case '3': case '4':
197 case '5': case '6': case '7': case '8': case '9':
198 case 'h': case 'l': case 'L': case 'z': case 'q':
202 return 0; /* false */
206 /******************************************************************
209 * Create an index with the type of each parameter entry and its
210 * value (may vary in size)
212 ******************************************************************/
214 static long dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
217 char *fmt = (char *)format;
230 continue; /* while */
235 /* Handle the positional case (N$) */
239 this_param = dprintf_DollarString(fmt, &fmt);
241 /* we got no positional, get the next counter */
242 this_param = param_num;
244 if(this_param > max_param)
245 max_param = this_param;
248 * The parameter with number 'i' should be used. Next, we need
249 * to get SIZE and TYPE of the parameter. Add the information
256 /* Handle the flags */
258 while(dprintf_IsQualifierNoDollar(*fmt)) {
261 flags |= FLAGS_SPACE;
264 flags |= FLAGS_SHOWSIGN;
268 flags &= ~FLAGS_PAD_NIL;
276 /* The precision is picked from a specified parameter */
278 flags |= FLAGS_PRECPARAM;
282 i = dprintf_DollarString(fmt, &fmt);
286 precision = param_num;
288 if(precision > max_param)
289 max_param = precision;
293 precision = strtol(fmt, &fmt, 10);
297 flags |= FLAGS_SHORT;
300 if(flags & FLAGS_LONG)
301 flags |= FLAGS_LONGLONG;
306 flags |= FLAGS_LONGDOUBLE;
309 flags |= FLAGS_LONGLONG;
312 /* the code below generates a warning if -Wunreachable-code is
314 #if (SIZEOF_SIZE_T > CURL_SIZEOF_LONG)
315 flags |= FLAGS_LONGLONG;
321 #if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
322 flags |= FLAGS_LONGLONG;
328 if(!(flags & FLAGS_LEFT))
329 flags |= FLAGS_PAD_NIL;
331 case '1': case '2': case '3': case '4':
332 case '5': case '6': case '7': case '8': case '9':
333 flags |= FLAGS_WIDTH;
334 width = strtol(fmt-1, &fmt, 10);
336 case '*': /* Special case */
337 flags |= FLAGS_WIDTHPARAM;
340 i = dprintf_DollarString(fmt, &fmt);
345 if(width > max_param)
353 /* Handle the specifier */
362 vto[i].type = FORMAT_STRING;
365 vto[i].type = FORMAT_INTPTR;
368 vto[i].type = FORMAT_PTR;
371 vto[i].type = FORMAT_INT;
374 vto[i].type = FORMAT_INT;
375 flags |= FLAGS_UNSIGNED;
378 vto[i].type = FORMAT_INT;
379 flags |= FLAGS_OCTAL;
382 vto[i].type = FORMAT_INT;
383 flags |= FLAGS_HEX|FLAGS_UNSIGNED;
386 vto[i].type = FORMAT_INT;
387 flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED;
390 vto[i].type = FORMAT_INT;
394 vto[i].type = FORMAT_DOUBLE;
397 vto[i].type = FORMAT_DOUBLE;
398 flags |= FLAGS_FLOATE;
401 vto[i].type = FORMAT_DOUBLE;
402 flags |= FLAGS_FLOATE|FLAGS_UPPER;
405 vto[i].type = FORMAT_DOUBLE;
406 flags |= FLAGS_FLOATG;
409 vto[i].type = FORMAT_DOUBLE;
410 flags |= FLAGS_FLOATG|FLAGS_UPPER;
413 vto[i].type = FORMAT_UNKNOWN;
417 vto[i].flags = flags;
418 vto[i].width = width;
419 vto[i].precision = precision;
421 if(flags & FLAGS_WIDTHPARAM) {
422 /* we have the width specified from a parameter, so we make that
423 parameter's info setup properly */
424 vto[i].width = width - 1;
426 vto[i].type = FORMAT_WIDTH;
427 vto[i].flags = FLAGS_NEW;
428 vto[i].precision = vto[i].width = 0; /* can't use width or precision
431 if(flags & FLAGS_PRECPARAM) {
432 /* we have the precision specified from a parameter, so we make that
433 parameter's info setup properly */
434 vto[i].precision = precision - 1;
436 vto[i].type = FORMAT_WIDTH;
437 vto[i].flags = FLAGS_NEW;
438 vto[i].precision = vto[i].width = 0; /* can't use width or precision
441 *endpos++ = fmt + 1; /* end of this sequence */
445 /* Read the arg list parameters into our data list */
446 for(i=0; i<max_param; i++) {
447 if((i + 1 < max_param) && (vto[i + 1].type == FORMAT_WIDTH)) {
448 /* Width/precision arguments must be read before the main argument
449 * they are attached to
451 vto[i + 1].data.num.as_signed = (mp_intmax_t)va_arg(arglist, int);
454 switch (vto[i].type) {
456 vto[i].data.str = va_arg(arglist, char *);
462 vto[i].data.ptr = va_arg(arglist, void *);
466 #ifdef HAVE_LONG_LONG_TYPE
467 if((vto[i].flags & FLAGS_LONGLONG) && (vto[i].flags & FLAGS_UNSIGNED))
468 vto[i].data.num.as_unsigned =
469 (mp_uintmax_t)va_arg(arglist, mp_uintmax_t);
470 else if(vto[i].flags & FLAGS_LONGLONG)
471 vto[i].data.num.as_signed =
472 (mp_intmax_t)va_arg(arglist, mp_intmax_t);
476 if((vto[i].flags & FLAGS_LONG) && (vto[i].flags & FLAGS_UNSIGNED))
477 vto[i].data.num.as_unsigned =
478 (mp_uintmax_t)va_arg(arglist, unsigned long);
479 else if(vto[i].flags & FLAGS_LONG)
480 vto[i].data.num.as_signed =
481 (mp_intmax_t)va_arg(arglist, long);
482 else if(vto[i].flags & FLAGS_UNSIGNED)
483 vto[i].data.num.as_unsigned =
484 (mp_uintmax_t)va_arg(arglist, unsigned int);
486 vto[i].data.num.as_signed =
487 (mp_intmax_t)va_arg(arglist, int);
492 vto[i].data.dnum = va_arg(arglist, double);
496 /* Argument has been read. Silently convert it into an integer
499 vto[i].type = FORMAT_INT;
511 static int dprintf_formatf(
512 void *data, /* untouched by format(), just sent to the stream() function in
513 the second argument */
514 /* function pointer called for each output character */
515 int (*stream)(int, FILE *),
516 const char *format, /* %-formatted string */
517 va_list ap_save) /* list of parameters */
519 /* Base-36 digits for numbers. */
520 const char *digits = lower_digits;
522 /* Pointer into the format string. */
525 /* Number of characters written. */
528 long param; /* current parameter to read */
529 long param_num=0; /* parameter counter */
531 va_stack_t vto[MAX_PARAMETERS];
532 char *endpos[MAX_PARAMETERS];
539 /* Do the actual %-code parsing */
540 dprintf_Pass1(format, vto, endpos, ap_save);
542 end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
547 /* Format spec modifiers. */
550 /* Width of a field. */
553 /* Precision of a field. */
556 /* Decimal integer is negative. */
559 /* Base of a number to be written. */
562 /* Integral values to be written. */
565 /* Used to convert negative in positive. */
566 mp_intmax_t signed_num;
569 /* This isn't a format spec, so write everything out until the next one
570 OR end of string is reached. */
573 } while(*++f && ('%' != *f));
579 /* Check for "%%". Note that although the ANSI standard lists
580 '%' as a conversion specifier, it says "The complete format
581 specification shall be `%%'," so we can avoid all the width
582 and precision processing. */
589 /* If this is a positional parameter, the position must follow immediately
590 after the %, thus create a %<num>$ sequence */
591 param=dprintf_DollarString(f, &f);
598 param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
599 third %s will pick the 3rd argument */
603 /* pick up the specified width */
604 if(p->flags & FLAGS_WIDTHPARAM)
605 width = (long)vto[p->width].data.num.as_signed;
609 /* pick up the specified precision */
610 if(p->flags & FLAGS_PRECPARAM) {
611 prec = (long)vto[p->precision].data.num.as_signed;
612 param_num++; /* since the precision is extraced from a parameter, we
613 must skip that to get to the next one properly */
615 else if(p->flags & FLAGS_PREC)
620 is_alt = (p->flags & FLAGS_ALT) ? 1 : 0;
624 num = p->data.num.as_unsigned;
625 if(p->flags & FLAGS_CHAR) {
627 if(!(p->flags & FLAGS_LEFT))
631 if(p->flags & FLAGS_LEFT)
636 if(p->flags & FLAGS_OCTAL) {
637 /* Octal unsigned integer. */
639 goto unsigned_number;
641 else if(p->flags & FLAGS_HEX) {
642 /* Hexadecimal unsigned integer. */
644 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
646 goto unsigned_number;
648 else if(p->flags & FLAGS_UNSIGNED) {
649 /* Decimal unsigned integer. */
651 goto unsigned_number;
654 /* Decimal integer. */
657 is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0;
659 /* signed_num might fail to hold absolute negative minimum by 1 */
660 signed_num = p->data.num.as_signed + (mp_intmax_t)1;
661 signed_num = -signed_num;
662 num = (mp_uintmax_t)signed_num;
663 num += (mp_uintmax_t)1;
669 /* Unsigned number of base BASE. */
673 /* Number of base BASE. */
675 char *workend = &work[sizeof(work) - 1];
678 /* Supply a default precision if none was given. */
682 /* Put the number in WORK. */
685 *w-- = digits[num % base];
688 width -= (long)(workend - w);
689 prec -= (long)(workend - w);
691 if(is_alt && base == 8 && prec <= 0) {
702 if(is_alt && base == 16)
705 if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
708 if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
714 else if(p->flags & FLAGS_SHOWSIGN)
716 else if(p->flags & FLAGS_SPACE)
719 if(is_alt && base == 16) {
721 if(p->flags & FLAGS_UPPER)
727 if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
731 /* Write the number. */
732 while(++w <= workend) {
736 if(p->flags & FLAGS_LEFT)
745 static const char null[] = "(nil)";
749 str = (char *) p->data.str;
751 /* Write null[] if there's space. */
752 if(prec == -1 || prec >= (long) sizeof(null) - 1) {
754 len = sizeof(null) - 1;
755 /* Disable quotes around (nil) */
756 p->flags &= (~FLAGS_ALT);
766 if(prec != -1 && (size_t) prec < len)
770 if(p->flags & FLAGS_ALT)
773 if(!(p->flags&FLAGS_LEFT))
779 if(p->flags&FLAGS_LEFT)
783 if(p->flags & FLAGS_ALT)
789 /* Generic pointer. */
792 ptr = (void *) p->data.ptr;
794 /* If the pointer is not NULL, write it as a %#x spec. */
796 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
803 /* Write "(nil)" for a nil pointer. */
804 static const char strnil[] = "(nil)";
807 width -= (long)(sizeof(strnil) - 1);
808 if(p->flags & FLAGS_LEFT)
811 for(point = strnil; *point != '\0'; ++point)
813 if(! (p->flags & FLAGS_LEFT))
822 char formatbuf[32]="%";
823 char *fptr = &formatbuf[1];
824 size_t left = sizeof(formatbuf)-strlen(formatbuf);
828 if(p->flags & FLAGS_WIDTH)
830 else if(p->flags & FLAGS_WIDTHPARAM)
831 width = (long)vto[p->width].data.num.as_signed;
834 if(p->flags & FLAGS_PREC)
836 else if(p->flags & FLAGS_PRECPARAM)
837 prec = (long)vto[p->precision].data.num.as_signed;
839 if(p->flags & FLAGS_LEFT)
841 if(p->flags & FLAGS_SHOWSIGN)
843 if(p->flags & FLAGS_SPACE)
845 if(p->flags & FLAGS_ALT)
851 /* RECURSIVE USAGE */
852 len = curl_msnprintf(fptr, left, "%ld", width);
857 /* RECURSIVE USAGE */
858 len = curl_msnprintf(fptr, left, ".%ld", prec);
861 if(p->flags & FLAGS_LONG)
864 if(p->flags & FLAGS_FLOATE)
865 *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e');
866 else if(p->flags & FLAGS_FLOATG)
867 *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g');
871 *fptr = 0; /* and a final zero termination */
873 /* NOTE NOTE NOTE!! Not all sprintf implementations return number of
875 (sprintf)(work, formatbuf, p->data.dnum);
877 for(fptr=work; *fptr; fptr++)
883 /* Answer the count of characters written. */
884 #ifdef HAVE_LONG_LONG_TYPE
885 if(p->flags & FLAGS_LONGLONG)
886 *(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done;
889 if(p->flags & FLAGS_LONG)
890 *(long *) p->data.ptr = (long)done;
891 else if(!(p->flags & FLAGS_SHORT))
892 *(int *) p->data.ptr = (int)done;
894 *(short *) p->data.ptr = (short)done;
900 f = *end++; /* goto end of %-code */
906 /* fputc() look-alike */
907 static int addbyter(int output, FILE *data)
909 struct nsprintf *infop=(struct nsprintf *)data;
910 unsigned char outc = (unsigned char)output;
912 if(infop->length < infop->max) {
913 /* only do this if we haven't reached max length yet */
914 infop->buffer[0] = outc; /* store */
915 infop->buffer++; /* increase pointer */
916 infop->length++; /* we are now one byte larger */
917 return outc; /* fputc() returns like this on success */
922 int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
926 struct nsprintf info;
928 info.buffer = buffer;
930 info.max = maxlength;
932 retcode = dprintf_formatf(&info, addbyter, format, ap_save);
934 /* we terminate this with a zero byte */
935 if(info.max == info.length)
936 /* we're at maximum, scrap the last letter */
944 int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
947 va_list ap_save; /* argument pointer */
948 va_start(ap_save, format);
949 retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
954 /* fputc() look-alike */
955 static int alloc_addbyter(int output, FILE *data)
957 struct asprintf *infop=(struct asprintf *)data;
958 unsigned char outc = (unsigned char)output;
961 infop->buffer = malloc(32);
964 return -1; /* fail */
969 else if(infop->len+1 >= infop->alloc) {
972 newptr = realloc(infop->buffer, infop->alloc*2);
976 return -1; /* fail */
978 infop->buffer = newptr;
982 infop->buffer[ infop->len ] = outc;
986 return outc; /* fputc() returns like this on success */
989 char *curl_maprintf(const char *format, ...)
991 va_list ap_save; /* argument pointer */
993 struct asprintf info;
1000 va_start(ap_save, format);
1001 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1003 if((-1 == retcode) || info.fail) {
1009 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1016 char *curl_mvaprintf(const char *format, va_list ap_save)
1019 struct asprintf info;
1026 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1027 if((-1 == retcode) || info.fail) {
1034 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1041 static int storebuffer(int output, FILE *data)
1043 char **buffer = (char **)data;
1044 unsigned char outc = (unsigned char)output;
1047 return outc; /* act like fputc() ! */
1050 int curl_msprintf(char *buffer, const char *format, ...)
1052 va_list ap_save; /* argument pointer */
1054 va_start(ap_save, format);
1055 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1057 *buffer=0; /* we terminate this with a zero byte */
1061 int curl_mprintf(const char *format, ...)
1064 va_list ap_save; /* argument pointer */
1065 va_start(ap_save, format);
1067 retcode = dprintf_formatf(stdout, fputc, format, ap_save);
1072 int curl_mfprintf(FILE *whereto, const char *format, ...)
1075 va_list ap_save; /* argument pointer */
1076 va_start(ap_save, format);
1077 retcode = dprintf_formatf(whereto, fputc, format, ap_save);
1082 int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
1085 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1086 *buffer=0; /* we terminate this with a zero byte */
1090 int curl_mvprintf(const char *format, va_list ap_save)
1092 return dprintf_formatf(stdout, fputc, format, ap_save);
1095 int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
1097 return dprintf_formatf(whereto, fputc, format, ap_save);