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