Back to index

lightning-sunbird  0.9+nobinonly
printf.c
Go to the documentation of this file.
00001 /*
00002 ** The "printf" code that follows dates from the 1980's.  It is in
00003 ** the public domain.  The original comments are included here for
00004 ** completeness.  They are very out-of-date but might be useful as
00005 ** an historical reference.  Most of the "enhancements" have been backed
00006 ** out so that the functionality is now the same as standard printf().
00007 **
00008 **************************************************************************
00009 **
00010 ** The following modules is an enhanced replacement for the "printf" subroutines
00011 ** found in the standard C library.  The following enhancements are
00012 ** supported:
00013 **
00014 **      +  Additional functions.  The standard set of "printf" functions
00015 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
00016 **         vsprintf.  This module adds the following:
00017 **
00018 **           *  snprintf -- Works like sprintf, but has an extra argument
00019 **                          which is the size of the buffer written to.
00020 **
00021 **           *  mprintf --  Similar to sprintf.  Writes output to memory
00022 **                          obtained from malloc.
00023 **
00024 **           *  xprintf --  Calls a function to dispose of output.
00025 **
00026 **           *  nprintf --  No output, but returns the number of characters
00027 **                          that would have been output by printf.
00028 **
00029 **           *  A v- version (ex: vsnprintf) of every function is also
00030 **              supplied.
00031 **
00032 **      +  A few extensions to the formatting notation are supported:
00033 **
00034 **           *  The "=" flag (similar to "-") causes the output to be
00035 **              be centered in the appropriately sized field.
00036 **
00037 **           *  The %b field outputs an integer in binary notation.
00038 **
00039 **           *  The %c field now accepts a precision.  The character output
00040 **              is repeated by the number of times the precision specifies.
00041 **
00042 **           *  The %' field works like %c, but takes as its character the
00043 **              next character of the format string, instead of the next
00044 **              argument.  For example,  printf("%.78'-")  prints 78 minus
00045 **              signs, the same as  printf("%.78c",'-').
00046 **
00047 **      +  When compiled using GCC on a SPARC, this version of printf is
00048 **         faster than the library printf for SUN OS 4.1.
00049 **
00050 **      +  All functions are fully reentrant.
00051 **
00052 */
00053 #include "sqliteInt.h"
00054 
00055 /*
00056 ** Conversion types fall into various categories as defined by the
00057 ** following enumeration.
00058 */
00059 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
00060 #define etFLOAT       2 /* Floating point.  %f */
00061 #define etEXP         3 /* Exponentional notation. %e and %E */
00062 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
00063 #define etSIZE        5 /* Return number of characters processed so far. %n */
00064 #define etSTRING      6 /* Strings. %s */
00065 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
00066 #define etPERCENT     8 /* Percent symbol. %% */
00067 #define etCHARX       9 /* Characters. %c */
00068 /* The rest are extensions, not normally found in printf() */
00069 #define etCHARLIT    10 /* Literal characters.  %' */
00070 #define etSQLESCAPE  11 /* Strings with '\'' doubled.  %q */
00071 #define etSQLESCAPE2 12 /* Strings with '\'' doubled and enclosed in '',
00072                           NULL pointers replaced by SQL NULL.  %Q */
00073 #define etTOKEN      13 /* a pointer to a Token structure */
00074 #define etSRCLIST    14 /* a pointer to a SrcList */
00075 #define etPOINTER    15 /* The %p conversion */
00076 
00077 
00078 /*
00079 ** An "etByte" is an 8-bit unsigned value.
00080 */
00081 typedef unsigned char etByte;
00082 
00083 /*
00084 ** Each builtin conversion character (ex: the 'd' in "%d") is described
00085 ** by an instance of the following structure
00086 */
00087 typedef struct et_info {   /* Information about each format field */
00088   char fmttype;            /* The format field code letter */
00089   etByte base;             /* The base for radix conversion */
00090   etByte flags;            /* One or more of FLAG_ constants below */
00091   etByte type;             /* Conversion paradigm */
00092   etByte charset;          /* Offset into aDigits[] of the digits string */
00093   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
00094 } et_info;
00095 
00096 /*
00097 ** Allowed values for et_info.flags
00098 */
00099 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
00100 #define FLAG_INTERN  2     /* True if for internal use only */
00101 #define FLAG_STRING  4     /* Allow infinity precision */
00102 
00103 
00104 /*
00105 ** The following table is searched linearly, so it is good to put the
00106 ** most frequently used conversion types first.
00107 */
00108 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
00109 static const char aPrefix[] = "-x0\000X0";
00110 static const et_info fmtinfo[] = {
00111   {  'd', 10, 1, etRADIX,      0,  0 },
00112   {  's',  0, 4, etSTRING,     0,  0 },
00113   {  'g',  0, 1, etGENERIC,    30, 0 },
00114   {  'z',  0, 6, etDYNSTRING,  0,  0 },
00115   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
00116   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
00117   {  'c',  0, 0, etCHARX,      0,  0 },
00118   {  'o',  8, 0, etRADIX,      0,  2 },
00119   {  'u', 10, 0, etRADIX,      0,  0 },
00120   {  'x', 16, 0, etRADIX,      16, 1 },
00121   {  'X', 16, 0, etRADIX,      0,  4 },
00122 #ifndef SQLITE_OMIT_FLOATING_POINT
00123   {  'f',  0, 1, etFLOAT,      0,  0 },
00124   {  'e',  0, 1, etEXP,        30, 0 },
00125   {  'E',  0, 1, etEXP,        14, 0 },
00126   {  'G',  0, 1, etGENERIC,    14, 0 },
00127 #endif
00128   {  'i', 10, 1, etRADIX,      0,  0 },
00129   {  'n',  0, 0, etSIZE,       0,  0 },
00130   {  '%',  0, 0, etPERCENT,    0,  0 },
00131   {  'p', 16, 0, etPOINTER,    0,  1 },
00132   {  'T',  0, 2, etTOKEN,      0,  0 },
00133   {  'S',  0, 2, etSRCLIST,    0,  0 },
00134 };
00135 #define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
00136 
00137 /*
00138 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
00139 ** conversions will work.
00140 */
00141 #ifndef SQLITE_OMIT_FLOATING_POINT
00142 /*
00143 ** "*val" is a double such that 0.1 <= *val < 10.0
00144 ** Return the ascii code for the leading digit of *val, then
00145 ** multiply "*val" by 10.0 to renormalize.
00146 **
00147 ** Example:
00148 **     input:     *val = 3.14159
00149 **     output:    *val = 1.4159    function return = '3'
00150 **
00151 ** The counter *cnt is incremented each time.  After counter exceeds
00152 ** 16 (the number of significant digits in a 64-bit float) '0' is
00153 ** always returned.
00154 */
00155 static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
00156   int digit;
00157   LONGDOUBLE_TYPE d;
00158   if( (*cnt)++ >= 16 ) return '0';
00159   digit = (int)*val;
00160   d = digit;
00161   digit += '0';
00162   *val = (*val - d)*10.0;
00163   return digit;
00164 }
00165 #endif /* SQLITE_OMIT_FLOATING_POINT */
00166 
00167 /*
00168 ** On machines with a small stack size, you can redefine the
00169 ** SQLITE_PRINT_BUF_SIZE to be less than 350.  But beware - for
00170 ** smaller values some %f conversions may go into an infinite loop.
00171 */
00172 #ifndef SQLITE_PRINT_BUF_SIZE
00173 # define SQLITE_PRINT_BUF_SIZE 350
00174 #endif
00175 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
00176 
00177 /*
00178 ** The root program.  All variations call this core.
00179 **
00180 ** INPUTS:
00181 **   func   This is a pointer to a function taking three arguments
00182 **            1. A pointer to anything.  Same as the "arg" parameter.
00183 **            2. A pointer to the list of characters to be output
00184 **               (Note, this list is NOT null terminated.)
00185 **            3. An integer number of characters to be output.
00186 **               (Note: This number might be zero.)
00187 **
00188 **   arg    This is the pointer to anything which will be passed as the
00189 **          first argument to "func".  Use it for whatever you like.
00190 **
00191 **   fmt    This is the format string, as in the usual print.
00192 **
00193 **   ap     This is a pointer to a list of arguments.  Same as in
00194 **          vfprint.
00195 **
00196 ** OUTPUTS:
00197 **          The return value is the total number of characters sent to
00198 **          the function "func".  Returns -1 on a error.
00199 **
00200 ** Note that the order in which automatic variables are declared below
00201 ** seems to make a big difference in determining how fast this beast
00202 ** will run.
00203 */
00204 static int vxprintf(
00205   void (*func)(void*,const char*,int),     /* Consumer of text */
00206   void *arg,                         /* First argument to the consumer */
00207   int useExtended,                   /* Allow extended %-conversions */
00208   const char *fmt,                   /* Format string */
00209   va_list ap                         /* arguments */
00210 ){
00211   int c;                     /* Next character in the format string */
00212   char *bufpt;               /* Pointer to the conversion buffer */
00213   int precision;             /* Precision of the current field */
00214   int length;                /* Length of the field */
00215   int idx;                   /* A general purpose loop counter */
00216   int count;                 /* Total number of characters output */
00217   int width;                 /* Width of the current field */
00218   etByte flag_leftjustify;   /* True if "-" flag is present */
00219   etByte flag_plussign;      /* True if "+" flag is present */
00220   etByte flag_blanksign;     /* True if " " flag is present */
00221   etByte flag_alternateform; /* True if "#" flag is present */
00222   etByte flag_altform2;      /* True if "!" flag is present */
00223   etByte flag_zeropad;       /* True if field width constant starts with zero */
00224   etByte flag_long;          /* True if "l" flag is present */
00225   etByte flag_longlong;      /* True if the "ll" flag is present */
00226   etByte done;               /* Loop termination flag */
00227   sqlite_uint64 longvalue;   /* Value for integer types */
00228   LONGDOUBLE_TYPE realvalue; /* Value for real types */
00229   const et_info *infop;      /* Pointer to the appropriate info structure */
00230   char buf[etBUFSIZE];       /* Conversion buffer */
00231   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
00232   etByte errorflag = 0;      /* True if an error is encountered */
00233   etByte xtype;              /* Conversion paradigm */
00234   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
00235   static const char spaces[] =
00236    "                                                                         ";
00237 #define etSPACESIZE (sizeof(spaces)-1)
00238 #ifndef SQLITE_OMIT_FLOATING_POINT
00239   int  exp, e2;              /* exponent of real numbers */
00240   double rounder;            /* Used for rounding floating point values */
00241   etByte flag_dp;            /* True if decimal point should be shown */
00242   etByte flag_rtz;           /* True if trailing zeros should be removed */
00243   etByte flag_exp;           /* True to force display of the exponent */
00244   int nsd;                   /* Number of significant digits returned */
00245 #endif
00246 
00247   func(arg,"",0);
00248   count = length = 0;
00249   bufpt = 0;
00250   for(; (c=(*fmt))!=0; ++fmt){
00251     if( c!='%' ){
00252       int amt;
00253       bufpt = (char *)fmt;
00254       amt = 1;
00255       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
00256       (*func)(arg,bufpt,amt);
00257       count += amt;
00258       if( c==0 ) break;
00259     }
00260     if( (c=(*++fmt))==0 ){
00261       errorflag = 1;
00262       (*func)(arg,"%",1);
00263       count++;
00264       break;
00265     }
00266     /* Find out what flags are present */
00267     flag_leftjustify = flag_plussign = flag_blanksign = 
00268      flag_alternateform = flag_altform2 = flag_zeropad = 0;
00269     done = 0;
00270     do{
00271       switch( c ){
00272         case '-':   flag_leftjustify = 1;     break;
00273         case '+':   flag_plussign = 1;        break;
00274         case ' ':   flag_blanksign = 1;       break;
00275         case '#':   flag_alternateform = 1;   break;
00276         case '!':   flag_altform2 = 1;        break;
00277         case '0':   flag_zeropad = 1;         break;
00278         default:    done = 1;                 break;
00279       }
00280     }while( !done && (c=(*++fmt))!=0 );
00281     /* Get the field width */
00282     width = 0;
00283     if( c=='*' ){
00284       width = va_arg(ap,int);
00285       if( width<0 ){
00286         flag_leftjustify = 1;
00287         width = -width;
00288       }
00289       c = *++fmt;
00290     }else{
00291       while( c>='0' && c<='9' ){
00292         width = width*10 + c - '0';
00293         c = *++fmt;
00294       }
00295     }
00296     if( width > etBUFSIZE-10 ){
00297       width = etBUFSIZE-10;
00298     }
00299     /* Get the precision */
00300     if( c=='.' ){
00301       precision = 0;
00302       c = *++fmt;
00303       if( c=='*' ){
00304         precision = va_arg(ap,int);
00305         if( precision<0 ) precision = -precision;
00306         c = *++fmt;
00307       }else{
00308         while( c>='0' && c<='9' ){
00309           precision = precision*10 + c - '0';
00310           c = *++fmt;
00311         }
00312       }
00313     }else{
00314       precision = -1;
00315     }
00316     /* Get the conversion type modifier */
00317     if( c=='l' ){
00318       flag_long = 1;
00319       c = *++fmt;
00320       if( c=='l' ){
00321         flag_longlong = 1;
00322         c = *++fmt;
00323       }else{
00324         flag_longlong = 0;
00325       }
00326     }else{
00327       flag_long = flag_longlong = 0;
00328     }
00329     /* Fetch the info entry for the field */
00330     infop = 0;
00331     for(idx=0; idx<etNINFO; idx++){
00332       if( c==fmtinfo[idx].fmttype ){
00333         infop = &fmtinfo[idx];
00334         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
00335           xtype = infop->type;
00336         }
00337         break;
00338       }
00339     }
00340     zExtra = 0;
00341     if( infop==0 ){
00342       return -1;
00343     }
00344 
00345 
00346     /* Limit the precision to prevent overflowing buf[] during conversion */
00347     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
00348       precision = etBUFSIZE-40;
00349     }
00350 
00351     /*
00352     ** At this point, variables are initialized as follows:
00353     **
00354     **   flag_alternateform          TRUE if a '#' is present.
00355     **   flag_altform2               TRUE if a '!' is present.
00356     **   flag_plussign               TRUE if a '+' is present.
00357     **   flag_leftjustify            TRUE if a '-' is present or if the
00358     **                               field width was negative.
00359     **   flag_zeropad                TRUE if the width began with 0.
00360     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
00361     **                               the conversion character.
00362     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
00363     **                               the conversion character.
00364     **   flag_blanksign              TRUE if a ' ' is present.
00365     **   width                       The specified field width.  This is
00366     **                               always non-negative.  Zero is the default.
00367     **   precision                   The specified precision.  The default
00368     **                               is -1.
00369     **   xtype                       The class of the conversion.
00370     **   infop                       Pointer to the appropriate info struct.
00371     */
00372     switch( xtype ){
00373       case etPOINTER:
00374         flag_longlong = sizeof(char*)==sizeof(i64);
00375         flag_long = sizeof(char*)==sizeof(long int);
00376         /* Fall through into the next case */
00377       case etRADIX:
00378         if( infop->flags & FLAG_SIGNED ){
00379           i64 v;
00380           if( flag_longlong )   v = va_arg(ap,i64);
00381           else if( flag_long )  v = va_arg(ap,long int);
00382           else                  v = va_arg(ap,int);
00383           if( v<0 ){
00384             longvalue = -v;
00385             prefix = '-';
00386           }else{
00387             longvalue = v;
00388             if( flag_plussign )        prefix = '+';
00389             else if( flag_blanksign )  prefix = ' ';
00390             else                       prefix = 0;
00391           }
00392         }else{
00393           if( flag_longlong )   longvalue = va_arg(ap,u64);
00394           else if( flag_long )  longvalue = va_arg(ap,unsigned long int);
00395           else                  longvalue = va_arg(ap,unsigned int);
00396           prefix = 0;
00397         }
00398         if( longvalue==0 ) flag_alternateform = 0;
00399         if( flag_zeropad && precision<width-(prefix!=0) ){
00400           precision = width-(prefix!=0);
00401         }
00402         bufpt = &buf[etBUFSIZE-1];
00403         {
00404           register const char *cset;      /* Use registers for speed */
00405           register int base;
00406           cset = &aDigits[infop->charset];
00407           base = infop->base;
00408           do{                                           /* Convert to ascii */
00409             *(--bufpt) = cset[longvalue%base];
00410             longvalue = longvalue/base;
00411           }while( longvalue>0 );
00412         }
00413         length = &buf[etBUFSIZE-1]-bufpt;
00414         for(idx=precision-length; idx>0; idx--){
00415           *(--bufpt) = '0';                             /* Zero pad */
00416         }
00417         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
00418         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
00419           const char *pre;
00420           char x;
00421           pre = &aPrefix[infop->prefix];
00422           if( *bufpt!=pre[0] ){
00423             for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
00424           }
00425         }
00426         length = &buf[etBUFSIZE-1]-bufpt;
00427         break;
00428       case etFLOAT:
00429       case etEXP:
00430       case etGENERIC:
00431         realvalue = va_arg(ap,double);
00432 #ifndef SQLITE_OMIT_FLOATING_POINT
00433         if( precision<0 ) precision = 6;         /* Set default precision */
00434         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
00435         if( realvalue<0.0 ){
00436           realvalue = -realvalue;
00437           prefix = '-';
00438         }else{
00439           if( flag_plussign )          prefix = '+';
00440           else if( flag_blanksign )    prefix = ' ';
00441           else                         prefix = 0;
00442         }
00443         if( xtype==etGENERIC && precision>0 ) precision--;
00444 #if 0
00445         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
00446         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
00447 #else
00448         /* It makes more sense to use 0.5 */
00449         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
00450 #endif
00451         if( xtype==etFLOAT ) realvalue += rounder;
00452         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
00453         exp = 0;
00454         if( realvalue>0.0 ){
00455           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
00456           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
00457           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
00458           while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
00459           while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
00460           if( exp>350 || exp<-350 ){
00461             bufpt = "NaN";
00462             length = 3;
00463             break;
00464           }
00465         }
00466         bufpt = buf;
00467         /*
00468         ** If the field type is etGENERIC, then convert to either etEXP
00469         ** or etFLOAT, as appropriate.
00470         */
00471         flag_exp = xtype==etEXP;
00472         if( xtype!=etFLOAT ){
00473           realvalue += rounder;
00474           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
00475         }
00476         if( xtype==etGENERIC ){
00477           flag_rtz = !flag_alternateform;
00478           if( exp<-4 || exp>precision ){
00479             xtype = etEXP;
00480           }else{
00481             precision = precision - exp;
00482             xtype = etFLOAT;
00483           }
00484         }else{
00485           flag_rtz = 0;
00486         }
00487         if( xtype==etEXP ){
00488           e2 = 0;
00489         }else{
00490           e2 = exp;
00491         }
00492         nsd = 0;
00493         flag_dp = (precision>0) | flag_alternateform | flag_altform2;
00494         /* The sign in front of the number */
00495         if( prefix ){
00496           *(bufpt++) = prefix;
00497         }
00498         /* Digits prior to the decimal point */
00499         if( e2<0 ){
00500           *(bufpt++) = '0';
00501         }else{
00502           for(; e2>=0; e2--){
00503             *(bufpt++) = et_getdigit(&realvalue,&nsd);
00504           }
00505         }
00506         /* The decimal point */
00507         if( flag_dp ){
00508           *(bufpt++) = '.';
00509         }
00510         /* "0" digits after the decimal point but before the first
00511         ** significant digit of the number */
00512         for(e2++; e2<0 && precision>0; precision--, e2++){
00513           *(bufpt++) = '0';
00514         }
00515         /* Significant digits after the decimal point */
00516         while( (precision--)>0 ){
00517           *(bufpt++) = et_getdigit(&realvalue,&nsd);
00518         }
00519         /* Remove trailing zeros and the "." if no digits follow the "." */
00520         if( flag_rtz && flag_dp ){
00521           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
00522           assert( bufpt>buf );
00523           if( bufpt[-1]=='.' ){
00524             if( flag_altform2 ){
00525               *(bufpt++) = '0';
00526             }else{
00527               *(--bufpt) = 0;
00528             }
00529           }
00530         }
00531         /* Add the "eNNN" suffix */
00532         if( flag_exp || (xtype==etEXP && exp) ){
00533           *(bufpt++) = aDigits[infop->charset];
00534           if( exp<0 ){
00535             *(bufpt++) = '-'; exp = -exp;
00536           }else{
00537             *(bufpt++) = '+';
00538           }
00539           if( exp>=100 ){
00540             *(bufpt++) = (exp/100)+'0';                /* 100's digit */
00541             exp %= 100;
00542           }
00543           *(bufpt++) = exp/10+'0';                     /* 10's digit */
00544           *(bufpt++) = exp%10+'0';                     /* 1's digit */
00545         }
00546         *bufpt = 0;
00547 
00548         /* The converted number is in buf[] and zero terminated. Output it.
00549         ** Note that the number is in the usual order, not reversed as with
00550         ** integer conversions. */
00551         length = bufpt-buf;
00552         bufpt = buf;
00553 
00554         /* Special case:  Add leading zeros if the flag_zeropad flag is
00555         ** set and we are not left justified */
00556         if( flag_zeropad && !flag_leftjustify && length < width){
00557           int i;
00558           int nPad = width - length;
00559           for(i=width; i>=nPad; i--){
00560             bufpt[i] = bufpt[i-nPad];
00561           }
00562           i = prefix!=0;
00563           while( nPad-- ) bufpt[i++] = '0';
00564           length = width;
00565         }
00566 #endif
00567         break;
00568       case etSIZE:
00569         *(va_arg(ap,int*)) = count;
00570         length = width = 0;
00571         break;
00572       case etPERCENT:
00573         buf[0] = '%';
00574         bufpt = buf;
00575         length = 1;
00576         break;
00577       case etCHARLIT:
00578       case etCHARX:
00579         c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
00580         if( precision>=0 ){
00581           for(idx=1; idx<precision; idx++) buf[idx] = c;
00582           length = precision;
00583         }else{
00584           length =1;
00585         }
00586         bufpt = buf;
00587         break;
00588       case etSTRING:
00589       case etDYNSTRING:
00590         bufpt = va_arg(ap,char*);
00591         if( bufpt==0 ){
00592           bufpt = "";
00593         }else if( xtype==etDYNSTRING ){
00594           zExtra = bufpt;
00595         }
00596         length = strlen(bufpt);
00597         if( precision>=0 && precision<length ) length = precision;
00598         break;
00599       case etSQLESCAPE:
00600       case etSQLESCAPE2: {
00601         int i, j, n, ch, isnull;
00602         int needQuote;
00603         char *escarg = va_arg(ap,char*);
00604         isnull = escarg==0;
00605         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
00606         for(i=n=0; (ch=escarg[i])!=0; i++){
00607           if( ch=='\'' )  n++;
00608         }
00609         needQuote = !isnull && xtype==etSQLESCAPE2;
00610         n += i + 1 + needQuote*2;
00611         if( n>etBUFSIZE ){
00612           bufpt = zExtra = sqliteMalloc( n );
00613           if( bufpt==0 ) return -1;
00614         }else{
00615           bufpt = buf;
00616         }
00617         j = 0;
00618         if( needQuote ) bufpt[j++] = '\'';
00619         for(i=0; (ch=escarg[i])!=0; i++){
00620           bufpt[j++] = ch;
00621           if( ch=='\'' ) bufpt[j++] = ch;
00622         }
00623         if( needQuote ) bufpt[j++] = '\'';
00624         bufpt[j] = 0;
00625         length = j;
00626         /* The precision is ignored on %q and %Q */
00627         /* if( precision>=0 && precision<length ) length = precision; */
00628         break;
00629       }
00630       case etTOKEN: {
00631         Token *pToken = va_arg(ap, Token*);
00632         if( pToken && pToken->z ){
00633           (*func)(arg, (char*)pToken->z, pToken->n);
00634         }
00635         length = width = 0;
00636         break;
00637       }
00638       case etSRCLIST: {
00639         SrcList *pSrc = va_arg(ap, SrcList*);
00640         int k = va_arg(ap, int);
00641         struct SrcList_item *pItem = &pSrc->a[k];
00642         assert( k>=0 && k<pSrc->nSrc );
00643         if( pItem->zDatabase && pItem->zDatabase[0] ){
00644           (*func)(arg, pItem->zDatabase, strlen(pItem->zDatabase));
00645           (*func)(arg, ".", 1);
00646         }
00647         (*func)(arg, pItem->zName, strlen(pItem->zName));
00648         length = width = 0;
00649         break;
00650       }
00651     }/* End switch over the format type */
00652     /*
00653     ** The text of the conversion is pointed to by "bufpt" and is
00654     ** "length" characters long.  The field width is "width".  Do
00655     ** the output.
00656     */
00657     if( !flag_leftjustify ){
00658       register int nspace;
00659       nspace = width-length;
00660       if( nspace>0 ){
00661         count += nspace;
00662         while( nspace>=etSPACESIZE ){
00663           (*func)(arg,spaces,etSPACESIZE);
00664           nspace -= etSPACESIZE;
00665         }
00666         if( nspace>0 ) (*func)(arg,spaces,nspace);
00667       }
00668     }
00669     if( length>0 ){
00670       (*func)(arg,bufpt,length);
00671       count += length;
00672     }
00673     if( flag_leftjustify ){
00674       register int nspace;
00675       nspace = width-length;
00676       if( nspace>0 ){
00677         count += nspace;
00678         while( nspace>=etSPACESIZE ){
00679           (*func)(arg,spaces,etSPACESIZE);
00680           nspace -= etSPACESIZE;
00681         }
00682         if( nspace>0 ) (*func)(arg,spaces,nspace);
00683       }
00684     }
00685     if( zExtra ){
00686       sqliteFree(zExtra);
00687     }
00688   }/* End for loop over the format string */
00689   return errorflag ? -1 : count;
00690 } /* End of function */
00691 
00692 
00693 /* This structure is used to store state information about the
00694 ** write to memory that is currently in progress.
00695 */
00696 struct sgMprintf {
00697   char *zBase;     /* A base allocation */
00698   char *zText;     /* The string collected so far */
00699   int  nChar;      /* Length of the string so far */
00700   int  nTotal;     /* Output size if unconstrained */
00701   int  nAlloc;     /* Amount of space allocated in zText */
00702   void *(*xRealloc)(void*,int);  /* Function used to realloc memory */
00703 };
00704 
00705 /* 
00706 ** This function implements the callback from vxprintf. 
00707 **
00708 ** This routine add nNewChar characters of text in zNewText to
00709 ** the sgMprintf structure pointed to by "arg".
00710 */
00711 static void mout(void *arg, const char *zNewText, int nNewChar){
00712   struct sgMprintf *pM = (struct sgMprintf*)arg;
00713   pM->nTotal += nNewChar;
00714   if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
00715     if( pM->xRealloc==0 ){
00716       nNewChar =  pM->nAlloc - pM->nChar - 1;
00717     }else{
00718       pM->nAlloc = pM->nChar + nNewChar*2 + 1;
00719       if( pM->zText==pM->zBase ){
00720         pM->zText = pM->xRealloc(0, pM->nAlloc);
00721         if( pM->zText && pM->nChar ){
00722           memcpy(pM->zText, pM->zBase, pM->nChar);
00723         }
00724       }else{
00725         char *zNew;
00726         zNew = pM->xRealloc(pM->zText, pM->nAlloc);
00727         if( zNew ){
00728           pM->zText = zNew;
00729         }
00730       }
00731     }
00732   }
00733   if( pM->zText ){
00734     if( nNewChar>0 ){
00735       memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
00736       pM->nChar += nNewChar;
00737     }
00738     pM->zText[pM->nChar] = 0;
00739   }
00740 }
00741 
00742 /*
00743 ** This routine is a wrapper around xprintf() that invokes mout() as
00744 ** the consumer.  
00745 */
00746 static char *base_vprintf(
00747   void *(*xRealloc)(void*,int),   /* Routine to realloc memory. May be NULL */
00748   int useInternal,                /* Use internal %-conversions if true */
00749   char *zInitBuf,                 /* Initially write here, before mallocing */
00750   int nInitBuf,                   /* Size of zInitBuf[] */
00751   const char *zFormat,            /* format string */
00752   va_list ap                      /* arguments */
00753 ){
00754   struct sgMprintf sM;
00755   sM.zBase = sM.zText = zInitBuf;
00756   sM.nChar = sM.nTotal = 0;
00757   sM.nAlloc = nInitBuf;
00758   sM.xRealloc = xRealloc;
00759   vxprintf(mout, &sM, useInternal, zFormat, ap);
00760   if( xRealloc ){
00761     if( sM.zText==sM.zBase ){
00762       sM.zText = xRealloc(0, sM.nChar+1);
00763       if( sM.zText ){
00764         memcpy(sM.zText, sM.zBase, sM.nChar+1);
00765       }
00766     }else if( sM.nAlloc>sM.nChar+10 ){
00767       char *zNew = xRealloc(sM.zText, sM.nChar+1);
00768       if( zNew ){
00769         sM.zText = zNew;
00770       }
00771     }
00772   }
00773   return sM.zText;
00774 }
00775 
00776 /*
00777 ** Realloc that is a real function, not a macro.
00778 */
00779 static void *printf_realloc(void *old, int size){
00780   return sqliteRealloc(old,size);
00781 }
00782 
00783 /*
00784 ** Print into memory obtained from sqliteMalloc().  Use the internal
00785 ** %-conversion extensions.
00786 */
00787 char *sqlite3VMPrintf(const char *zFormat, va_list ap){
00788   char zBase[SQLITE_PRINT_BUF_SIZE];
00789   return base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
00790 }
00791 
00792 /*
00793 ** Print into memory obtained from sqliteMalloc().  Use the internal
00794 ** %-conversion extensions.
00795 */
00796 char *sqlite3MPrintf(const char *zFormat, ...){
00797   va_list ap;
00798   char *z;
00799   char zBase[SQLITE_PRINT_BUF_SIZE];
00800   va_start(ap, zFormat);
00801   z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
00802   va_end(ap);
00803   return z;
00804 }
00805 
00806 /*
00807 ** Print into memory obtained from malloc().  Do not use the internal
00808 ** %-conversion extensions.  This routine is for use by external users.
00809 */
00810 char *sqlite3_mprintf(const char *zFormat, ...){
00811   va_list ap;
00812   char *z;
00813   char zBuf[200];
00814 
00815   va_start(ap,zFormat);
00816   z = base_vprintf((void*(*)(void*,int))realloc, 0, 
00817                    zBuf, sizeof(zBuf), zFormat, ap);
00818   va_end(ap);
00819   return z;
00820 }
00821 
00822 /* This is the varargs version of sqlite3_mprintf.  
00823 */
00824 char *sqlite3_vmprintf(const char *zFormat, va_list ap){
00825   char zBuf[200];
00826   return base_vprintf((void*(*)(void*,int))realloc, 0,
00827                       zBuf, sizeof(zBuf), zFormat, ap);
00828 }
00829 
00830 /*
00831 ** sqlite3_snprintf() works like snprintf() except that it ignores the
00832 ** current locale settings.  This is important for SQLite because we
00833 ** are not able to use a "," as the decimal point in place of "." as
00834 ** specified by some locales.
00835 */
00836 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
00837   char *z;
00838   va_list ap;
00839 
00840   va_start(ap,zFormat);
00841   z = base_vprintf(0, 0, zBuf, n, zFormat, ap);
00842   va_end(ap);
00843   return z;
00844 }
00845 
00846 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
00847 /*
00848 ** A version of printf() that understands %lld.  Used for debugging.
00849 ** The printf() built into some versions of windows does not understand %lld
00850 ** and segfaults if you give it a long long int.
00851 */
00852 void sqlite3DebugPrintf(const char *zFormat, ...){
00853   extern int getpid(void);
00854   va_list ap;
00855   char zBuf[500];
00856   va_start(ap, zFormat);
00857   base_vprintf(0, 0, zBuf, sizeof(zBuf), zFormat, ap);
00858   va_end(ap);
00859   fprintf(stdout,"%d: %s", getpid(), zBuf);
00860   fflush(stdout);
00861 }
00862 #endif