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

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:56 2011 by Doxygen 1.6.1