xref: /titanic_51/usr/src/lib/libsqlite/src/printf.c (revision 5c0b7edee9bd9fad49038456b16972ff28fa4187)
1 
2 #pragma ident	"%Z%%M%	%I%	%E% SMI"
3 
4 /*
5 ** The "printf" code that follows dates from the 1980's.  It is in
6 ** the public domain.  The original comments are included here for
7 ** completeness.  They are very out-of-date but might be useful as
8 ** an historical reference.  Most of the "enhancements" have been backed
9 ** out so that the functionality is now the same as standard printf().
10 **
11 **************************************************************************
12 **
13 ** The following modules is an enhanced replacement for the "printf" subroutines
14 ** found in the standard C library.  The following enhancements are
15 ** supported:
16 **
17 **      +  Additional functions.  The standard set of "printf" functions
18 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
19 **         vsprintf.  This module adds the following:
20 **
21 **           *  snprintf -- Works like sprintf, but has an extra argument
22 **                          which is the size of the buffer written to.
23 **
24 **           *  mprintf --  Similar to sprintf.  Writes output to memory
25 **                          obtained from malloc.
26 **
27 **           *  xprintf --  Calls a function to dispose of output.
28 **
29 **           *  nprintf --  No output, but returns the number of characters
30 **                          that would have been output by printf.
31 **
32 **           *  A v- version (ex: vsnprintf) of every function is also
33 **              supplied.
34 **
35 **      +  A few extensions to the formatting notation are supported:
36 **
37 **           *  The "=" flag (similar to "-") causes the output to be
38 **              be centered in the appropriately sized field.
39 **
40 **           *  The %b field outputs an integer in binary notation.
41 **
42 **           *  The %c field now accepts a precision.  The character output
43 **              is repeated by the number of times the precision specifies.
44 **
45 **           *  The %' field works like %c, but takes as its character the
46 **              next character of the format string, instead of the next
47 **              argument.  For example,  printf("%.78'-")  prints 78 minus
48 **              signs, the same as  printf("%.78c",'-').
49 **
50 **      +  When compiled using GCC on a SPARC, this version of printf is
51 **         faster than the library printf for SUN OS 4.1.
52 **
53 **      +  All functions are fully reentrant.
54 **
55 */
56 #include "sqliteInt.h"
57 
58 /*
59 ** Conversion types fall into various categories as defined by the
60 ** following enumeration.
61 */
62 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
63 #define etFLOAT       2 /* Floating point.  %f */
64 #define etEXP         3 /* Exponentional notation. %e and %E */
65 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
66 #define etSIZE        5 /* Return number of characters processed so far. %n */
67 #define etSTRING      6 /* Strings. %s */
68 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
69 #define etPERCENT     8 /* Percent symbol. %% */
70 #define etCHARX       9 /* Characters. %c */
71 #define etERROR      10 /* Used to indicate no such conversion type */
72 /* The rest are extensions, not normally found in printf() */
73 #define etCHARLIT    11 /* Literal characters.  %' */
74 #define etSQLESCAPE  12 /* Strings with '\'' doubled.  %q */
75 #define etSQLESCAPE2 13 /* Strings with '\'' doubled and enclosed in '',
76                           NULL pointers replaced by SQL NULL.  %Q */
77 #define etTOKEN      14 /* a pointer to a Token structure */
78 #define etSRCLIST    15 /* a pointer to a SrcList */
79 
80 
81 /*
82 ** An "etByte" is an 8-bit unsigned value.
83 */
84 typedef unsigned char etByte;
85 
86 /*
87 ** Each builtin conversion character (ex: the 'd' in "%d") is described
88 ** by an instance of the following structure
89 */
90 typedef struct et_info {   /* Information about each format field */
91   char fmttype;            /* The format field code letter */
92   etByte base;             /* The base for radix conversion */
93   etByte flags;            /* One or more of FLAG_ constants below */
94   etByte type;             /* Conversion paradigm */
95   char *charset;           /* The character set for conversion */
96   char *prefix;            /* Prefix on non-zero values in alt format */
97 } et_info;
98 
99 /*
100 ** Allowed values for et_info.flags
101 */
102 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
103 #define FLAG_INTERN  2     /* True if for internal use only */
104 
105 
106 /*
107 ** The following table is searched linearly, so it is good to put the
108 ** most frequently used conversion types first.
109 */
110 static et_info fmtinfo[] = {
111   {  'd', 10, 1, etRADIX,      "0123456789",       0    },
112   {  's',  0, 0, etSTRING,     0,                  0    },
113   {  'z',  0, 2, etDYNSTRING,  0,                  0    },
114   {  'q',  0, 0, etSQLESCAPE,  0,                  0    },
115   {  'Q',  0, 0, etSQLESCAPE2, 0,                  0    },
116   {  'c',  0, 0, etCHARX,      0,                  0    },
117   {  'o',  8, 0, etRADIX,      "01234567",         "0"  },
118   {  'u', 10, 0, etRADIX,      "0123456789",       0    },
119   {  'x', 16, 0, etRADIX,      "0123456789abcdef", "x0" },
120   {  'X', 16, 0, etRADIX,      "0123456789ABCDEF", "X0" },
121   {  'f',  0, 1, etFLOAT,      0,                  0    },
122   {  'e',  0, 1, etEXP,        "e",                0    },
123   {  'E',  0, 1, etEXP,        "E",                0    },
124   {  'g',  0, 1, etGENERIC,    "e",                0    },
125   {  'G',  0, 1, etGENERIC,    "E",                0    },
126   {  'i', 10, 1, etRADIX,      "0123456789",       0    },
127   {  'n',  0, 0, etSIZE,       0,                  0    },
128   {  '%',  0, 0, etPERCENT,    0,                  0    },
129   {  'p', 10, 0, etRADIX,      "0123456789",       0    },
130   {  'T',  0, 2, etTOKEN,      0,                  0    },
131   {  'S',  0, 2, etSRCLIST,    0,                  0    },
132 };
133 #define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
134 
135 /*
136 ** If NOFLOATINGPOINT is defined, then none of the floating point
137 ** conversions will work.
138 */
139 #ifndef etNOFLOATINGPOINT
140 /*
141 ** "*val" is a double such that 0.1 <= *val < 10.0
142 ** Return the ascii code for the leading digit of *val, then
143 ** multiply "*val" by 10.0 to renormalize.
144 **
145 ** Example:
146 **     input:     *val = 3.14159
147 **     output:    *val = 1.4159    function return = '3'
148 **
149 ** The counter *cnt is incremented each time.  After counter exceeds
150 ** 16 (the number of significant digits in a 64-bit float) '0' is
151 ** always returned.
152 */
153 static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
154   int digit;
155   LONGDOUBLE_TYPE d;
156   if( (*cnt)++ >= 16 ) return '0';
157   digit = (int)*val;
158   d = digit;
159   digit += '0';
160   *val = (*val - d)*10.0;
161   return digit;
162 }
163 #endif
164 
165 #define etBUFSIZE 1000  /* Size of the output buffer */
166 
167 /*
168 ** The root program.  All variations call this core.
169 **
170 ** INPUTS:
171 **   func   This is a pointer to a function taking three arguments
172 **            1. A pointer to anything.  Same as the "arg" parameter.
173 **            2. A pointer to the list of characters to be output
174 **               (Note, this list is NOT null terminated.)
175 **            3. An integer number of characters to be output.
176 **               (Note: This number might be zero.)
177 **
178 **   arg    This is the pointer to anything which will be passed as the
179 **          first argument to "func".  Use it for whatever you like.
180 **
181 **   fmt    This is the format string, as in the usual print.
182 **
183 **   ap     This is a pointer to a list of arguments.  Same as in
184 **          vfprint.
185 **
186 ** OUTPUTS:
187 **          The return value is the total number of characters sent to
188 **          the function "func".  Returns -1 on a error.
189 **
190 ** Note that the order in which automatic variables are declared below
191 ** seems to make a big difference in determining how fast this beast
192 ** will run.
193 */
194 static int vxprintf(
195   void (*func)(void*,const char*,int),     /* Consumer of text */
196   void *arg,                         /* First argument to the consumer */
197   int useExtended,                   /* Allow extended %-conversions */
198   const char *fmt,                   /* Format string */
199   va_list ap                         /* arguments */
200 ){
201   int c;                     /* Next character in the format string */
202   char *bufpt;               /* Pointer to the conversion buffer */
203   int precision;             /* Precision of the current field */
204   int length;                /* Length of the field */
205   int idx;                   /* A general purpose loop counter */
206   int count;                 /* Total number of characters output */
207   int width;                 /* Width of the current field */
208   etByte flag_leftjustify;   /* True if "-" flag is present */
209   etByte flag_plussign;      /* True if "+" flag is present */
210   etByte flag_blanksign;     /* True if " " flag is present */
211   etByte flag_alternateform; /* True if "#" flag is present */
212   etByte flag_zeropad;       /* True if field width constant starts with zero */
213   etByte flag_long;          /* True if "l" flag is present */
214   unsigned long longvalue;   /* Value for integer types */
215   LONGDOUBLE_TYPE realvalue; /* Value for real types */
216   et_info *infop;            /* Pointer to the appropriate info structure */
217   char buf[etBUFSIZE];       /* Conversion buffer */
218   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
219   etByte errorflag = 0;      /* True if an error is encountered */
220   etByte xtype;              /* Conversion paradigm */
221   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
222   static char spaces[] = "                                                  ";
223 #define etSPACESIZE (sizeof(spaces)-1)
224 #ifndef etNOFLOATINGPOINT
225   int  exp;                  /* exponent of real numbers */
226   double rounder;            /* Used for rounding floating point values */
227   etByte flag_dp;            /* True if decimal point should be shown */
228   etByte flag_rtz;           /* True if trailing zeros should be removed */
229   etByte flag_exp;           /* True to force display of the exponent */
230   int nsd;                   /* Number of significant digits returned */
231 #endif
232 
233   func(arg,"",0);
234   count = length = 0;
235   bufpt = 0;
236   for(; (c=(*fmt))!=0; ++fmt){
237     if( c!='%' ){
238       int amt;
239       bufpt = (char *)fmt;
240       amt = 1;
241       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
242       (*func)(arg,bufpt,amt);
243       count += amt;
244       if( c==0 ) break;
245     }
246     if( (c=(*++fmt))==0 ){
247       errorflag = 1;
248       (*func)(arg,"%",1);
249       count++;
250       break;
251     }
252     /* Find out what flags are present */
253     flag_leftjustify = flag_plussign = flag_blanksign =
254      flag_alternateform = flag_zeropad = 0;
255     do{
256       switch( c ){
257         case '-':   flag_leftjustify = 1;     c = 0;   break;
258         case '+':   flag_plussign = 1;        c = 0;   break;
259         case ' ':   flag_blanksign = 1;       c = 0;   break;
260         case '#':   flag_alternateform = 1;   c = 0;   break;
261         case '0':   flag_zeropad = 1;         c = 0;   break;
262         default:                                       break;
263       }
264     }while( c==0 && (c=(*++fmt))!=0 );
265     /* Get the field width */
266     width = 0;
267     if( c=='*' ){
268       width = va_arg(ap,int);
269       if( width<0 ){
270         flag_leftjustify = 1;
271         width = -width;
272       }
273       c = *++fmt;
274     }else{
275       while( c>='0' && c<='9' ){
276         width = width*10 + c - '0';
277         c = *++fmt;
278       }
279     }
280     if( width > etBUFSIZE-10 ){
281       width = etBUFSIZE-10;
282     }
283     /* Get the precision */
284     if( c=='.' ){
285       precision = 0;
286       c = *++fmt;
287       if( c=='*' ){
288         precision = va_arg(ap,int);
289         if( precision<0 ) precision = -precision;
290         c = *++fmt;
291       }else{
292         while( c>='0' && c<='9' ){
293           precision = precision*10 + c - '0';
294           c = *++fmt;
295         }
296       }
297       /* Limit the precision to prevent overflowing buf[] during conversion */
298       if( precision>etBUFSIZE-40 ) precision = etBUFSIZE-40;
299     }else{
300       precision = -1;
301     }
302     /* Get the conversion type modifier */
303     if( c=='l' ){
304       flag_long = 1;
305       c = *++fmt;
306     }else{
307       flag_long = 0;
308     }
309     /* Fetch the info entry for the field */
310     infop = 0;
311     xtype = etERROR;
312     for(idx=0; idx<etNINFO; idx++){
313       if( c==fmtinfo[idx].fmttype ){
314         infop = &fmtinfo[idx];
315         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
316           xtype = infop->type;
317         }
318         break;
319       }
320     }
321     zExtra = 0;
322 
323     /*
324     ** At this point, variables are initialized as follows:
325     **
326     **   flag_alternateform          TRUE if a '#' is present.
327     **   flag_plussign               TRUE if a '+' is present.
328     **   flag_leftjustify            TRUE if a '-' is present or if the
329     **                               field width was negative.
330     **   flag_zeropad                TRUE if the width began with 0.
331     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
332     **                               the conversion character.
333     **   flag_blanksign              TRUE if a ' ' is present.
334     **   width                       The specified field width.  This is
335     **                               always non-negative.  Zero is the default.
336     **   precision                   The specified precision.  The default
337     **                               is -1.
338     **   xtype                       The class of the conversion.
339     **   infop                       Pointer to the appropriate info struct.
340     */
341     switch( xtype ){
342       case etRADIX:
343         if( flag_long )  longvalue = va_arg(ap,long);
344         else             longvalue = va_arg(ap,int);
345 #if 1
346         /* For the format %#x, the value zero is printed "0" not "0x0".
347         ** I think this is stupid. */
348         if( longvalue==0 ) flag_alternateform = 0;
349 #else
350         /* More sensible: turn off the prefix for octal (to prevent "00"),
351         ** but leave the prefix for hex. */
352         if( longvalue==0 && infop->base==8 ) flag_alternateform = 0;
353 #endif
354         if( infop->flags & FLAG_SIGNED ){
355           if( *(long*)&longvalue<0 ){
356             longvalue = -*(long*)&longvalue;
357             prefix = '-';
358           }else if( flag_plussign )  prefix = '+';
359           else if( flag_blanksign )  prefix = ' ';
360           else                       prefix = 0;
361         }else                        prefix = 0;
362         if( flag_zeropad && precision<width-(prefix!=0) ){
363           precision = width-(prefix!=0);
364         }
365         bufpt = &buf[etBUFSIZE-1];
366         {
367           register char *cset;      /* Use registers for speed */
368           register int base;
369           cset = infop->charset;
370           base = infop->base;
371           do{                                           /* Convert to ascii */
372             *(--bufpt) = cset[longvalue%base];
373             longvalue = longvalue/base;
374           }while( longvalue>0 );
375         }
376         length = &buf[etBUFSIZE-1]-bufpt;
377         for(idx=precision-length; idx>0; idx--){
378           *(--bufpt) = '0';                             /* Zero pad */
379         }
380         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
381         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
382           char *pre, x;
383           pre = infop->prefix;
384           if( *bufpt!=pre[0] ){
385             for(pre=infop->prefix; (x=(*pre))!=0; pre++) *(--bufpt) = x;
386           }
387         }
388         length = &buf[etBUFSIZE-1]-bufpt;
389         break;
390       case etFLOAT:
391       case etEXP:
392       case etGENERIC:
393         realvalue = va_arg(ap,double);
394 #ifndef etNOFLOATINGPOINT
395         if( precision<0 ) precision = 6;         /* Set default precision */
396         if( precision>etBUFSIZE-10 ) precision = etBUFSIZE-10;
397         if( realvalue<0.0 ){
398           realvalue = -realvalue;
399           prefix = '-';
400         }else{
401           if( flag_plussign )          prefix = '+';
402           else if( flag_blanksign )    prefix = ' ';
403           else                         prefix = 0;
404         }
405         if( infop->type==etGENERIC && precision>0 ) precision--;
406         rounder = 0.0;
407 #if 0
408         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
409         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
410 #else
411         /* It makes more sense to use 0.5 */
412         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1);
413 #endif
414         if( infop->type==etFLOAT ) realvalue += rounder;
415         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
416         exp = 0;
417         if( realvalue>0.0 ){
418           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
419           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
420           while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
421           while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
422           if( exp>350 || exp<-350 ){
423             bufpt = "NaN";
424             length = 3;
425             break;
426           }
427         }
428         bufpt = buf;
429         /*
430         ** If the field type is etGENERIC, then convert to either etEXP
431         ** or etFLOAT, as appropriate.
432         */
433         flag_exp = xtype==etEXP;
434         if( xtype!=etFLOAT ){
435           realvalue += rounder;
436           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
437         }
438         if( xtype==etGENERIC ){
439           flag_rtz = !flag_alternateform;
440           if( exp<-4 || exp>precision ){
441             xtype = etEXP;
442           }else{
443             precision = precision - exp;
444             xtype = etFLOAT;
445           }
446         }else{
447           flag_rtz = 0;
448         }
449         /*
450         ** The "exp+precision" test causes output to be of type etEXP if
451         ** the precision is too large to fit in buf[].
452         */
453         nsd = 0;
454         if( xtype==etFLOAT && exp+precision<etBUFSIZE-30 ){
455           flag_dp = (precision>0 || flag_alternateform);
456           if( prefix ) *(bufpt++) = prefix;         /* Sign */
457           if( exp<0 )  *(bufpt++) = '0';            /* Digits before "." */
458           else for(; exp>=0; exp--) *(bufpt++) = et_getdigit(&realvalue,&nsd);
459           if( flag_dp ) *(bufpt++) = '.';           /* The decimal point */
460           for(exp++; exp<0 && precision>0; precision--, exp++){
461             *(bufpt++) = '0';
462           }
463           while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
464           *(bufpt--) = 0;                           /* Null terminate */
465           if( flag_rtz && flag_dp ){     /* Remove trailing zeros and "." */
466             while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
467             if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
468           }
469           bufpt++;                            /* point to next free slot */
470         }else{    /* etEXP or etGENERIC */
471           flag_dp = (precision>0 || flag_alternateform);
472           if( prefix ) *(bufpt++) = prefix;   /* Sign */
473           *(bufpt++) = et_getdigit(&realvalue,&nsd);  /* First digit */
474           if( flag_dp ) *(bufpt++) = '.';     /* Decimal point */
475           while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
476           bufpt--;                            /* point to last digit */
477           if( flag_rtz && flag_dp ){          /* Remove tail zeros */
478             while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
479             if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
480           }
481           bufpt++;                            /* point to next free slot */
482           if( exp || flag_exp ){
483             *(bufpt++) = infop->charset[0];
484             if( exp<0 ){ *(bufpt++) = '-'; exp = -exp; } /* sign of exp */
485             else       { *(bufpt++) = '+'; }
486             if( exp>=100 ){
487               *(bufpt++) = (exp/100)+'0';                /* 100's digit */
488               exp %= 100;
489             }
490             *(bufpt++) = exp/10+'0';                     /* 10's digit */
491             *(bufpt++) = exp%10+'0';                     /* 1's digit */
492           }
493         }
494         /* The converted number is in buf[] and zero terminated. Output it.
495         ** Note that the number is in the usual order, not reversed as with
496         ** integer conversions. */
497         length = bufpt-buf;
498         bufpt = buf;
499 
500         /* Special case:  Add leading zeros if the flag_zeropad flag is
501         ** set and we are not left justified */
502         if( flag_zeropad && !flag_leftjustify && length < width){
503           int i;
504           int nPad = width - length;
505           for(i=width; i>=nPad; i--){
506             bufpt[i] = bufpt[i-nPad];
507           }
508           i = prefix!=0;
509           while( nPad-- ) bufpt[i++] = '0';
510           length = width;
511         }
512 #endif
513         break;
514       case etSIZE:
515         *(va_arg(ap,int*)) = count;
516         length = width = 0;
517         break;
518       case etPERCENT:
519         buf[0] = '%';
520         bufpt = buf;
521         length = 1;
522         break;
523       case etCHARLIT:
524       case etCHARX:
525         c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
526         if( precision>=0 ){
527           for(idx=1; idx<precision; idx++) buf[idx] = c;
528           length = precision;
529         }else{
530           length =1;
531         }
532         bufpt = buf;
533         break;
534       case etSTRING:
535       case etDYNSTRING:
536         bufpt = va_arg(ap,char*);
537         if( bufpt==0 ){
538           bufpt = "";
539         }else if( xtype==etDYNSTRING ){
540           zExtra = bufpt;
541         }
542         length = strlen(bufpt);
543         if( precision>=0 && precision<length ) length = precision;
544         break;
545       case etSQLESCAPE:
546       case etSQLESCAPE2:
547         {
548           int i, j, n, c, isnull;
549           char *arg = va_arg(ap,char*);
550           isnull = arg==0;
551           if( isnull ) arg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
552           for(i=n=0; (c=arg[i])!=0; i++){
553             if( c=='\'' )  n++;
554           }
555           n += i + 1 + ((!isnull && xtype==etSQLESCAPE2) ? 2 : 0);
556           if( n>etBUFSIZE ){
557             bufpt = zExtra = sqliteMalloc( n );
558             if( bufpt==0 ) return -1;
559           }else{
560             bufpt = buf;
561           }
562           j = 0;
563           if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
564           for(i=0; (c=arg[i])!=0; i++){
565             bufpt[j++] = c;
566             if( c=='\'' ) bufpt[j++] = c;
567           }
568           if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
569           bufpt[j] = 0;
570           length = j;
571           if( precision>=0 && precision<length ) length = precision;
572         }
573         break;
574       case etTOKEN: {
575         Token *pToken = va_arg(ap, Token*);
576         (*func)(arg, pToken->z, pToken->n);
577         length = width = 0;
578         break;
579       }
580       case etSRCLIST: {
581         SrcList *pSrc = va_arg(ap, SrcList*);
582         int k = va_arg(ap, int);
583         struct SrcList_item *pItem = &pSrc->a[k];
584         assert( k>=0 && k<pSrc->nSrc );
585         if( pItem->zDatabase && pItem->zDatabase[0] ){
586           (*func)(arg, pItem->zDatabase, strlen(pItem->zDatabase));
587           (*func)(arg, ".", 1);
588         }
589         (*func)(arg, pItem->zName, strlen(pItem->zName));
590         length = width = 0;
591         break;
592       }
593       case etERROR:
594         buf[0] = '%';
595         buf[1] = c;
596         errorflag = 0;
597         idx = 1+(c!=0);
598         (*func)(arg,"%",idx);
599         count += idx;
600         if( c==0 ) fmt--;
601         break;
602     }/* End switch over the format type */
603     /*
604     ** The text of the conversion is pointed to by "bufpt" and is
605     ** "length" characters long.  The field width is "width".  Do
606     ** the output.
607     */
608     if( !flag_leftjustify ){
609       register int nspace;
610       nspace = width-length;
611       if( nspace>0 ){
612         count += nspace;
613         while( nspace>=etSPACESIZE ){
614           (*func)(arg,spaces,etSPACESIZE);
615           nspace -= etSPACESIZE;
616         }
617         if( nspace>0 ) (*func)(arg,spaces,nspace);
618       }
619     }
620     if( length>0 ){
621       (*func)(arg,bufpt,length);
622       count += length;
623     }
624     if( flag_leftjustify ){
625       register int nspace;
626       nspace = width-length;
627       if( nspace>0 ){
628         count += nspace;
629         while( nspace>=etSPACESIZE ){
630           (*func)(arg,spaces,etSPACESIZE);
631           nspace -= etSPACESIZE;
632         }
633         if( nspace>0 ) (*func)(arg,spaces,nspace);
634       }
635     }
636     if( zExtra ){
637       sqliteFree(zExtra);
638     }
639   }/* End for loop over the format string */
640   return errorflag ? -1 : count;
641 } /* End of function */
642 
643 
644 /* This structure is used to store state information about the
645 ** write to memory that is currently in progress.
646 */
647 struct sgMprintf {
648   char *zBase;     /* A base allocation */
649   char *zText;     /* The string collected so far */
650   int  nChar;      /* Length of the string so far */
651   int  nTotal;     /* Output size if unconstrained */
652   int  nAlloc;     /* Amount of space allocated in zText */
653   void *(*xRealloc)(void*,int);  /* Function used to realloc memory */
654 };
655 
656 /*
657 ** This function implements the callback from vxprintf.
658 **
659 ** This routine add nNewChar characters of text in zNewText to
660 ** the sgMprintf structure pointed to by "arg".
661 */
662 static void mout(void *arg, const char *zNewText, int nNewChar){
663   struct sgMprintf *pM = (struct sgMprintf*)arg;
664   pM->nTotal += nNewChar;
665   if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
666     if( pM->xRealloc==0 ){
667       nNewChar =  pM->nAlloc - pM->nChar - 1;
668     }else{
669       pM->nAlloc = pM->nChar + nNewChar*2 + 1;
670       if( pM->zText==pM->zBase ){
671         pM->zText = pM->xRealloc(0, pM->nAlloc);
672         if( pM->zText && pM->nChar ){
673           memcpy(pM->zText, pM->zBase, pM->nChar);
674         }
675       }else{
676         pM->zText = pM->xRealloc(pM->zText, pM->nAlloc);
677       }
678     }
679   }
680   if( pM->zText ){
681     if( nNewChar>0 ){
682       memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
683       pM->nChar += nNewChar;
684     }
685     pM->zText[pM->nChar] = 0;
686   }
687 }
688 
689 /*
690 ** This routine is a wrapper around xprintf() that invokes mout() as
691 ** the consumer.
692 */
693 static char *base_vprintf(
694   void *(*xRealloc)(void*,int),   /* Routine to realloc memory. May be NULL */
695   int useInternal,                /* Use internal %-conversions if true */
696   char *zInitBuf,                 /* Initially write here, before mallocing */
697   int nInitBuf,                   /* Size of zInitBuf[] */
698   const char *zFormat,            /* format string */
699   va_list ap                      /* arguments */
700 ){
701   struct sgMprintf sM;
702   sM.zBase = sM.zText = zInitBuf;
703   sM.nChar = sM.nTotal = 0;
704   sM.nAlloc = nInitBuf;
705   sM.xRealloc = xRealloc;
706   vxprintf(mout, &sM, useInternal, zFormat, ap);
707   if( xRealloc ){
708     if( sM.zText==sM.zBase ){
709       sM.zText = xRealloc(0, sM.nChar+1);
710       memcpy(sM.zText, sM.zBase, sM.nChar+1);
711     }else if( sM.nAlloc>sM.nChar+10 ){
712       sM.zText = xRealloc(sM.zText, sM.nChar+1);
713     }
714   }
715   return sM.zText;
716 }
717 
718 /*
719 ** Realloc that is a real function, not a macro.
720 */
721 static void *printf_realloc(void *old, int size){
722   return sqliteRealloc(old,size);
723 }
724 
725 /*
726 ** Print into memory obtained from sqliteMalloc().  Use the internal
727 ** %-conversion extensions.
728 */
729 char *sqliteVMPrintf(const char *zFormat, va_list ap){
730   char zBase[1000];
731   return base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
732 }
733 
734 /*
735 ** Print into memory obtained from sqliteMalloc().  Use the internal
736 ** %-conversion extensions.
737 */
738 char *sqliteMPrintf(const char *zFormat, ...){
739   va_list ap;
740   char *z;
741   char zBase[1000];
742   va_start(ap, zFormat);
743   z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
744   va_end(ap);
745   return z;
746 }
747 
748 /*
749 ** Print into memory obtained from malloc().  Do not use the internal
750 ** %-conversion extensions.  This routine is for use by external users.
751 */
752 char *sqlite_mprintf(const char *zFormat, ...){
753   va_list ap;
754   char *z;
755   char zBuf[200];
756 
757   va_start(ap,zFormat);
758   z = base_vprintf((void*(*)(void*,int))realloc, 0,
759                    zBuf, sizeof(zBuf), zFormat, ap);
760   va_end(ap);
761   return z;
762 }
763 
764 /* This is the varargs version of sqlite_mprintf.
765 */
766 char *sqlite_vmprintf(const char *zFormat, va_list ap){
767   char zBuf[200];
768   return base_vprintf((void*(*)(void*,int))realloc, 0,
769                       zBuf, sizeof(zBuf), zFormat, ap);
770 }
771 
772 /*
773 ** sqlite_snprintf() works like snprintf() except that it ignores the
774 ** current locale settings.  This is important for SQLite because we
775 ** are not able to use a "," as the decimal point in place of "." as
776 ** specified by some locales.
777 */
778 char *sqlite_snprintf(int n, char *zBuf, const char *zFormat, ...){
779   char *z;
780   va_list ap;
781 
782   va_start(ap,zFormat);
783   z = base_vprintf(0, 0, zBuf, n, zFormat, ap);
784   va_end(ap);
785   return z;
786 }
787 
788 /*
789 ** The following four routines implement the varargs versions of the
790 ** sqlite_exec() and sqlite_get_table() interfaces.  See the sqlite.h
791 ** header files for a more detailed description of how these interfaces
792 ** work.
793 **
794 ** These routines are all just simple wrappers.
795 */
796 int sqlite_exec_printf(
797   sqlite *db,                   /* An open database */
798   const char *sqlFormat,        /* printf-style format string for the SQL */
799   sqlite_callback xCallback,    /* Callback function */
800   void *pArg,                   /* 1st argument to callback function */
801   char **errmsg,                /* Error msg written here */
802   ...                           /* Arguments to the format string. */
803 ){
804   va_list ap;
805   int rc;
806 
807   va_start(ap, errmsg);
808   rc = sqlite_exec_vprintf(db, sqlFormat, xCallback, pArg, errmsg, ap);
809   va_end(ap);
810   return rc;
811 }
812 int sqlite_exec_vprintf(
813   sqlite *db,                   /* An open database */
814   const char *sqlFormat,        /* printf-style format string for the SQL */
815   sqlite_callback xCallback,    /* Callback function */
816   void *pArg,                   /* 1st argument to callback function */
817   char **errmsg,                /* Error msg written here */
818   va_list ap                    /* Arguments to the format string. */
819 ){
820   char *zSql;
821   int rc;
822 
823   zSql = sqlite_vmprintf(sqlFormat, ap);
824   rc = sqlite_exec(db, zSql, xCallback, pArg, errmsg);
825   free(zSql);
826   return rc;
827 }
828 int sqlite_get_table_printf(
829   sqlite *db,            /* An open database */
830   const char *sqlFormat, /* printf-style format string for the SQL */
831   char ***resultp,       /* Result written to a char *[]  that this points to */
832   int *nrow,             /* Number of result rows written here */
833   int *ncol,             /* Number of result columns written here */
834   char **errmsg,         /* Error msg written here */
835   ...                    /* Arguments to the format string */
836 ){
837   va_list ap;
838   int rc;
839 
840   va_start(ap, errmsg);
841   rc = sqlite_get_table_vprintf(db, sqlFormat, resultp, nrow, ncol, errmsg, ap);
842   va_end(ap);
843   return rc;
844 }
845 int sqlite_get_table_vprintf(
846   sqlite *db,            /* An open database */
847   const char *sqlFormat, /* printf-style format string for the SQL */
848   char ***resultp,       /* Result written to a char *[]  that this points to */
849   int *nrow,             /* Number of result rows written here */
850   int *ncolumn,          /* Number of result columns written here */
851   char **errmsg,         /* Error msg written here */
852   va_list ap             /* Arguments to the format string */
853 ){
854   char *zSql;
855   int rc;
856 
857   zSql = sqlite_vmprintf(sqlFormat, ap);
858   rc = sqlite_get_table(db, zSql, resultp, nrow, ncolumn, errmsg);
859   free(zSql);
860   return rc;
861 }
862