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