Main Page | Directories | File List

printf.c

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 #define etERROR      10 /* Used to indicate no such conversion type */
00069 /* The rest are extensions, not normally found in printf() */
00070 #define etCHARLIT    11 /* Literal characters.  %' */
00071 #define etSQLESCAPE  12 /* Strings with '\'' doubled.  %q */
00072 #define etSQLESCAPE2 13 /* Strings with '\'' doubled and enclosed in '',
00073                           NULL pointers replaced by SQL NULL.  %Q */
00074 #define etTOKEN      14 /* a pointer to a Token structure */
00075 #define etSRCLIST    15 /* a pointer to a SrcList */
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   char *charset;           /* The character set for conversion */
00093   char *prefix;            /* Prefix on non-zero values in alt format */
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 
00102 
00103 /*
00104 ** The following table is searched linearly, so it is good to put the
00105 ** most frequently used conversion types first.
00106 */
00107 static et_info fmtinfo[] = {
00108   {  'd', 10, 1, etRADIX,      "0123456789",       0    },
00109   {  's',  0, 0, etSTRING,     0,                  0    },
00110   {  'z',  0, 2, etDYNSTRING,  0,                  0    },
00111   {  'q',  0, 0, etSQLESCAPE,  0,                  0    },
00112   {  'Q',  0, 0, etSQLESCAPE2, 0,                  0    },
00113   {  'c',  0, 0, etCHARX,      0,                  0    },
00114   {  'o',  8, 0, etRADIX,      "01234567",         "0"  },
00115   {  'u', 10, 0, etRADIX,      "0123456789",       0    },
00116   {  'x', 16, 0, etRADIX,      "0123456789abcdef", "x0" },
00117   {  'X', 16, 0, etRADIX,      "0123456789ABCDEF", "X0" },
00118   {  'f',  0, 1, etFLOAT,      0,                  0    },
00119   {  'e',  0, 1, etEXP,        "e",                0    },
00120   {  'E',  0, 1, etEXP,        "E",                0    },
00121   {  'g',  0, 1, etGENERIC,    "e",                0    },
00122   {  'G',  0, 1, etGENERIC,    "E",                0    },
00123   {  'i', 10, 1, etRADIX,      "0123456789",       0    },
00124   {  'n',  0, 0, etSIZE,       0,                  0    },
00125   {  '%',  0, 0, etPERCENT,    0,                  0    },
00126   {  'p', 10, 0, etRADIX,      "0123456789",       0    },
00127   {  'T',  0, 2, etTOKEN,      0,                  0    },
00128   {  'S',  0, 2, etSRCLIST,    0,                  0    },
00129 };
00130 #define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
00131 
00132 /*
00133 ** If NOFLOATINGPOINT is defined, then none of the floating point
00134 ** conversions will work.
00135 */
00136 #ifndef etNOFLOATINGPOINT
00137 /*
00138 ** "*val" is a double such that 0.1 <= *val < 10.0
00139 ** Return the ascii code for the leading digit of *val, then
00140 ** multiply "*val" by 10.0 to renormalize.
00141 **
00142 ** Example:
00143 **     input:     *val = 3.14159
00144 **     output:    *val = 1.4159    function return = '3'
00145 **
00146 ** The counter *cnt is incremented each time.  After counter exceeds
00147 ** 16 (the number of significant digits in a 64-bit float) '0' is
00148 ** always returned.
00149 */
00150 static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
00151   int digit;
00152   LONGDOUBLE_TYPE d;
00153   if( (*cnt)++ >= 16 ) return '0';
00154   digit = (int)*val;
00155   d = digit;
00156   digit += '0';
00157   *val = (*val - d)*10.0;
00158   return digit;
00159 }
00160 #endif
00161 
00162 #define etBUFSIZE 1000  /* Size of the output buffer */
00163 
00164 /*
00165 ** The root program.  All variations call this core.
00166 **
00167 ** INPUTS:
00168 **   func   This is a pointer to a function taking three arguments
00169 **            1. A pointer to anything.  Same as the "arg" parameter.
00170 **            2. A pointer to the list of characters to be output
00171 **               (Note, this list is NOT null terminated.)
00172 **            3. An integer number of characters to be output.
00173 **               (Note: This number might be zero.)
00174 **
00175 **   arg    This is the pointer to anything which will be passed as the
00176 **          first argument to "func".  Use it for whatever you like.
00177 **
00178 **   fmt    This is the format string, as in the usual print.
00179 **
00180 **   ap     This is a pointer to a list of arguments.  Same as in
00181 **          vfprint.
00182 **
00183 ** OUTPUTS:
00184 **          The return value is the total number of characters sent to
00185 **          the function "func".  Returns -1 on a error.
00186 **
00187 ** Note that the order in which automatic variables are declared below
00188 ** seems to make a big difference in determining how fast this beast
00189 ** will run.
00190 */
00191 static int vxprintf(
00192   void (*func)(void*,const char*,int),     /* Consumer of text */
00193   void *arg,                         /* First argument to the consumer */
00194   int useExtended,                   /* Allow extended %-conversions */
00195   const char *fmt,                   /* Format string */
00196   va_list ap                         /* arguments */
00197 ){
00198   int c;                     /* Next character in the format string */
00199   char *bufpt;               /* Pointer to the conversion buffer */
00200   int precision;             /* Precision of the current field */
00201   int length;                /* Length of the field */
00202   int idx;                   /* A general purpose loop counter */
00203   int count;                 /* Total number of characters output */
00204   int width;                 /* Width of the current field */
00205   etByte flag_leftjustify;   /* True if "-" flag is present */
00206   etByte flag_plussign;      /* True if "+" flag is present */
00207   etByte flag_blanksign;     /* True if " " flag is present */
00208   etByte flag_alternateform; /* True if "#" flag is present */
00209   etByte flag_zeropad;       /* True if field width constant starts with zero */
00210   etByte flag_long;          /* True if "l" flag is present */
00211   unsigned long longvalue;   /* Value for integer types */
00212   LONGDOUBLE_TYPE realvalue; /* Value for real types */
00213   et_info *infop;            /* Pointer to the appropriate info structure */
00214   char buf[etBUFSIZE];       /* Conversion buffer */
00215   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
00216   etByte errorflag = 0;      /* True if an error is encountered */
00217   etByte xtype;              /* Conversion paradigm */
00218   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
00219   static char spaces[] = "                                                  ";
00220 #define etSPACESIZE (sizeof(spaces)-1)
00221 #ifndef etNOFLOATINGPOINT
00222   int  exp;                  /* exponent of real numbers */
00223   double rounder;            /* Used for rounding floating point values */
00224   etByte flag_dp;            /* True if decimal point should be shown */
00225   etByte flag_rtz;           /* True if trailing zeros should be removed */
00226   etByte flag_exp;           /* True to force display of the exponent */
00227   int nsd;                   /* Number of significant digits returned */
00228 #endif
00229 
00230   func(arg,"",0);
00231   count = length = 0;
00232   bufpt = 0;
00233   for(; (c=(*fmt))!=0; ++fmt){
00234     if( c!='%' ){
00235       int amt;
00236       bufpt = (char *)fmt;
00237       amt = 1;
00238       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
00239       (*func)(arg,bufpt,amt);
00240       count += amt;
00241       if( c==0 ) break;
00242     }
00243     if( (c=(*++fmt))==0 ){
00244       errorflag = 1;
00245       (*func)(arg,"%",1);
00246       count++;
00247       break;
00248     }
00249     /* Find out what flags are present */
00250     flag_leftjustify = flag_plussign = flag_blanksign = 
00251      flag_alternateform = flag_zeropad = 0;
00252     do{
00253       switch( c ){
00254         case '-':   flag_leftjustify = 1;     c = 0;   break;
00255         case '+':   flag_plussign = 1;        c = 0;   break;
00256         case ' ':   flag_blanksign = 1;       c = 0;   break;
00257         case '#':   flag_alternateform = 1;   c = 0;   break;
00258         case '0':   flag_zeropad = 1;         c = 0;   break;
00259         default:                                       break;
00260       }
00261     }while( c==0 && (c=(*++fmt))!=0 );
00262     /* Get the field width */
00263     width = 0;
00264     if( c=='*' ){
00265       width = va_arg(ap,int);
00266       if( width<0 ){
00267         flag_leftjustify = 1;
00268         width = -width;
00269       }
00270       c = *++fmt;
00271     }else{
00272       while( c>='0' && c<='9' ){
00273         width = width*10 + c - '0';
00274         c = *++fmt;
00275       }
00276     }
00277     if( width > etBUFSIZE-10 ){
00278       width = etBUFSIZE-10;
00279     }
00280     /* Get the precision */
00281     if( c=='.' ){
00282       precision = 0;
00283       c = *++fmt;
00284       if( c=='*' ){
00285         precision = va_arg(ap,int);
00286         if( precision<0 ) precision = -precision;
00287         c = *++fmt;
00288       }else{
00289         while( c>='0' && c<='9' ){
00290           precision = precision*10 + c - '0';
00291           c = *++fmt;
00292         }
00293       }
00294       /* Limit the precision to prevent overflowing buf[] during conversion */
00295       if( precision>etBUFSIZE-40 ) precision = etBUFSIZE-40;
00296     }else{
00297       precision = -1;
00298     }
00299     /* Get the conversion type modifier */
00300     if( c=='l' ){
00301       flag_long = 1;
00302       c = *++fmt;
00303     }else{
00304       flag_long = 0;
00305     }
00306     /* Fetch the info entry for the field */
00307     infop = 0;
00308     xtype = etERROR;
00309     for(idx=0; idx<etNINFO; idx++){
00310       if( c==fmtinfo[idx].fmttype ){
00311         infop = &fmtinfo[idx];
00312         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
00313           xtype = infop->type;
00314         }
00315         break;
00316       }
00317     }
00318     zExtra = 0;
00319 
00320     /*
00321     ** At this point, variables are initialized as follows:
00322     **
00323     **   flag_alternateform          TRUE if a '#' is present.
00324     **   flag_plussign               TRUE if a '+' is present.
00325     **   flag_leftjustify            TRUE if a '-' is present or if the
00326     **                               field width was negative.
00327     **   flag_zeropad                TRUE if the width began with 0.
00328     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
00329     **                               the conversion character.
00330     **   flag_blanksign              TRUE if a ' ' is present.
00331     **   width                       The specified field width.  This is
00332     **                               always non-negative.  Zero is the default.
00333     **   precision                   The specified precision.  The default
00334     **                               is -1.
00335     **   xtype                       The class of the conversion.
00336     **   infop                       Pointer to the appropriate info struct.
00337     */
00338     switch( xtype ){
00339       case etRADIX:
00340         if( flag_long )  longvalue = va_arg(ap,long);
00341         else             longvalue = va_arg(ap,int);
00342 #if 1
00343         /* For the format %#x, the value zero is printed "0" not "0x0".
00344         ** I think this is stupid. */
00345         if( longvalue==0 ) flag_alternateform = 0;
00346 #else
00347         /* More sensible: turn off the prefix for octal (to prevent "00"),
00348         ** but leave the prefix for hex. */
00349         if( longvalue==0 && infop->base==8 ) flag_alternateform = 0;
00350 #endif
00351         if( infop->flags & FLAG_SIGNED ){
00352           if( *(long*)&longvalue<0 ){
00353             longvalue = -*(long*)&longvalue;
00354             prefix = '-';
00355           }else if( flag_plussign )  prefix = '+';
00356           else if( flag_blanksign )  prefix = ' ';
00357           else                       prefix = 0;
00358         }else                        prefix = 0;
00359         if( flag_zeropad && precision<width-(prefix!=0) ){
00360           precision = width-(prefix!=0);
00361         }
00362         bufpt = &buf[etBUFSIZE-1];
00363         {
00364           register char *cset;      /* Use registers for speed */
00365           register int base;
00366           cset = infop->charset;
00367           base = infop->base;
00368           do{                                           /* Convert to ascii */
00369             *(--bufpt) = cset[longvalue%base];
00370             longvalue = longvalue/base;
00371           }while( longvalue>0 );
00372         }
00373         length = &buf[etBUFSIZE-1]-bufpt;
00374         for(idx=precision-length; idx>0; idx--){
00375           *(--bufpt) = '0';                             /* Zero pad */
00376         }
00377         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
00378         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
00379           char *pre, x;
00380           pre = infop->prefix;
00381           if( *bufpt!=pre[0] ){
00382             for(pre=infop->prefix; (x=(*pre))!=0; pre++) *(--bufpt) = x;
00383           }
00384         }
00385         length = &buf[etBUFSIZE-1]-bufpt;
00386         break;
00387       case etFLOAT:
00388       case etEXP:
00389       case etGENERIC:
00390         realvalue = va_arg(ap,double);
00391 #ifndef etNOFLOATINGPOINT
00392         if( precision<0 ) precision = 6;         /* Set default precision */
00393         if( precision>etBUFSIZE-10 ) precision = etBUFSIZE-10;
00394         if( realvalue<0.0 ){
00395           realvalue = -realvalue;
00396           prefix = '-';
00397         }else{
00398           if( flag_plussign )          prefix = '+';
00399           else if( flag_blanksign )    prefix = ' ';
00400           else                         prefix = 0;
00401         }
00402         if( infop->type==etGENERIC && precision>0 ) precision--;
00403         rounder = 0.0;
00404 #if 0
00405         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
00406         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
00407 #else
00408         /* It makes more sense to use 0.5 */
00409         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1);
00410 #endif
00411         if( infop->type==etFLOAT ) realvalue += rounder;
00412         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
00413         exp = 0;
00414         if( realvalue>0.0 ){
00415           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
00416           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
00417           while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
00418           while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
00419           if( exp>350 || exp<-350 ){
00420             bufpt = "NaN";
00421             length = 3;
00422             break;
00423           }
00424         }
00425         bufpt = buf;
00426         /*
00427         ** If the field type is etGENERIC, then convert to either etEXP
00428         ** or etFLOAT, as appropriate.
00429         */
00430         flag_exp = xtype==etEXP;
00431         if( xtype!=etFLOAT ){
00432           realvalue += rounder;
00433           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
00434         }
00435         if( xtype==etGENERIC ){
00436           flag_rtz = !flag_alternateform;
00437           if( exp<-4 || exp>precision ){
00438             xtype = etEXP;
00439           }else{
00440             precision = precision - exp;
00441             xtype = etFLOAT;
00442           }
00443         }else{
00444           flag_rtz = 0;
00445         }
00446         /*
00447         ** The "exp+precision" test causes output to be of type etEXP if
00448         ** the precision is too large to fit in buf[].
00449         */
00450         nsd = 0;
00451         if( xtype==etFLOAT && exp+precision<etBUFSIZE-30 ){
00452           flag_dp = (precision>0 || flag_alternateform);
00453           if( prefix ) *(bufpt++) = prefix;         /* Sign */
00454           if( exp<0 )  *(bufpt++) = '0';            /* Digits before "." */
00455           else for(; exp>=0; exp--) *(bufpt++) = et_getdigit(&realvalue,&nsd);
00456           if( flag_dp ) *(bufpt++) = '.';           /* The decimal point */
00457           for(exp++; exp<0 && precision>0; precision--, exp++){
00458             *(bufpt++) = '0';
00459           }
00460           while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
00461           *(bufpt--) = 0;                           /* Null terminate */
00462           if( flag_rtz && flag_dp ){     /* Remove trailing zeros and "." */
00463             while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
00464             if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
00465           }
00466           bufpt++;                            /* point to next free slot */
00467         }else{    /* etEXP or etGENERIC */
00468           flag_dp = (precision>0 || flag_alternateform);
00469           if( prefix ) *(bufpt++) = prefix;   /* Sign */
00470           *(bufpt++) = et_getdigit(&realvalue,&nsd);  /* First digit */
00471           if( flag_dp ) *(bufpt++) = '.';     /* Decimal point */
00472           while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
00473           bufpt--;                            /* point to last digit */
00474           if( flag_rtz && flag_dp ){          /* Remove tail zeros */
00475             while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
00476             if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
00477           }
00478           bufpt++;                            /* point to next free slot */
00479           if( exp || flag_exp ){
00480             *(bufpt++) = infop->charset[0];
00481             if( exp<0 ){ *(bufpt++) = '-'; exp = -exp; } /* sign of exp */
00482             else       { *(bufpt++) = '+'; }
00483             if( exp>=100 ){
00484               *(bufpt++) = (exp/100)+'0';                /* 100's digit */
00485               exp %= 100;
00486             }
00487             *(bufpt++) = exp/10+'0';                     /* 10's digit */
00488             *(bufpt++) = exp%10+'0';                     /* 1's digit */
00489           }
00490         }
00491         /* The converted number is in buf[] and zero terminated. Output it.
00492         ** Note that the number is in the usual order, not reversed as with
00493         ** integer conversions. */
00494         length = bufpt-buf;
00495         bufpt = buf;
00496 
00497         /* Special case:  Add leading zeros if the flag_zeropad flag is
00498         ** set and we are not left justified */
00499         if( flag_zeropad && !flag_leftjustify && length < width){
00500           int i;
00501           int nPad = width - length;
00502           for(i=width; i>=nPad; i--){
00503             bufpt[i] = bufpt[i-nPad];
00504           }
00505           i = prefix!=0;
00506           while( nPad-- ) bufpt[i++] = '0';
00507           length = width;
00508         }
00509 #endif
00510         break;
00511       case etSIZE:
00512         *(va_arg(ap,int*)) = count;
00513         length = width = 0;
00514         break;
00515       case etPERCENT:
00516         buf[0] = '%';
00517         bufpt = buf;
00518         length = 1;
00519         break;
00520       case etCHARLIT:
00521       case etCHARX:
00522         c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
00523         if( precision>=0 ){
00524           for(idx=1; idx<precision; idx++) buf[idx] = c;
00525           length = precision;
00526         }else{
00527           length =1;
00528         }
00529         bufpt = buf;
00530         break;
00531       case etSTRING:
00532       case etDYNSTRING:
00533         bufpt = va_arg(ap,char*);
00534         if( bufpt==0 ){
00535           bufpt = "";
00536         }else if( xtype==etDYNSTRING ){
00537           zExtra = bufpt;
00538         }
00539         length = strlen(bufpt);
00540         if( precision>=0 && precision<length ) length = precision;
00541         break;
00542       case etSQLESCAPE:
00543       case etSQLESCAPE2:
00544         {
00545           int i, j, n, c, isnull;
00546           char *arg = va_arg(ap,char*);
00547           isnull = arg==0;
00548           if( isnull ) arg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
00549           for(i=n=0; (c=arg[i])!=0; i++){
00550             if( c=='\'' )  n++;
00551           }
00552           n += i + 1 + ((!isnull && xtype==etSQLESCAPE2) ? 2 : 0);
00553           if( n>etBUFSIZE ){
00554             bufpt = zExtra = sqliteMalloc( n );
00555             if( bufpt==0 ) return -1;
00556           }else{
00557             bufpt = buf;
00558           }
00559           j = 0;
00560           if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
00561           for(i=0; (c=arg[i])!=0; i++){
00562             bufpt[j++] = c;
00563             if( c=='\'' ) bufpt[j++] = c;
00564           }
00565           if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
00566           bufpt[j] = 0;
00567           length = j;
00568           if( precision>=0 && precision<length ) length = precision;
00569         }
00570         break;
00571       case etTOKEN: {
00572         Token *pToken = va_arg(ap, Token*);
00573         (*func)(arg, pToken->z, pToken->n);
00574         length = width = 0;
00575         break;
00576       }
00577       case etSRCLIST: {
00578         SrcList *pSrc = va_arg(ap, SrcList*);
00579         int k = va_arg(ap, int);
00580         struct SrcList_item *pItem = &pSrc->a[k];
00581         assert( k>=0 && k<pSrc->nSrc );
00582         if( pItem->zDatabase && pItem->zDatabase[0] ){
00583           (*func)(arg, pItem->zDatabase, strlen(pItem->zDatabase));
00584           (*func)(arg, ".", 1);
00585         }
00586         (*func)(arg, pItem->zName, strlen(pItem->zName));
00587         length = width = 0;
00588         break;
00589       }
00590       case etERROR:
00591         buf[0] = '%';
00592         buf[1] = c;
00593         errorflag = 0;
00594         idx = 1+(c!=0);
00595         (*func)(arg,"%",idx);
00596         count += idx;
00597         if( c==0 ) fmt--;
00598         break;
00599     }/* End switch over the format type */
00600     /*
00601     ** The text of the conversion is pointed to by "bufpt" and is
00602     ** "length" characters long.  The field width is "width".  Do
00603     ** the output.
00604     */
00605     if( !flag_leftjustify ){
00606       register int nspace;
00607       nspace = width-length;
00608       if( nspace>0 ){
00609         count += nspace;
00610         while( nspace>=etSPACESIZE ){
00611           (*func)(arg,spaces,etSPACESIZE);
00612           nspace -= etSPACESIZE;
00613         }
00614         if( nspace>0 ) (*func)(arg,spaces,nspace);
00615       }
00616     }
00617     if( length>0 ){
00618       (*func)(arg,bufpt,length);
00619       count += length;
00620     }
00621     if( flag_leftjustify ){
00622       register int nspace;
00623       nspace = width-length;
00624       if( nspace>0 ){
00625         count += nspace;
00626         while( nspace>=etSPACESIZE ){
00627           (*func)(arg,spaces,etSPACESIZE);
00628           nspace -= etSPACESIZE;
00629         }
00630         if( nspace>0 ) (*func)(arg,spaces,nspace);
00631       }
00632     }
00633     if( zExtra ){
00634       sqliteFree(zExtra);
00635     }
00636   }/* End for loop over the format string */
00637   return errorflag ? -1 : count;
00638 } /* End of function */
00639 
00640 
00641 /* This structure is used to store state information about the
00642 ** write to memory that is currently in progress.
00643 */
00644 struct sgMprintf {
00645   char *zBase;     /* A base allocation */
00646   char *zText;     /* The string collected so far */
00647   int  nChar;      /* Length of the string so far */
00648   int  nTotal;     /* Output size if unconstrained */
00649   int  nAlloc;     /* Amount of space allocated in zText */
00650   void *(*xRealloc)(void*,int);  /* Function used to realloc memory */
00651 };
00652 
00653 /* 
00654 ** This function implements the callback from vxprintf. 
00655 **
00656 ** This routine add nNewChar characters of text in zNewText to
00657 ** the sgMprintf structure pointed to by "arg".
00658 */
00659 static void mout(void *arg, const char *zNewText, int nNewChar){
00660   struct sgMprintf *pM = (struct sgMprintf*)arg;
00661   pM->nTotal += nNewChar;
00662   if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
00663     if( pM->xRealloc==0 ){
00664       nNewChar =  pM->nAlloc - pM->nChar - 1;
00665     }else{
00666       pM->nAlloc = pM->nChar + nNewChar*2 + 1;
00667       if( pM->zText==pM->zBase ){
00668         pM->zText = pM->xRealloc(0, pM->nAlloc);
00669         if( pM->zText && pM->nChar ){
00670           memcpy(pM->zText, pM->zBase, pM->nChar);
00671         }
00672       }else{
00673         pM->zText = pM->xRealloc(pM->zText, pM->nAlloc);
00674       }
00675     }
00676   }
00677   if( pM->zText ){
00678     if( nNewChar>0 ){
00679       memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
00680       pM->nChar += nNewChar;
00681     }
00682     pM->zText[pM->nChar] = 0;
00683   }
00684 }
00685 
00686 /*
00687 ** This routine is a wrapper around xprintf() that invokes mout() as
00688 ** the consumer.  
00689 */
00690 static char *base_vprintf(
00691   void *(*xRealloc)(void*,int),   /* Routine to realloc memory. May be NULL */
00692   int useInternal,                /* Use internal %-conversions if true */
00693   char *zInitBuf,                 /* Initially write here, before mallocing */
00694   int nInitBuf,                   /* Size of zInitBuf[] */
00695   const char *zFormat,            /* format string */
00696   va_list ap                      /* arguments */
00697 ){
00698   struct sgMprintf sM;
00699   sM.zBase = sM.zText = zInitBuf;
00700   sM.nChar = sM.nTotal = 0;
00701   sM.nAlloc = nInitBuf;
00702   sM.xRealloc = xRealloc;
00703   vxprintf(mout, &sM, useInternal, zFormat, ap);
00704   if( xRealloc ){
00705     if( sM.zText==sM.zBase ){
00706       sM.zText = xRealloc(0, sM.nChar+1);
00707       memcpy(sM.zText, sM.zBase, sM.nChar+1);
00708     }else if( sM.nAlloc>sM.nChar+10 ){
00709       sM.zText = xRealloc(sM.zText, sM.nChar+1);
00710     }
00711   }
00712   return sM.zText;
00713 }
00714 
00715 /*
00716 ** Realloc that is a real function, not a macro.
00717 */
00718 static void *printf_realloc(void *old, int size){
00719   return sqliteRealloc(old,size);
00720 }
00721 
00722 /*
00723 ** Print into memory obtained from sqliteMalloc().  Use the internal
00724 ** %-conversion extensions.
00725 */
00726 char *sqliteVMPrintf(const char *zFormat, va_list ap){
00727   char zBase[1000];
00728   return base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
00729 }
00730 
00731 /*
00732 ** Print into memory obtained from sqliteMalloc().  Use the internal
00733 ** %-conversion extensions.
00734 */
00735 char *sqliteMPrintf(const char *zFormat, ...){
00736   va_list ap;
00737   char *z;
00738   char zBase[1000];
00739   va_start(ap, zFormat);
00740   z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
00741   va_end(ap);
00742   return z;
00743 }
00744 
00745 /*
00746 ** Print into memory obtained from malloc().  Do not use the internal
00747 ** %-conversion extensions.  This routine is for use by external users.
00748 */
00749 char *sqlite_mprintf(const char *zFormat, ...){
00750   va_list ap;
00751   char *z;
00752   char zBuf[200];
00753 
00754   va_start(ap,zFormat);
00755   z = base_vprintf((void*(*)(void*,int))realloc, 0, 
00756                    zBuf, sizeof(zBuf), zFormat, ap);
00757   va_end(ap);
00758   return z;
00759 }
00760 
00761 /* This is the varargs version of sqlite_mprintf.  
00762 */
00763 char *sqlite_vmprintf(const char *zFormat, va_list ap){
00764   char zBuf[200];
00765   return base_vprintf((void*(*)(void*,int))realloc, 0,
00766                       zBuf, sizeof(zBuf), zFormat, ap);
00767 }
00768 
00769 /*
00770 ** sqlite_snprintf() works like snprintf() except that it ignores the
00771 ** current locale settings.  This is important for SQLite because we
00772 ** are not able to use a "," as the decimal point in place of "." as
00773 ** specified by some locales.
00774 */
00775 char *sqlite_snprintf(int n, char *zBuf, const char *zFormat, ...){
00776   char *z;
00777   va_list ap;
00778 
00779   va_start(ap,zFormat);
00780   z = base_vprintf(0, 0, zBuf, n, zFormat, ap);
00781   va_end(ap);
00782   return z;
00783 }
00784 
00785 /*
00786 ** The following four routines implement the varargs versions of the
00787 ** sqlite_exec() and sqlite_get_table() interfaces.  See the sqlite.h
00788 ** header files for a more detailed description of how these interfaces
00789 ** work.
00790 **
00791 ** These routines are all just simple wrappers.
00792 */
00793 int sqlite_exec_printf(
00794   sqlite *db,                   /* An open database */
00795   const char *sqlFormat,        /* printf-style format string for the SQL */
00796   sqlite_callback xCallback,    /* Callback function */
00797   void *pArg,                   /* 1st argument to callback function */
00798   char **errmsg,                /* Error msg written here */
00799   ...                           /* Arguments to the format string. */
00800 ){
00801   va_list ap;
00802   int rc;
00803 
00804   va_start(ap, errmsg);
00805   rc = sqlite_exec_vprintf(db, sqlFormat, xCallback, pArg, errmsg, ap);
00806   va_end(ap);
00807   return rc;
00808 }
00809 int sqlite_exec_vprintf(
00810   sqlite *db,                   /* An open database */
00811   const char *sqlFormat,        /* printf-style format string for the SQL */
00812   sqlite_callback xCallback,    /* Callback function */
00813   void *pArg,                   /* 1st argument to callback function */
00814   char **errmsg,                /* Error msg written here */
00815   va_list ap                    /* Arguments to the format string. */
00816 ){
00817   char *zSql;
00818   int rc;
00819 
00820   zSql = sqlite_vmprintf(sqlFormat, ap);
00821   rc = sqlite_exec(db, zSql, xCallback, pArg, errmsg);
00822   free(zSql);
00823   return rc;
00824 }
00825 int sqlite_get_table_printf(
00826   sqlite *db,            /* An open database */
00827   const char *sqlFormat, /* printf-style format string for the SQL */
00828   char ***resultp,       /* Result written to a char *[]  that this points to */
00829   int *nrow,             /* Number of result rows written here */
00830   int *ncol,             /* Number of result columns written here */
00831   char **errmsg,         /* Error msg written here */
00832   ...                    /* Arguments to the format string */
00833 ){
00834   va_list ap;
00835   int rc;
00836 
00837   va_start(ap, errmsg);
00838   rc = sqlite_get_table_vprintf(db, sqlFormat, resultp, nrow, ncol, errmsg, ap);
00839   va_end(ap);
00840   return rc;
00841 }
00842 int sqlite_get_table_vprintf(
00843   sqlite *db,            /* An open database */
00844   const char *sqlFormat, /* printf-style format string for the SQL */
00845   char ***resultp,       /* Result written to a char *[]  that this points to */
00846   int *nrow,             /* Number of result rows written here */
00847   int *ncolumn,          /* Number of result columns written here */
00848   char **errmsg,         /* Error msg written here */
00849   va_list ap             /* Arguments to the format string */
00850 ){
00851   char *zSql;
00852   int rc;
00853 
00854   zSql = sqlite_vmprintf(sqlFormat, ap);
00855   rc = sqlite_get_table(db, zSql, resultp, nrow, ncolumn, errmsg);
00856   free(zSql);
00857   return rc;
00858 }

Generated on Sun Dec 25 12:29:52 2005 for sqlite 2.8.17 by  doxygen 1.4.2