xref: /sqlite-3.40.0/src/printf.c (revision 049d487e)
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 ** This file contains code for a set of "printf"-like routines.  These
11 ** routines format strings much like the printf() from the standard C
12 ** library, though the implementation here has enhancements to support
13 ** SQLlite.
14 */
15 #include "sqliteInt.h"
16 
17 /*
18 ** Conversion types fall into various categories as defined by the
19 ** following enumeration.
20 */
21 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
22 #define etFLOAT       2 /* Floating point.  %f */
23 #define etEXP         3 /* Exponentional notation. %e and %E */
24 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
25 #define etSIZE        5 /* Return number of characters processed so far. %n */
26 #define etSTRING      6 /* Strings. %s */
27 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
28 #define etPERCENT     8 /* Percent symbol. %% */
29 #define etCHARX       9 /* Characters. %c */
30 /* The rest are extensions, not normally found in printf() */
31 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
32 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
33                           NULL pointers replaced by SQL NULL.  %Q */
34 #define etTOKEN      12 /* a pointer to a Token structure */
35 #define etSRCLIST    13 /* a pointer to a SrcList */
36 #define etPOINTER    14 /* The %p conversion */
37 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
38 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
39 
40 #define etINVALID     0 /* Any unrecognized conversion type */
41 
42 
43 /*
44 ** An "etByte" is an 8-bit unsigned value.
45 */
46 typedef unsigned char etByte;
47 
48 /*
49 ** Each builtin conversion character (ex: the 'd' in "%d") is described
50 ** by an instance of the following structure
51 */
52 typedef struct et_info {   /* Information about each format field */
53   char fmttype;            /* The format field code letter */
54   etByte base;             /* The base for radix conversion */
55   etByte flags;            /* One or more of FLAG_ constants below */
56   etByte type;             /* Conversion paradigm */
57   etByte charset;          /* Offset into aDigits[] of the digits string */
58   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
59 } et_info;
60 
61 /*
62 ** Allowed values for et_info.flags
63 */
64 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
65 #define FLAG_INTERN  2     /* True if for internal use only */
66 #define FLAG_STRING  4     /* Allow infinity precision */
67 
68 
69 /*
70 ** The following table is searched linearly, so it is good to put the
71 ** most frequently used conversion types first.
72 */
73 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
74 static const char aPrefix[] = "-x0\000X0";
75 static const et_info fmtinfo[] = {
76   {  'd', 10, 1, etRADIX,      0,  0 },
77   {  's',  0, 4, etSTRING,     0,  0 },
78   {  'g',  0, 1, etGENERIC,    30, 0 },
79   {  'z',  0, 4, etDYNSTRING,  0,  0 },
80   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
81   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
82   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
83   {  'c',  0, 0, etCHARX,      0,  0 },
84   {  'o',  8, 0, etRADIX,      0,  2 },
85   {  'u', 10, 0, etRADIX,      0,  0 },
86   {  'x', 16, 0, etRADIX,      16, 1 },
87   {  'X', 16, 0, etRADIX,      0,  4 },
88 #ifndef SQLITE_OMIT_FLOATING_POINT
89   {  'f',  0, 1, etFLOAT,      0,  0 },
90   {  'e',  0, 1, etEXP,        30, 0 },
91   {  'E',  0, 1, etEXP,        14, 0 },
92   {  'G',  0, 1, etGENERIC,    14, 0 },
93 #endif
94   {  'i', 10, 1, etRADIX,      0,  0 },
95   {  'n',  0, 0, etSIZE,       0,  0 },
96   {  '%',  0, 0, etPERCENT,    0,  0 },
97   {  'p', 16, 0, etPOINTER,    0,  1 },
98 
99 /* All the rest have the FLAG_INTERN bit set and are thus for internal
100 ** use only */
101   {  'T',  0, 2, etTOKEN,      0,  0 },
102   {  'S',  0, 2, etSRCLIST,    0,  0 },
103   {  'r', 10, 3, etORDINAL,    0,  0 },
104 };
105 
106 /*
107 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
108 ** conversions will work.
109 */
110 #ifndef SQLITE_OMIT_FLOATING_POINT
111 /*
112 ** "*val" is a double such that 0.1 <= *val < 10.0
113 ** Return the ascii code for the leading digit of *val, then
114 ** multiply "*val" by 10.0 to renormalize.
115 **
116 ** Example:
117 **     input:     *val = 3.14159
118 **     output:    *val = 1.4159    function return = '3'
119 **
120 ** The counter *cnt is incremented each time.  After counter exceeds
121 ** 16 (the number of significant digits in a 64-bit float) '0' is
122 ** always returned.
123 */
124 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
125   int digit;
126   LONGDOUBLE_TYPE d;
127   if( (*cnt)<=0 ) return '0';
128   (*cnt)--;
129   digit = (int)*val;
130   d = digit;
131   digit += '0';
132   *val = (*val - d)*10.0;
133   return (char)digit;
134 }
135 #endif /* SQLITE_OMIT_FLOATING_POINT */
136 
137 /*
138 ** Append N space characters to the given string buffer.
139 */
140 void sqlite3AppendSpace(StrAccum *pAccum, int N){
141   static const char zSpaces[] = "                             ";
142   while( N>=(int)sizeof(zSpaces)-1 ){
143     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
144     N -= sizeof(zSpaces)-1;
145   }
146   if( N>0 ){
147     sqlite3StrAccumAppend(pAccum, zSpaces, N);
148   }
149 }
150 
151 /*
152 ** On machines with a small stack size, you can redefine the
153 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
154 */
155 #ifndef SQLITE_PRINT_BUF_SIZE
156 # define SQLITE_PRINT_BUF_SIZE 70
157 #endif
158 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
159 
160 /*
161 ** Render a string given by "fmt" into the StrAccum object.
162 */
163 void sqlite3VXPrintf(
164   StrAccum *pAccum,                  /* Accumulate results here */
165   int useExtended,                   /* Allow extended %-conversions */
166   const char *fmt,                   /* Format string */
167   va_list ap                         /* arguments */
168 ){
169   int c;                     /* Next character in the format string */
170   char *bufpt;               /* Pointer to the conversion buffer */
171   int precision;             /* Precision of the current field */
172   int length;                /* Length of the field */
173   int idx;                   /* A general purpose loop counter */
174   int width;                 /* Width of the current field */
175   etByte flag_leftjustify;   /* True if "-" flag is present */
176   etByte flag_plussign;      /* True if "+" flag is present */
177   etByte flag_blanksign;     /* True if " " flag is present */
178   etByte flag_alternateform; /* True if "#" flag is present */
179   etByte flag_altform2;      /* True if "!" flag is present */
180   etByte flag_zeropad;       /* True if field width constant starts with zero */
181   etByte flag_long;          /* True if "l" flag is present */
182   etByte flag_longlong;      /* True if the "ll" flag is present */
183   etByte done;               /* Loop termination flag */
184   etByte xtype = 0;          /* Conversion paradigm */
185   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
186   sqlite_uint64 longvalue;   /* Value for integer types */
187   LONGDOUBLE_TYPE realvalue; /* Value for real types */
188   const et_info *infop;      /* Pointer to the appropriate info structure */
189   char *zOut;                /* Rendering buffer */
190   int nOut;                  /* Size of the rendering buffer */
191   char *zExtra;              /* Malloced memory used by some conversion */
192 #ifndef SQLITE_OMIT_FLOATING_POINT
193   int  exp, e2;              /* exponent of real numbers */
194   int nsd;                   /* Number of significant digits returned */
195   double rounder;            /* Used for rounding floating point values */
196   etByte flag_dp;            /* True if decimal point should be shown */
197   etByte flag_rtz;           /* True if trailing zeros should be removed */
198 #endif
199   char buf[etBUFSIZE];       /* Conversion buffer */
200 
201   bufpt = 0;
202   for(; (c=(*fmt))!=0; ++fmt){
203     if( c!='%' ){
204       int amt;
205       bufpt = (char *)fmt;
206       amt = 1;
207       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
208       sqlite3StrAccumAppend(pAccum, bufpt, amt);
209       if( c==0 ) break;
210     }
211     if( (c=(*++fmt))==0 ){
212       sqlite3StrAccumAppend(pAccum, "%", 1);
213       break;
214     }
215     /* Find out what flags are present */
216     flag_leftjustify = flag_plussign = flag_blanksign =
217      flag_alternateform = flag_altform2 = flag_zeropad = 0;
218     done = 0;
219     do{
220       switch( c ){
221         case '-':   flag_leftjustify = 1;     break;
222         case '+':   flag_plussign = 1;        break;
223         case ' ':   flag_blanksign = 1;       break;
224         case '#':   flag_alternateform = 1;   break;
225         case '!':   flag_altform2 = 1;        break;
226         case '0':   flag_zeropad = 1;         break;
227         default:    done = 1;                 break;
228       }
229     }while( !done && (c=(*++fmt))!=0 );
230     /* Get the field width */
231     width = 0;
232     if( c=='*' ){
233       width = va_arg(ap,int);
234       if( width<0 ){
235         flag_leftjustify = 1;
236         width = -width;
237       }
238       c = *++fmt;
239     }else{
240       while( c>='0' && c<='9' ){
241         width = width*10 + c - '0';
242         c = *++fmt;
243       }
244     }
245     /* Get the precision */
246     if( c=='.' ){
247       precision = 0;
248       c = *++fmt;
249       if( c=='*' ){
250         precision = va_arg(ap,int);
251         if( precision<0 ) precision = -precision;
252         c = *++fmt;
253       }else{
254         while( c>='0' && c<='9' ){
255           precision = precision*10 + c - '0';
256           c = *++fmt;
257         }
258       }
259     }else{
260       precision = -1;
261     }
262     /* Get the conversion type modifier */
263     if( c=='l' ){
264       flag_long = 1;
265       c = *++fmt;
266       if( c=='l' ){
267         flag_longlong = 1;
268         c = *++fmt;
269       }else{
270         flag_longlong = 0;
271       }
272     }else{
273       flag_long = flag_longlong = 0;
274     }
275     /* Fetch the info entry for the field */
276     infop = &fmtinfo[0];
277     xtype = etINVALID;
278     for(idx=0; idx<ArraySize(fmtinfo); idx++){
279       if( c==fmtinfo[idx].fmttype ){
280         infop = &fmtinfo[idx];
281         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
282           xtype = infop->type;
283         }else{
284           return;
285         }
286         break;
287       }
288     }
289     zExtra = 0;
290 
291     /*
292     ** At this point, variables are initialized as follows:
293     **
294     **   flag_alternateform          TRUE if a '#' is present.
295     **   flag_altform2               TRUE if a '!' is present.
296     **   flag_plussign               TRUE if a '+' is present.
297     **   flag_leftjustify            TRUE if a '-' is present or if the
298     **                               field width was negative.
299     **   flag_zeropad                TRUE if the width began with 0.
300     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
301     **                               the conversion character.
302     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
303     **                               the conversion character.
304     **   flag_blanksign              TRUE if a ' ' is present.
305     **   width                       The specified field width.  This is
306     **                               always non-negative.  Zero is the default.
307     **   precision                   The specified precision.  The default
308     **                               is -1.
309     **   xtype                       The class of the conversion.
310     **   infop                       Pointer to the appropriate info struct.
311     */
312     switch( xtype ){
313       case etPOINTER:
314         flag_longlong = sizeof(char*)==sizeof(i64);
315         flag_long = sizeof(char*)==sizeof(long int);
316         /* Fall through into the next case */
317       case etORDINAL:
318       case etRADIX:
319         if( infop->flags & FLAG_SIGNED ){
320           i64 v;
321           if( flag_longlong ){
322             v = va_arg(ap,i64);
323           }else if( flag_long ){
324             v = va_arg(ap,long int);
325           }else{
326             v = va_arg(ap,int);
327           }
328           if( v<0 ){
329             if( v==SMALLEST_INT64 ){
330               longvalue = ((u64)1)<<63;
331             }else{
332               longvalue = -v;
333             }
334             prefix = '-';
335           }else{
336             longvalue = v;
337             if( flag_plussign )        prefix = '+';
338             else if( flag_blanksign )  prefix = ' ';
339             else                       prefix = 0;
340           }
341         }else{
342           if( flag_longlong ){
343             longvalue = va_arg(ap,u64);
344           }else if( flag_long ){
345             longvalue = va_arg(ap,unsigned long int);
346           }else{
347             longvalue = va_arg(ap,unsigned int);
348           }
349           prefix = 0;
350         }
351         if( longvalue==0 ) flag_alternateform = 0;
352         if( flag_zeropad && precision<width-(prefix!=0) ){
353           precision = width-(prefix!=0);
354         }
355         if( precision<etBUFSIZE-10 ){
356           nOut = etBUFSIZE;
357           zOut = buf;
358         }else{
359           nOut = precision + 10;
360           zOut = zExtra = sqlite3Malloc( nOut );
361           if( zOut==0 ){
362             pAccum->mallocFailed = 1;
363             return;
364           }
365         }
366         bufpt = &zOut[nOut-1];
367         if( xtype==etORDINAL ){
368           static const char zOrd[] = "thstndrd";
369           int x = (int)(longvalue % 10);
370           if( x>=4 || (longvalue/10)%10==1 ){
371             x = 0;
372           }
373           *(--bufpt) = zOrd[x*2+1];
374           *(--bufpt) = zOrd[x*2];
375         }
376         {
377           register const char *cset;      /* Use registers for speed */
378           register int base;
379           cset = &aDigits[infop->charset];
380           base = infop->base;
381           do{                                           /* Convert to ascii */
382             *(--bufpt) = cset[longvalue%base];
383             longvalue = longvalue/base;
384           }while( longvalue>0 );
385         }
386         length = (int)(&zOut[nOut-1]-bufpt);
387         for(idx=precision-length; idx>0; idx--){
388           *(--bufpt) = '0';                             /* Zero pad */
389         }
390         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
391         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
392           const char *pre;
393           char x;
394           pre = &aPrefix[infop->prefix];
395           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
396         }
397         length = (int)(&zOut[nOut-1]-bufpt);
398         break;
399       case etFLOAT:
400       case etEXP:
401       case etGENERIC:
402         realvalue = va_arg(ap,double);
403 #ifdef SQLITE_OMIT_FLOATING_POINT
404         length = 0;
405 #else
406         if( precision<0 ) precision = 6;         /* Set default precision */
407         if( realvalue<0.0 ){
408           realvalue = -realvalue;
409           prefix = '-';
410         }else{
411           if( flag_plussign )          prefix = '+';
412           else if( flag_blanksign )    prefix = ' ';
413           else                         prefix = 0;
414         }
415         if( xtype==etGENERIC && precision>0 ) precision--;
416         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
417         if( xtype==etFLOAT ) realvalue += rounder;
418         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
419         exp = 0;
420         if( sqlite3IsNaN((double)realvalue) ){
421           bufpt = "NaN";
422           length = 3;
423           break;
424         }
425         if( realvalue>0.0 ){
426           LONGDOUBLE_TYPE scale = 1.0;
427           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
428           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
429           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
430           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
431           realvalue /= scale;
432           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
433           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
434           if( exp>350 ){
435             if( prefix=='-' ){
436               bufpt = "-Inf";
437             }else if( prefix=='+' ){
438               bufpt = "+Inf";
439             }else{
440               bufpt = "Inf";
441             }
442             length = sqlite3Strlen30(bufpt);
443             break;
444           }
445         }
446         bufpt = buf;
447         /*
448         ** If the field type is etGENERIC, then convert to either etEXP
449         ** or etFLOAT, as appropriate.
450         */
451         if( xtype!=etFLOAT ){
452           realvalue += rounder;
453           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
454         }
455         if( xtype==etGENERIC ){
456           flag_rtz = !flag_alternateform;
457           if( exp<-4 || exp>precision ){
458             xtype = etEXP;
459           }else{
460             precision = precision - exp;
461             xtype = etFLOAT;
462           }
463         }else{
464           flag_rtz = flag_altform2;
465         }
466         if( xtype==etEXP ){
467           e2 = 0;
468         }else{
469           e2 = exp;
470         }
471         if( e2+precision+width > etBUFSIZE - 15 ){
472           bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
473           if( bufpt==0 ){
474             pAccum->mallocFailed = 1;
475             return;
476           }
477         }
478         zOut = bufpt;
479         nsd = 16 + flag_altform2*10;
480         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
481         /* The sign in front of the number */
482         if( prefix ){
483           *(bufpt++) = prefix;
484         }
485         /* Digits prior to the decimal point */
486         if( e2<0 ){
487           *(bufpt++) = '0';
488         }else{
489           for(; e2>=0; e2--){
490             *(bufpt++) = et_getdigit(&realvalue,&nsd);
491           }
492         }
493         /* The decimal point */
494         if( flag_dp ){
495           *(bufpt++) = '.';
496         }
497         /* "0" digits after the decimal point but before the first
498         ** significant digit of the number */
499         for(e2++; e2<0; precision--, e2++){
500           assert( precision>0 );
501           *(bufpt++) = '0';
502         }
503         /* Significant digits after the decimal point */
504         while( (precision--)>0 ){
505           *(bufpt++) = et_getdigit(&realvalue,&nsd);
506         }
507         /* Remove trailing zeros and the "." if no digits follow the "." */
508         if( flag_rtz && flag_dp ){
509           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
510           assert( bufpt>zOut );
511           if( bufpt[-1]=='.' ){
512             if( flag_altform2 ){
513               *(bufpt++) = '0';
514             }else{
515               *(--bufpt) = 0;
516             }
517           }
518         }
519         /* Add the "eNNN" suffix */
520         if( xtype==etEXP ){
521           *(bufpt++) = aDigits[infop->charset];
522           if( exp<0 ){
523             *(bufpt++) = '-'; exp = -exp;
524           }else{
525             *(bufpt++) = '+';
526           }
527           if( exp>=100 ){
528             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
529             exp %= 100;
530           }
531           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
532           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
533         }
534         *bufpt = 0;
535 
536         /* The converted number is in buf[] and zero terminated. Output it.
537         ** Note that the number is in the usual order, not reversed as with
538         ** integer conversions. */
539         length = (int)(bufpt-zOut);
540         bufpt = zOut;
541 
542         /* Special case:  Add leading zeros if the flag_zeropad flag is
543         ** set and we are not left justified */
544         if( flag_zeropad && !flag_leftjustify && length < width){
545           int i;
546           int nPad = width - length;
547           for(i=width; i>=nPad; i--){
548             bufpt[i] = bufpt[i-nPad];
549           }
550           i = prefix!=0;
551           while( nPad-- ) bufpt[i++] = '0';
552           length = width;
553         }
554 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
555         break;
556       case etSIZE:
557         *(va_arg(ap,int*)) = pAccum->nChar;
558         length = width = 0;
559         break;
560       case etPERCENT:
561         buf[0] = '%';
562         bufpt = buf;
563         length = 1;
564         break;
565       case etCHARX:
566         c = va_arg(ap,int);
567         buf[0] = (char)c;
568         if( precision>=0 ){
569           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
570           length = precision;
571         }else{
572           length =1;
573         }
574         bufpt = buf;
575         break;
576       case etSTRING:
577       case etDYNSTRING:
578         bufpt = va_arg(ap,char*);
579         if( bufpt==0 ){
580           bufpt = "";
581         }else if( xtype==etDYNSTRING ){
582           zExtra = bufpt;
583         }
584         if( precision>=0 ){
585           for(length=0; length<precision && bufpt[length]; length++){}
586         }else{
587           length = sqlite3Strlen30(bufpt);
588         }
589         break;
590       case etSQLESCAPE:
591       case etSQLESCAPE2:
592       case etSQLESCAPE3: {
593         int i, j, k, n, isnull;
594         int needQuote;
595         char ch;
596         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
597         char *escarg = va_arg(ap,char*);
598         isnull = escarg==0;
599         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
600         k = precision;
601         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
602           if( ch==q )  n++;
603         }
604         needQuote = !isnull && xtype==etSQLESCAPE2;
605         n += i + 1 + needQuote*2;
606         if( n>etBUFSIZE ){
607           bufpt = zExtra = sqlite3Malloc( n );
608           if( bufpt==0 ){
609             pAccum->mallocFailed = 1;
610             return;
611           }
612         }else{
613           bufpt = buf;
614         }
615         j = 0;
616         if( needQuote ) bufpt[j++] = q;
617         k = i;
618         for(i=0; i<k; i++){
619           bufpt[j++] = ch = escarg[i];
620           if( ch==q ) bufpt[j++] = ch;
621         }
622         if( needQuote ) bufpt[j++] = q;
623         bufpt[j] = 0;
624         length = j;
625         /* The precision in %q and %Q means how many input characters to
626         ** consume, not the length of the output...
627         ** if( precision>=0 && precision<length ) length = precision; */
628         break;
629       }
630       case etTOKEN: {
631         Token *pToken = va_arg(ap, Token*);
632         if( pToken ){
633           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
634         }
635         length = width = 0;
636         break;
637       }
638       case etSRCLIST: {
639         SrcList *pSrc = va_arg(ap, SrcList*);
640         int k = va_arg(ap, int);
641         struct SrcList_item *pItem = &pSrc->a[k];
642         assert( k>=0 && k<pSrc->nSrc );
643         if( pItem->zDatabase ){
644           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
645           sqlite3StrAccumAppend(pAccum, ".", 1);
646         }
647         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
648         length = width = 0;
649         break;
650       }
651       default: {
652         assert( xtype==etINVALID );
653         return;
654       }
655     }/* End switch over the format type */
656     /*
657     ** The text of the conversion is pointed to by "bufpt" and is
658     ** "length" characters long.  The field width is "width".  Do
659     ** the output.
660     */
661     if( !flag_leftjustify ){
662       register int nspace;
663       nspace = width-length;
664       if( nspace>0 ){
665         sqlite3AppendSpace(pAccum, nspace);
666       }
667     }
668     if( length>0 ){
669       sqlite3StrAccumAppend(pAccum, bufpt, length);
670     }
671     if( flag_leftjustify ){
672       register int nspace;
673       nspace = width-length;
674       if( nspace>0 ){
675         sqlite3AppendSpace(pAccum, nspace);
676       }
677     }
678     sqlite3_free(zExtra);
679   }/* End for loop over the format string */
680 } /* End of function */
681 
682 /*
683 ** Append N bytes of text from z to the StrAccum object.
684 */
685 void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
686   assert( z!=0 || N==0 );
687   if( p->tooBig | p->mallocFailed ){
688     testcase(p->tooBig);
689     testcase(p->mallocFailed);
690     return;
691   }
692   assert( p->zText!=0 || p->nChar==0 );
693   if( N<0 ){
694     N = sqlite3Strlen30(z);
695   }
696   if( N==0 || NEVER(z==0) ){
697     return;
698   }
699   if( p->nChar+N >= p->nAlloc ){
700     char *zNew;
701     if( !p->useMalloc ){
702       p->tooBig = 1;
703       N = p->nAlloc - p->nChar - 1;
704       if( N<=0 ){
705         return;
706       }
707     }else{
708       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
709       i64 szNew = p->nChar;
710       szNew += N + 1;
711       if( szNew > p->mxAlloc ){
712         sqlite3StrAccumReset(p);
713         p->tooBig = 1;
714         return;
715       }else{
716         p->nAlloc = (int)szNew;
717       }
718       if( p->useMalloc==1 ){
719         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
720       }else{
721         zNew = sqlite3_realloc(zOld, p->nAlloc);
722       }
723       if( zNew ){
724         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
725         p->zText = zNew;
726       }else{
727         p->mallocFailed = 1;
728         sqlite3StrAccumReset(p);
729         return;
730       }
731     }
732   }
733   assert( p->zText );
734   memcpy(&p->zText[p->nChar], z, N);
735   p->nChar += N;
736 }
737 
738 /*
739 ** Finish off a string by making sure it is zero-terminated.
740 ** Return a pointer to the resulting string.  Return a NULL
741 ** pointer if any kind of error was encountered.
742 */
743 char *sqlite3StrAccumFinish(StrAccum *p){
744   if( p->zText ){
745     p->zText[p->nChar] = 0;
746     if( p->useMalloc && p->zText==p->zBase ){
747       if( p->useMalloc==1 ){
748         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
749       }else{
750         p->zText = sqlite3_malloc(p->nChar+1);
751       }
752       if( p->zText ){
753         memcpy(p->zText, p->zBase, p->nChar+1);
754       }else{
755         p->mallocFailed = 1;
756       }
757     }
758   }
759   return p->zText;
760 }
761 
762 /*
763 ** Reset an StrAccum string.  Reclaim all malloced memory.
764 */
765 void sqlite3StrAccumReset(StrAccum *p){
766   if( p->zText!=p->zBase ){
767     if( p->useMalloc==1 ){
768       sqlite3DbFree(p->db, p->zText);
769     }else{
770       sqlite3_free(p->zText);
771     }
772   }
773   p->zText = 0;
774 }
775 
776 /*
777 ** Initialize a string accumulator
778 */
779 void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
780   p->zText = p->zBase = zBase;
781   p->db = 0;
782   p->nChar = 0;
783   p->nAlloc = n;
784   p->mxAlloc = mx;
785   p->useMalloc = 1;
786   p->tooBig = 0;
787   p->mallocFailed = 0;
788 }
789 
790 /*
791 ** Print into memory obtained from sqliteMalloc().  Use the internal
792 ** %-conversion extensions.
793 */
794 char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
795   char *z;
796   char zBase[SQLITE_PRINT_BUF_SIZE];
797   StrAccum acc;
798   assert( db!=0 );
799   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
800                       db->aLimit[SQLITE_LIMIT_LENGTH]);
801   acc.db = db;
802   sqlite3VXPrintf(&acc, 1, zFormat, ap);
803   z = sqlite3StrAccumFinish(&acc);
804   if( acc.mallocFailed ){
805     db->mallocFailed = 1;
806   }
807   return z;
808 }
809 
810 /*
811 ** Print into memory obtained from sqliteMalloc().  Use the internal
812 ** %-conversion extensions.
813 */
814 char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
815   va_list ap;
816   char *z;
817   va_start(ap, zFormat);
818   z = sqlite3VMPrintf(db, zFormat, ap);
819   va_end(ap);
820   return z;
821 }
822 
823 /*
824 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
825 ** the string and before returnning.  This routine is intended to be used
826 ** to modify an existing string.  For example:
827 **
828 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
829 **
830 */
831 char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
832   va_list ap;
833   char *z;
834   va_start(ap, zFormat);
835   z = sqlite3VMPrintf(db, zFormat, ap);
836   va_end(ap);
837   sqlite3DbFree(db, zStr);
838   return z;
839 }
840 
841 /*
842 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
843 ** %-conversion extensions.
844 */
845 char *sqlite3_vmprintf(const char *zFormat, va_list ap){
846   char *z;
847   char zBase[SQLITE_PRINT_BUF_SIZE];
848   StrAccum acc;
849 #ifndef SQLITE_OMIT_AUTOINIT
850   if( sqlite3_initialize() ) return 0;
851 #endif
852   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
853   acc.useMalloc = 2;
854   sqlite3VXPrintf(&acc, 0, zFormat, ap);
855   z = sqlite3StrAccumFinish(&acc);
856   return z;
857 }
858 
859 /*
860 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
861 ** %-conversion extensions.
862 */
863 char *sqlite3_mprintf(const char *zFormat, ...){
864   va_list ap;
865   char *z;
866 #ifndef SQLITE_OMIT_AUTOINIT
867   if( sqlite3_initialize() ) return 0;
868 #endif
869   va_start(ap, zFormat);
870   z = sqlite3_vmprintf(zFormat, ap);
871   va_end(ap);
872   return z;
873 }
874 
875 /*
876 ** sqlite3_snprintf() works like snprintf() except that it ignores the
877 ** current locale settings.  This is important for SQLite because we
878 ** are not able to use a "," as the decimal point in place of "." as
879 ** specified by some locales.
880 **
881 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
882 ** from the snprintf() standard.  Unfortunately, it is too late to change
883 ** this without breaking compatibility, so we just have to live with the
884 ** mistake.
885 **
886 ** sqlite3_vsnprintf() is the varargs version.
887 */
888 char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
889   StrAccum acc;
890   if( n<=0 ) return zBuf;
891   sqlite3StrAccumInit(&acc, zBuf, n, 0);
892   acc.useMalloc = 0;
893   sqlite3VXPrintf(&acc, 0, zFormat, ap);
894   return sqlite3StrAccumFinish(&acc);
895 }
896 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
897   char *z;
898   va_list ap;
899   va_start(ap,zFormat);
900   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
901   va_end(ap);
902   return z;
903 }
904 
905 /*
906 ** This is the routine that actually formats the sqlite3_log() message.
907 ** We house it in a separate routine from sqlite3_log() to avoid using
908 ** stack space on small-stack systems when logging is disabled.
909 **
910 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
911 ** allocate memory because it might be called while the memory allocator
912 ** mutex is held.
913 */
914 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
915   StrAccum acc;                          /* String accumulator */
916   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
917 
918   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
919   acc.useMalloc = 0;
920   sqlite3VXPrintf(&acc, 0, zFormat, ap);
921   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
922                            sqlite3StrAccumFinish(&acc));
923 }
924 
925 /*
926 ** Format and write a message to the log if logging is enabled.
927 */
928 void sqlite3_log(int iErrCode, const char *zFormat, ...){
929   va_list ap;                             /* Vararg list */
930   if( sqlite3GlobalConfig.xLog ){
931     va_start(ap, zFormat);
932     renderLogMsg(iErrCode, zFormat, ap);
933     va_end(ap);
934   }
935 }
936 
937 #if defined(SQLITE_DEBUG)
938 /*
939 ** A version of printf() that understands %lld.  Used for debugging.
940 ** The printf() built into some versions of windows does not understand %lld
941 ** and segfaults if you give it a long long int.
942 */
943 void sqlite3DebugPrintf(const char *zFormat, ...){
944   va_list ap;
945   StrAccum acc;
946   char zBuf[500];
947   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
948   acc.useMalloc = 0;
949   va_start(ap,zFormat);
950   sqlite3VXPrintf(&acc, 0, zFormat, ap);
951   va_end(ap);
952   sqlite3StrAccumFinish(&acc);
953   fprintf(stdout,"%s", zBuf);
954   fflush(stdout);
955 }
956 #endif
957 
958 #ifndef SQLITE_OMIT_TRACE
959 /*
960 ** variable-argument wrapper around sqlite3VXPrintf().
961 */
962 void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
963   va_list ap;
964   va_start(ap,zFormat);
965   sqlite3VXPrintf(p, 1, zFormat, ap);
966   va_end(ap);
967 }
968 #endif
969