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