extensions/sqlite/sqlite-source/printf.c
author David Anderson <dvander@alliedmods.net>
Sun Oct 28 05:48:06 2007 +0000 (2007-10-28)
changeset 1645 27307df4d711
parent 1203 633c25ce6405
permissions -rw-r--r--
updated to sqlite-3.5.1 now that it's stable
used new shared cache functionality (yay)
     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, 4, 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 = sqlite3_malloc( 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       sqlite3_free(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   int  iMallocFailed;            /* True if xRealloc() has failed */
   722 };
   723 
   724 /* 
   725 ** This function implements the callback from vxprintf. 
   726 **
   727 ** This routine add nNewChar characters of text in zNewText to
   728 ** the sgMprintf structure pointed to by "arg".
   729 */
   730 static void mout(void *arg, const char *zNewText, int nNewChar){
   731   struct sgMprintf *pM = (struct sgMprintf*)arg;
   732   if( pM->iMallocFailed ) return;
   733   pM->nTotal += nNewChar;
   734   if( pM->zText ){
   735     if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
   736       if( pM->xRealloc==0 ){
   737         nNewChar =  pM->nAlloc - pM->nChar - 1;
   738       }else{
   739         int nAlloc = pM->nChar + nNewChar*2 + 1;
   740         if( pM->zText==pM->zBase ){
   741           pM->zText = pM->xRealloc(0, nAlloc);
   742           if( pM->zText==0 ){
   743             pM->nAlloc = 0;
   744             pM->iMallocFailed = 1;
   745             return;
   746           }else if( pM->nChar ){
   747             memcpy(pM->zText, pM->zBase, pM->nChar);
   748           }
   749         }else{
   750           char *zNew;
   751           zNew = pM->xRealloc(pM->zText, nAlloc);
   752           if( zNew ){
   753             pM->zText = zNew;
   754           }else{
   755             pM->iMallocFailed = 1;
   756             pM->xRealloc(pM->zText, 0);
   757             pM->zText = 0;
   758             pM->nAlloc = 0;
   759             return;
   760           }
   761         }
   762         pM->nAlloc = nAlloc;
   763       }
   764     }
   765     if( nNewChar>0 ){
   766       memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
   767       pM->nChar += nNewChar;
   768     }
   769     pM->zText[pM->nChar] = 0;
   770   }
   771 }
   772 
   773 /*
   774 ** This routine is a wrapper around xprintf() that invokes mout() as
   775 ** the consumer.  
   776 */
   777 static char *base_vprintf(
   778   void *(*xRealloc)(void*, int),  /* realloc() function. May be NULL */
   779   int useInternal,                /* Use internal %-conversions if true */
   780   char *zInitBuf,                 /* Initially write here, before mallocing */
   781   int nInitBuf,                   /* Size of zInitBuf[] */
   782   const char *zFormat,            /* format string */
   783   va_list ap                      /* arguments */
   784 ){
   785   struct sgMprintf sM;
   786   sM.zBase = sM.zText = zInitBuf;
   787   sM.nChar = sM.nTotal = 0;
   788   sM.nAlloc = nInitBuf;
   789   sM.xRealloc = xRealloc;
   790   sM.iMallocFailed = 0;
   791   vxprintf(mout, &sM, useInternal, zFormat, ap);
   792   assert(sM.iMallocFailed==0 || sM.zText==0);
   793   if( xRealloc && !sM.iMallocFailed ){
   794     if( sM.zText==sM.zBase ){
   795       sM.zText = xRealloc(0, sM.nChar+1);
   796       if( sM.zText ){
   797         memcpy(sM.zText, sM.zBase, sM.nChar+1);
   798       }
   799     }else if( sM.nAlloc>sM.nChar+10 ){
   800       char *zNew;
   801       sqlite3MallocBenignFailure(1);
   802       zNew = xRealloc(sM.zText, sM.nChar+1);
   803       if( zNew ){
   804         sM.zText = zNew;
   805       }
   806     }
   807   }
   808   return sM.zText;
   809 }
   810 
   811 /*
   812 ** Realloc that is a real function, not a macro.
   813 */
   814 static void *printf_realloc(void *old, int size){
   815   return sqlite3_realloc(old, size);
   816 }
   817 
   818 /*
   819 ** Print into memory obtained from sqliteMalloc().  Use the internal
   820 ** %-conversion extensions.
   821 */
   822 char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
   823   char *z;
   824   char zBase[SQLITE_PRINT_BUF_SIZE];
   825   z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
   826   if( z==0 && db!=0 ){
   827     db->mallocFailed = 1;
   828   }
   829   return z;
   830 }
   831 
   832 /*
   833 ** Print into memory obtained from sqliteMalloc().  Use the internal
   834 ** %-conversion extensions.
   835 */
   836 char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
   837   va_list ap;
   838   char *z;
   839   char zBase[SQLITE_PRINT_BUF_SIZE];
   840   va_start(ap, zFormat);
   841   z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
   842   va_end(ap);
   843   if( z==0 && db!=0 ){
   844     db->mallocFailed = 1;
   845   }
   846   return z;
   847 }
   848 
   849 /*
   850 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
   851 ** %-conversion extensions.
   852 */
   853 char *sqlite3_vmprintf(const char *zFormat, va_list ap){
   854   char zBase[SQLITE_PRINT_BUF_SIZE];
   855   return base_vprintf(sqlite3_realloc, 0, zBase, sizeof(zBase), zFormat, ap);
   856 }
   857 
   858 /*
   859 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
   860 ** %-conversion extensions.
   861 */
   862 char *sqlite3_mprintf(const char *zFormat, ...){
   863   va_list ap;
   864   char *z;
   865   va_start(ap, zFormat);
   866   z = sqlite3_vmprintf(zFormat, ap);
   867   va_end(ap);
   868   return z;
   869 }
   870 
   871 /*
   872 ** sqlite3_snprintf() works like snprintf() except that it ignores the
   873 ** current locale settings.  This is important for SQLite because we
   874 ** are not able to use a "," as the decimal point in place of "." as
   875 ** specified by some locales.
   876 */
   877 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
   878   char *z;
   879   va_list ap;
   880 
   881   if( n<=0 ){
   882     return zBuf;
   883   }
   884   zBuf[0] = 0;
   885   va_start(ap,zFormat);
   886   z = base_vprintf(0, 0, zBuf, n, zFormat, ap);
   887   va_end(ap);
   888   return z;
   889 }
   890 
   891 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) || defined(SQLITE_MEMDEBUG)
   892 /*
   893 ** A version of printf() that understands %lld.  Used for debugging.
   894 ** The printf() built into some versions of windows does not understand %lld
   895 ** and segfaults if you give it a long long int.
   896 */
   897 void sqlite3DebugPrintf(const char *zFormat, ...){
   898   extern int getpid(void);
   899   va_list ap;
   900   char zBuf[500];
   901   va_start(ap, zFormat);
   902   base_vprintf(0, 0, zBuf, sizeof(zBuf), zFormat, ap);
   903   va_end(ap);
   904   fprintf(stdout,"%s", zBuf);
   905   fflush(stdout);
   906 }
   907 #endif