1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1999 - 2014, 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 * Non-ANSI integer extensions
79 #if (defined(__BORLANDC__) && (__BORLANDC__ >= 0x520)) || \
80 (defined(__WATCOMC__) && defined(__386__)) || \
81 (defined(__POCC__) && defined(_MSC_VER)) || \
82 (defined(_WIN32_WCE)) || \
83 (defined(__MINGW32__)) || \
84 (defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64))
85 # define MP_HAVE_INT_EXTENSIONS
89 * Max integer data types that mprintf.c is capable
92 #ifdef HAVE_LONG_LONG_TYPE
93 # define mp_intmax_t LONG_LONG_TYPE
94 # define mp_uintmax_t unsigned LONG_LONG_TYPE
96 # define mp_intmax_t long
97 # define mp_uintmax_t unsigned long
100 #define BUFFSIZE 256 /* buffer for long-to-str and float-to-str calcs */
101 #define MAX_PARAMETERS 128 /* lame static limit */
107 /* Lower-case digits. */
108 static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
110 /* Upper-case digits. */
111 static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
115 if(stream((unsigned char)(x), (FILE *)data) != -1) \
118 return done; /* return immediately on failure */ \
121 /* Data type to read from the arglist */
132 FORMAT_WIDTH /* For internal use */
135 /* conversion and display flags */
139 FLAGS_SHOWSIGN = 1<<1,
144 FLAGS_LONGLONG = 1<<6,
145 FLAGS_LONGDOUBLE = 1<<7,
146 FLAGS_PAD_NIL = 1<<8,
147 FLAGS_UNSIGNED = 1<<9,
151 FLAGS_WIDTH = 1<<13, /* '*' or '*<num>$' used */
152 FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */
153 FLAGS_PREC = 1<<15, /* precision was specified */
154 FLAGS_PRECPARAM = 1<<16, /* precision PARAMETER was specified */
155 FLAGS_CHAR = 1<<17, /* %c story */
156 FLAGS_FLOATE = 1<<18, /* %e or %E */
157 FLAGS_FLOATG = 1<<19 /* %g or %G */
163 long width; /* width OR width parameter number */
164 long precision; /* precision OR precision parameter number */
169 mp_intmax_t as_signed;
170 mp_uintmax_t as_unsigned;
183 char *buffer; /* allocated buffer */
184 size_t len; /* length of string */
185 size_t alloc; /* length of alloc */
186 int fail; /* (!= 0) if an alloc has failed and thus
187 the output is not the complete data */
190 static long dprintf_DollarString(char *input, char **end)
193 while(ISDIGIT(*input)) {
195 number += *input-'0';
198 if(number && ('$'==*input++)) {
205 static bool dprintf_IsQualifierNoDollar(const char *fmt)
207 #if defined(MP_HAVE_INT_EXTENSIONS)
208 if(!strncmp(fmt, "I32", 3) || !strncmp(fmt, "I64", 3)) {
214 case '-': case '+': case ' ': case '#': case '.':
215 case '0': case '1': case '2': case '3': case '4':
216 case '5': case '6': case '7': case '8': case '9':
217 case 'h': case 'l': case 'L': case 'z': case 'q':
219 #if defined(MP_HAVE_INT_EXTENSIONS)
229 /******************************************************************
232 * Create an index with the type of each parameter entry and its
233 * value (may vary in size)
235 ******************************************************************/
237 static long dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
240 char *fmt = (char *)format;
253 continue; /* while */
258 /* Handle the positional case (N$) */
262 this_param = dprintf_DollarString(fmt, &fmt);
264 /* we got no positional, get the next counter */
265 this_param = param_num;
267 if(this_param > max_param)
268 max_param = this_param;
271 * The parameter with number 'i' should be used. Next, we need
272 * to get SIZE and TYPE of the parameter. Add the information
279 /* Handle the flags */
281 while(dprintf_IsQualifierNoDollar(fmt)) {
282 #if defined(MP_HAVE_INT_EXTENSIONS)
283 if(!strncmp(fmt, "I32", 3)) {
287 else if(!strncmp(fmt, "I64", 3)) {
288 flags |= FLAGS_LONGLONG;
296 flags |= FLAGS_SPACE;
299 flags |= FLAGS_SHOWSIGN;
303 flags &= ~FLAGS_PAD_NIL;
311 /* The precision is picked from a specified parameter */
313 flags |= FLAGS_PRECPARAM;
317 i = dprintf_DollarString(fmt, &fmt);
321 precision = param_num;
323 if(precision > max_param)
324 max_param = precision;
328 precision = strtol(fmt, &fmt, 10);
332 flags |= FLAGS_SHORT;
334 #if defined(MP_HAVE_INT_EXTENSIONS)
336 #if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
337 flags |= FLAGS_LONGLONG;
344 if(flags & FLAGS_LONG)
345 flags |= FLAGS_LONGLONG;
350 flags |= FLAGS_LONGDOUBLE;
353 flags |= FLAGS_LONGLONG;
356 /* the code below generates a warning if -Wunreachable-code is
358 #if (SIZEOF_SIZE_T > CURL_SIZEOF_LONG)
359 flags |= FLAGS_LONGLONG;
365 #if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
366 flags |= FLAGS_LONGLONG;
372 if(!(flags & FLAGS_LEFT))
373 flags |= FLAGS_PAD_NIL;
375 case '1': case '2': case '3': case '4':
376 case '5': case '6': case '7': case '8': case '9':
377 flags |= FLAGS_WIDTH;
378 width = strtol(fmt-1, &fmt, 10);
380 case '*': /* Special case */
381 flags |= FLAGS_WIDTHPARAM;
384 i = dprintf_DollarString(fmt, &fmt);
389 if(width > max_param)
397 /* Handle the specifier */
406 vto[i].type = FORMAT_STRING;
409 vto[i].type = FORMAT_INTPTR;
412 vto[i].type = FORMAT_PTR;
415 vto[i].type = FORMAT_INT;
418 vto[i].type = FORMAT_INT;
419 flags |= FLAGS_UNSIGNED;
422 vto[i].type = FORMAT_INT;
423 flags |= FLAGS_OCTAL;
426 vto[i].type = FORMAT_INT;
427 flags |= FLAGS_HEX|FLAGS_UNSIGNED;
430 vto[i].type = FORMAT_INT;
431 flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED;
434 vto[i].type = FORMAT_INT;
438 vto[i].type = FORMAT_DOUBLE;
441 vto[i].type = FORMAT_DOUBLE;
442 flags |= FLAGS_FLOATE;
445 vto[i].type = FORMAT_DOUBLE;
446 flags |= FLAGS_FLOATE|FLAGS_UPPER;
449 vto[i].type = FORMAT_DOUBLE;
450 flags |= FLAGS_FLOATG;
453 vto[i].type = FORMAT_DOUBLE;
454 flags |= FLAGS_FLOATG|FLAGS_UPPER;
457 vto[i].type = FORMAT_UNKNOWN;
461 vto[i].flags = flags;
462 vto[i].width = width;
463 vto[i].precision = precision;
465 if(flags & FLAGS_WIDTHPARAM) {
466 /* we have the width specified from a parameter, so we make that
467 parameter's info setup properly */
468 vto[i].width = width - 1;
470 vto[i].type = FORMAT_WIDTH;
471 vto[i].flags = FLAGS_NEW;
472 vto[i].precision = vto[i].width = 0; /* can't use width or precision
475 if(flags & FLAGS_PRECPARAM) {
476 /* we have the precision specified from a parameter, so we make that
477 parameter's info setup properly */
478 vto[i].precision = precision - 1;
480 vto[i].type = FORMAT_WIDTH;
481 vto[i].flags = FLAGS_NEW;
482 vto[i].precision = vto[i].width = 0; /* can't use width or precision
485 *endpos++ = fmt + 1; /* end of this sequence */
489 /* Read the arg list parameters into our data list */
490 for(i=0; i<max_param; i++) {
491 if((i + 1 < max_param) && (vto[i + 1].type == FORMAT_WIDTH)) {
492 /* Width/precision arguments must be read before the main argument
493 * they are attached to
495 vto[i + 1].data.num.as_signed = (mp_intmax_t)va_arg(arglist, int);
498 switch (vto[i].type) {
500 vto[i].data.str = va_arg(arglist, char *);
506 vto[i].data.ptr = va_arg(arglist, void *);
510 #ifdef HAVE_LONG_LONG_TYPE
511 if((vto[i].flags & FLAGS_LONGLONG) && (vto[i].flags & FLAGS_UNSIGNED))
512 vto[i].data.num.as_unsigned =
513 (mp_uintmax_t)va_arg(arglist, mp_uintmax_t);
514 else if(vto[i].flags & FLAGS_LONGLONG)
515 vto[i].data.num.as_signed =
516 (mp_intmax_t)va_arg(arglist, mp_intmax_t);
520 if((vto[i].flags & FLAGS_LONG) && (vto[i].flags & FLAGS_UNSIGNED))
521 vto[i].data.num.as_unsigned =
522 (mp_uintmax_t)va_arg(arglist, unsigned long);
523 else if(vto[i].flags & FLAGS_LONG)
524 vto[i].data.num.as_signed =
525 (mp_intmax_t)va_arg(arglist, long);
526 else if(vto[i].flags & FLAGS_UNSIGNED)
527 vto[i].data.num.as_unsigned =
528 (mp_uintmax_t)va_arg(arglist, unsigned int);
530 vto[i].data.num.as_signed =
531 (mp_intmax_t)va_arg(arglist, int);
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 stream() function in
557 the second argument */
558 /* function pointer called for each output character */
559 int (*stream)(int, FILE *),
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. */
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(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. */
597 /* Precision of a field. */
600 /* Decimal integer is negative. */
603 /* Base of a number to be written. */
606 /* Integral values to be written. */
609 /* Used to convert negative in positive. */
610 mp_intmax_t signed_num;
613 /* This isn't a format spec, so write everything out until the next one
614 OR end of string is reached. */
617 } while(*++f && ('%' != *f));
623 /* Check for "%%". Note that although the ANSI standard lists
624 '%' as a conversion specifier, it says "The complete format
625 specification shall be `%%'," so we can avoid all the width
626 and precision processing. */
633 /* If this is a positional parameter, the position must follow immediately
634 after the %, thus create a %<num>$ sequence */
635 param=dprintf_DollarString(f, &f);
642 param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
643 third %s will pick the 3rd argument */
647 /* pick up the specified width */
648 if(p->flags & FLAGS_WIDTHPARAM)
649 width = (long)vto[p->width].data.num.as_signed;
653 /* pick up the specified precision */
654 if(p->flags & FLAGS_PRECPARAM) {
655 prec = (long)vto[p->precision].data.num.as_signed;
656 param_num++; /* since the precision is extraced from a parameter, we
657 must skip that to get to the next one properly */
659 else if(p->flags & FLAGS_PREC)
664 is_alt = (p->flags & FLAGS_ALT) ? 1 : 0;
668 num = p->data.num.as_unsigned;
669 if(p->flags & FLAGS_CHAR) {
671 if(!(p->flags & FLAGS_LEFT))
675 if(p->flags & FLAGS_LEFT)
680 if(p->flags & FLAGS_OCTAL) {
681 /* Octal unsigned integer. */
683 goto unsigned_number;
685 else if(p->flags & FLAGS_HEX) {
686 /* Hexadecimal unsigned integer. */
688 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
690 goto unsigned_number;
692 else if(p->flags & FLAGS_UNSIGNED) {
693 /* Decimal unsigned integer. */
695 goto unsigned_number;
698 /* Decimal integer. */
701 is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0;
703 /* signed_num might fail to hold absolute negative minimum by 1 */
704 signed_num = p->data.num.as_signed + (mp_intmax_t)1;
705 signed_num = -signed_num;
706 num = (mp_uintmax_t)signed_num;
707 num += (mp_uintmax_t)1;
713 /* Unsigned number of base BASE. */
717 /* Number of base BASE. */
719 char *workend = &work[sizeof(work) - 1];
722 /* Supply a default precision if none was given. */
726 /* Put the number in WORK. */
729 *w-- = digits[num % base];
732 width -= (long)(workend - w);
733 prec -= (long)(workend - w);
735 if(is_alt && base == 8 && prec <= 0) {
746 if(is_alt && base == 16)
749 if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
752 if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
758 else if(p->flags & FLAGS_SHOWSIGN)
760 else if(p->flags & FLAGS_SPACE)
763 if(is_alt && base == 16) {
765 if(p->flags & FLAGS_UPPER)
771 if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
775 /* Write the number. */
776 while(++w <= workend) {
780 if(p->flags & FLAGS_LEFT)
789 static const char null[] = "(nil)";
793 str = (char *) p->data.str;
795 /* Write null[] if there's space. */
796 if(prec == -1 || prec >= (long) sizeof(null) - 1) {
798 len = sizeof(null) - 1;
799 /* Disable quotes around (nil) */
800 p->flags &= (~FLAGS_ALT);
814 if(p->flags & FLAGS_ALT)
817 if(!(p->flags&FLAGS_LEFT))
821 while((len-- > 0) && *str)
823 if(p->flags&FLAGS_LEFT)
827 if(p->flags & FLAGS_ALT)
833 /* Generic pointer. */
836 ptr = (void *) p->data.ptr;
838 /* If the pointer is not NULL, write it as a %#x spec. */
840 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
847 /* Write "(nil)" for a nil pointer. */
848 static const char strnil[] = "(nil)";
851 width -= (long)(sizeof(strnil) - 1);
852 if(p->flags & FLAGS_LEFT)
855 for(point = strnil; *point != '\0'; ++point)
857 if(! (p->flags & FLAGS_LEFT))
866 char formatbuf[32]="%";
867 char *fptr = &formatbuf[1];
868 size_t left = sizeof(formatbuf)-strlen(formatbuf);
872 if(p->flags & FLAGS_WIDTH)
874 else if(p->flags & FLAGS_WIDTHPARAM)
875 width = (long)vto[p->width].data.num.as_signed;
878 if(p->flags & FLAGS_PREC)
880 else if(p->flags & FLAGS_PRECPARAM)
881 prec = (long)vto[p->precision].data.num.as_signed;
883 if(p->flags & FLAGS_LEFT)
885 if(p->flags & FLAGS_SHOWSIGN)
887 if(p->flags & FLAGS_SPACE)
889 if(p->flags & FLAGS_ALT)
895 /* RECURSIVE USAGE */
896 len = curl_msnprintf(fptr, left, "%ld", width);
901 /* RECURSIVE USAGE */
902 len = curl_msnprintf(fptr, left, ".%ld", prec);
905 if(p->flags & FLAGS_LONG)
908 if(p->flags & FLAGS_FLOATE)
909 *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e');
910 else if(p->flags & FLAGS_FLOATG)
911 *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g');
915 *fptr = 0; /* and a final zero termination */
917 /* NOTE NOTE NOTE!! Not all sprintf implementations return number of
919 (sprintf)(work, formatbuf, p->data.dnum);
921 for(fptr=work; *fptr; fptr++)
927 /* Answer the count of characters written. */
928 #ifdef HAVE_LONG_LONG_TYPE
929 if(p->flags & FLAGS_LONGLONG)
930 *(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done;
933 if(p->flags & FLAGS_LONG)
934 *(long *) p->data.ptr = (long)done;
935 else if(!(p->flags & FLAGS_SHORT))
936 *(int *) p->data.ptr = (int)done;
938 *(short *) p->data.ptr = (short)done;
944 f = *end++; /* goto end of %-code */
950 /* fputc() look-alike */
951 static int addbyter(int output, FILE *data)
953 struct nsprintf *infop=(struct nsprintf *)data;
954 unsigned char outc = (unsigned char)output;
956 if(infop->length < infop->max) {
957 /* only do this if we haven't reached max length yet */
958 infop->buffer[0] = outc; /* store */
959 infop->buffer++; /* increase pointer */
960 infop->length++; /* we are now one byte larger */
961 return outc; /* fputc() returns like this on success */
966 int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
970 struct nsprintf info;
972 info.buffer = buffer;
974 info.max = maxlength;
976 retcode = dprintf_formatf(&info, addbyter, format, ap_save);
978 /* we terminate this with a zero byte */
979 if(info.max == info.length)
980 /* we're at maximum, scrap the last letter */
988 int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
991 va_list ap_save; /* argument pointer */
992 va_start(ap_save, format);
993 retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
998 /* fputc() look-alike */
999 static int alloc_addbyter(int output, FILE *data)
1001 struct asprintf *infop=(struct asprintf *)data;
1002 unsigned char outc = (unsigned char)output;
1004 if(!infop->buffer) {
1005 infop->buffer = malloc(32);
1006 if(!infop->buffer) {
1008 return -1; /* fail */
1013 else if(infop->len+1 >= infop->alloc) {
1016 newptr = realloc(infop->buffer, infop->alloc*2);
1020 return -1; /* fail */
1022 infop->buffer = newptr;
1026 infop->buffer[ infop->len ] = outc;
1030 return outc; /* fputc() returns like this on success */
1033 char *curl_maprintf(const char *format, ...)
1035 va_list ap_save; /* argument pointer */
1037 struct asprintf info;
1044 va_start(ap_save, format);
1045 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1047 if((-1 == retcode) || info.fail) {
1053 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1060 char *curl_mvaprintf(const char *format, va_list ap_save)
1063 struct asprintf info;
1070 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1071 if((-1 == retcode) || info.fail) {
1078 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1085 static int storebuffer(int output, FILE *data)
1087 char **buffer = (char **)data;
1088 unsigned char outc = (unsigned char)output;
1091 return outc; /* act like fputc() ! */
1094 int curl_msprintf(char *buffer, const char *format, ...)
1096 va_list ap_save; /* argument pointer */
1098 va_start(ap_save, format);
1099 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1101 *buffer=0; /* we terminate this with a zero byte */
1105 int curl_mprintf(const char *format, ...)
1108 va_list ap_save; /* argument pointer */
1109 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);