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