Main Page | Directories | File List

util.c

00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** Utility functions used throughout sqlite.
00013 **
00014 ** This file contains functions for allocating memory, comparing
00015 ** strings, and stuff like that.
00016 **
00017 ** $Id: util.c,v 1.74.2.2 2005/06/06 15:07:03 drh Exp $
00018 */
00019 #include "sqliteInt.h"
00020 #include <stdarg.h>
00021 #include <ctype.h>
00022 
00023 /*
00024 ** If malloc() ever fails, this global variable gets set to 1.
00025 ** This causes the library to abort and never again function.
00026 */
00027 int sqlite_malloc_failed = 0;
00028 
00029 /*
00030 ** If MEMORY_DEBUG is defined, then use versions of malloc() and
00031 ** free() that track memory usage and check for buffer overruns.
00032 */
00033 #ifdef MEMORY_DEBUG
00034 
00035 /*
00036 ** For keeping track of the number of mallocs and frees.   This
00037 ** is used to check for memory leaks.
00038 */
00039 int sqlite_nMalloc;         /* Number of sqliteMalloc() calls */
00040 int sqlite_nFree;           /* Number of sqliteFree() calls */
00041 int sqlite_iMallocFail;     /* Fail sqliteMalloc() after this many calls */
00042 #if MEMORY_DEBUG>1
00043 static int memcnt = 0;
00044 #endif
00045 
00046 /*
00047 ** Number of 32-bit guard words
00048 */
00049 #define N_GUARD 1
00050 
00051 /*
00052 ** Allocate new memory and set it to zero.  Return NULL if
00053 ** no memory is available.
00054 */
00055 void *sqliteMalloc_(int n, int bZero, char *zFile, int line){
00056   void *p;
00057   int *pi;
00058   int i, k;
00059   if( sqlite_iMallocFail>=0 ){
00060     sqlite_iMallocFail--;
00061     if( sqlite_iMallocFail==0 ){
00062       sqlite_malloc_failed++;
00063 #if MEMORY_DEBUG>1
00064       fprintf(stderr,"**** failed to allocate %d bytes at %s:%d\n",
00065               n, zFile,line);
00066 #endif
00067       sqlite_iMallocFail--;
00068       return 0;
00069     }
00070   }
00071   if( n==0 ) return 0;
00072   k = (n+sizeof(int)-1)/sizeof(int);
00073   pi = malloc( (N_GUARD*2+1+k)*sizeof(int));
00074   if( pi==0 ){
00075     sqlite_malloc_failed++;
00076     return 0;
00077   }
00078   sqlite_nMalloc++;
00079   for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
00080   pi[N_GUARD] = n;
00081   for(i=0; i<N_GUARD; i++) pi[k+1+N_GUARD+i] = 0xdead3344;
00082   p = &pi[N_GUARD+1];
00083   memset(p, bZero==0, n);
00084 #if MEMORY_DEBUG>1
00085   fprintf(stderr,"%06d malloc %d bytes at 0x%x from %s:%d\n",
00086       ++memcnt, n, (int)p, zFile,line);
00087 #endif
00088   return p;
00089 }
00090 
00091 /*
00092 ** Check to see if the given pointer was obtained from sqliteMalloc()
00093 ** and is able to hold at least N bytes.  Raise an exception if this
00094 ** is not the case.
00095 **
00096 ** This routine is used for testing purposes only.
00097 */
00098 void sqliteCheckMemory(void *p, int N){
00099   int *pi = p;
00100   int n, i, k;
00101   pi -= N_GUARD+1;
00102   for(i=0; i<N_GUARD; i++){
00103     assert( pi[i]==0xdead1122 );
00104   }
00105   n = pi[N_GUARD];
00106   assert( N>=0 && N<n );
00107   k = (n+sizeof(int)-1)/sizeof(int);
00108   for(i=0; i<N_GUARD; i++){
00109     assert( pi[k+N_GUARD+1+i]==0xdead3344 );
00110   }
00111 }
00112 
00113 /*
00114 ** Free memory previously obtained from sqliteMalloc()
00115 */
00116 void sqliteFree_(void *p, char *zFile, int line){
00117   if( p ){
00118     int *pi, i, k, n;
00119     pi = p;
00120     pi -= N_GUARD+1;
00121     sqlite_nFree++;
00122     for(i=0; i<N_GUARD; i++){
00123       if( pi[i]!=0xdead1122 ){
00124         fprintf(stderr,"Low-end memory corruption at 0x%x\n", (int)p);
00125         return;
00126       }
00127     }
00128     n = pi[N_GUARD];
00129     k = (n+sizeof(int)-1)/sizeof(int);
00130     for(i=0; i<N_GUARD; i++){
00131       if( pi[k+N_GUARD+1+i]!=0xdead3344 ){
00132         fprintf(stderr,"High-end memory corruption at 0x%x\n", (int)p);
00133         return;
00134       }
00135     }
00136     memset(pi, 0xff, (k+N_GUARD*2+1)*sizeof(int));
00137 #if MEMORY_DEBUG>1
00138     fprintf(stderr,"%06d free %d bytes at 0x%x from %s:%d\n",
00139          ++memcnt, n, (int)p, zFile,line);
00140 #endif
00141     free(pi);
00142   }
00143 }
00144 
00145 /*
00146 ** Resize a prior allocation.  If p==0, then this routine
00147 ** works just like sqliteMalloc().  If n==0, then this routine
00148 ** works just like sqliteFree().
00149 */
00150 void *sqliteRealloc_(void *oldP, int n, char *zFile, int line){
00151   int *oldPi, *pi, i, k, oldN, oldK;
00152   void *p;
00153   if( oldP==0 ){
00154     return sqliteMalloc_(n,1,zFile,line);
00155   }
00156   if( n==0 ){
00157     sqliteFree_(oldP,zFile,line);
00158     return 0;
00159   }
00160   oldPi = oldP;
00161   oldPi -= N_GUARD+1;
00162   if( oldPi[0]!=0xdead1122 ){
00163     fprintf(stderr,"Low-end memory corruption in realloc at 0x%x\n", (int)oldP);
00164     return 0;
00165   }
00166   oldN = oldPi[N_GUARD];
00167   oldK = (oldN+sizeof(int)-1)/sizeof(int);
00168   for(i=0; i<N_GUARD; i++){
00169     if( oldPi[oldK+N_GUARD+1+i]!=0xdead3344 ){
00170       fprintf(stderr,"High-end memory corruption in realloc at 0x%x\n",
00171               (int)oldP);
00172       return 0;
00173     }
00174   }
00175   k = (n + sizeof(int) - 1)/sizeof(int);
00176   pi = malloc( (k+N_GUARD*2+1)*sizeof(int) );
00177   if( pi==0 ){
00178     sqlite_malloc_failed++;
00179     return 0;
00180   }
00181   for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
00182   pi[N_GUARD] = n;
00183   for(i=0; i<N_GUARD; i++) pi[k+N_GUARD+1+i] = 0xdead3344;
00184   p = &pi[N_GUARD+1];
00185   memcpy(p, oldP, n>oldN ? oldN : n);
00186   if( n>oldN ){
00187     memset(&((char*)p)[oldN], 0, n-oldN);
00188   }
00189   memset(oldPi, 0xab, (oldK+N_GUARD+2)*sizeof(int));
00190   free(oldPi);
00191 #if MEMORY_DEBUG>1
00192   fprintf(stderr,"%06d realloc %d to %d bytes at 0x%x to 0x%x at %s:%d\n",
00193     ++memcnt, oldN, n, (int)oldP, (int)p, zFile, line);
00194 #endif
00195   return p;
00196 }
00197 
00198 /*
00199 ** Make a duplicate of a string into memory obtained from malloc()
00200 ** Free the original string using sqliteFree().
00201 **
00202 ** This routine is called on all strings that are passed outside of
00203 ** the SQLite library.  That way clients can free the string using free()
00204 ** rather than having to call sqliteFree().
00205 */
00206 void sqliteStrRealloc(char **pz){
00207   char *zNew;
00208   if( pz==0 || *pz==0 ) return;
00209   zNew = malloc( strlen(*pz) + 1 );
00210   if( zNew==0 ){
00211     sqlite_malloc_failed++;
00212     sqliteFree(*pz);
00213     *pz = 0;
00214   }
00215   strcpy(zNew, *pz);
00216   sqliteFree(*pz);
00217   *pz = zNew;
00218 }
00219 
00220 /*
00221 ** Make a copy of a string in memory obtained from sqliteMalloc()
00222 */
00223 char *sqliteStrDup_(const char *z, char *zFile, int line){
00224   char *zNew;
00225   if( z==0 ) return 0;
00226   zNew = sqliteMalloc_(strlen(z)+1, 0, zFile, line);
00227   if( zNew ) strcpy(zNew, z);
00228   return zNew;
00229 }
00230 char *sqliteStrNDup_(const char *z, int n, char *zFile, int line){
00231   char *zNew;
00232   if( z==0 ) return 0;
00233   zNew = sqliteMalloc_(n+1, 0, zFile, line);
00234   if( zNew ){
00235     memcpy(zNew, z, n);
00236     zNew[n] = 0;
00237   }
00238   return zNew;
00239 }
00240 #endif /* MEMORY_DEBUG */
00241 
00242 /*
00243 ** The following versions of malloc() and free() are for use in a
00244 ** normal build.
00245 */
00246 #if !defined(MEMORY_DEBUG)
00247 
00248 /*
00249 ** Allocate new memory and set it to zero.  Return NULL if
00250 ** no memory is available.  See also sqliteMallocRaw().
00251 */
00252 void *sqliteMalloc(int n){
00253   void *p;
00254   if( (p = malloc(n))==0 ){
00255     if( n>0 ) sqlite_malloc_failed++;
00256   }else{
00257     memset(p, 0, n);
00258   }
00259   return p;
00260 }
00261 
00262 /*
00263 ** Allocate new memory but do not set it to zero.  Return NULL if
00264 ** no memory is available.  See also sqliteMalloc().
00265 */
00266 void *sqliteMallocRaw(int n){
00267   void *p;
00268   if( (p = malloc(n))==0 ){
00269     if( n>0 ) sqlite_malloc_failed++;
00270   }
00271   return p;
00272 }
00273 
00274 /*
00275 ** Free memory previously obtained from sqliteMalloc()
00276 */
00277 void sqliteFree(void *p){
00278   if( p ){
00279     free(p);
00280   }
00281 }
00282 
00283 /*
00284 ** Resize a prior allocation.  If p==0, then this routine
00285 ** works just like sqliteMalloc().  If n==0, then this routine
00286 ** works just like sqliteFree().
00287 */
00288 void *sqliteRealloc(void *p, int n){
00289   void *p2;
00290   if( p==0 ){
00291     return sqliteMalloc(n);
00292   }
00293   if( n==0 ){
00294     sqliteFree(p);
00295     return 0;
00296   }
00297   p2 = realloc(p, n);
00298   if( p2==0 ){
00299     sqlite_malloc_failed++;
00300   }
00301   return p2;
00302 }
00303 
00304 /*
00305 ** Make a copy of a string in memory obtained from sqliteMalloc()
00306 */
00307 char *sqliteStrDup(const char *z){
00308   char *zNew;
00309   if( z==0 ) return 0;
00310   zNew = sqliteMallocRaw(strlen(z)+1);
00311   if( zNew ) strcpy(zNew, z);
00312   return zNew;
00313 }
00314 char *sqliteStrNDup(const char *z, int n){
00315   char *zNew;
00316   if( z==0 ) return 0;
00317   zNew = sqliteMallocRaw(n+1);
00318   if( zNew ){
00319     memcpy(zNew, z, n);
00320     zNew[n] = 0;
00321   }
00322   return zNew;
00323 }
00324 #endif /* !defined(MEMORY_DEBUG) */
00325 
00326 /*
00327 ** Create a string from the 2nd and subsequent arguments (up to the
00328 ** first NULL argument), store the string in memory obtained from
00329 ** sqliteMalloc() and make the pointer indicated by the 1st argument
00330 ** point to that string.  The 1st argument must either be NULL or 
00331 ** point to memory obtained from sqliteMalloc().
00332 */
00333 void sqliteSetString(char **pz, ...){
00334   va_list ap;
00335   int nByte;
00336   const char *z;
00337   char *zResult;
00338 
00339   if( pz==0 ) return;
00340   nByte = 1;
00341   va_start(ap, pz);
00342   while( (z = va_arg(ap, const char*))!=0 ){
00343     nByte += strlen(z);
00344   }
00345   va_end(ap);
00346   sqliteFree(*pz);
00347   *pz = zResult = sqliteMallocRaw( nByte );
00348   if( zResult==0 ){
00349     return;
00350   }
00351   *zResult = 0;
00352   va_start(ap, pz);
00353   while( (z = va_arg(ap, const char*))!=0 ){
00354     strcpy(zResult, z);
00355     zResult += strlen(zResult);
00356   }
00357   va_end(ap);
00358 #ifdef MEMORY_DEBUG
00359 #if MEMORY_DEBUG>1
00360   fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
00361 #endif
00362 #endif
00363 }
00364 
00365 /*
00366 ** Works like sqliteSetString, but each string is now followed by
00367 ** a length integer which specifies how much of the source string 
00368 ** to copy (in bytes).  -1 means use the whole string.  The 1st 
00369 ** argument must either be NULL or point to memory obtained from 
00370 ** sqliteMalloc().
00371 */
00372 void sqliteSetNString(char **pz, ...){
00373   va_list ap;
00374   int nByte;
00375   const char *z;
00376   char *zResult;
00377   int n;
00378 
00379   if( pz==0 ) return;
00380   nByte = 0;
00381   va_start(ap, pz);
00382   while( (z = va_arg(ap, const char*))!=0 ){
00383     n = va_arg(ap, int);
00384     if( n<=0 ) n = strlen(z);
00385     nByte += n;
00386   }
00387   va_end(ap);
00388   sqliteFree(*pz);
00389   *pz = zResult = sqliteMallocRaw( nByte + 1 );
00390   if( zResult==0 ) return;
00391   va_start(ap, pz);
00392   while( (z = va_arg(ap, const char*))!=0 ){
00393     n = va_arg(ap, int);
00394     if( n<=0 ) n = strlen(z);
00395     strncpy(zResult, z, n);
00396     zResult += n;
00397   }
00398   *zResult = 0;
00399 #ifdef MEMORY_DEBUG
00400 #if MEMORY_DEBUG>1
00401   fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
00402 #endif
00403 #endif
00404   va_end(ap);
00405 }
00406 
00407 /*
00408 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
00409 ** The following formatting characters are allowed:
00410 **
00411 **      %s      Insert a string
00412 **      %z      A string that should be freed after use
00413 **      %d      Insert an integer
00414 **      %T      Insert a token
00415 **      %S      Insert the first element of a SrcList
00416 */
00417 void sqliteErrorMsg(Parse *pParse, const char *zFormat, ...){
00418   va_list ap;
00419   pParse->nErr++;
00420   sqliteFree(pParse->zErrMsg);
00421   va_start(ap, zFormat);
00422   pParse->zErrMsg = sqliteVMPrintf(zFormat, ap);
00423   va_end(ap);
00424 }
00425 
00426 /*
00427 ** Convert an SQL-style quoted string into a normal string by removing
00428 ** the quote characters.  The conversion is done in-place.  If the
00429 ** input does not begin with a quote character, then this routine
00430 ** is a no-op.
00431 **
00432 ** 2002-Feb-14: This routine is extended to remove MS-Access style
00433 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
00434 ** "a-b-c".
00435 */
00436 void sqliteDequote(char *z){
00437   int quote;
00438   int i, j;
00439   if( z==0 ) return;
00440   quote = z[0];
00441   switch( quote ){
00442     case '\'':  break;
00443     case '"':   break;
00444     case '[':   quote = ']';  break;
00445     default:    return;
00446   }
00447   for(i=1, j=0; z[i]; i++){
00448     if( z[i]==quote ){
00449       if( z[i+1]==quote ){
00450         z[j++] = quote;
00451         i++;
00452       }else{
00453         z[j++] = 0;
00454         break;
00455       }
00456     }else{
00457       z[j++] = z[i];
00458     }
00459   }
00460 }
00461 
00462 /* An array to map all upper-case characters into their corresponding
00463 ** lower-case character. 
00464 */
00465 static unsigned char UpperToLower[] = {
00466       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
00467      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
00468      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
00469      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
00470     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
00471     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
00472     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
00473     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
00474     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
00475     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
00476     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
00477     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
00478     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
00479     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
00480     252,253,254,255
00481 };
00482 
00483 /*
00484 ** This function computes a hash on the name of a keyword.
00485 ** Case is not significant.
00486 */
00487 int sqliteHashNoCase(const char *z, int n){
00488   int h = 0;
00489   if( n<=0 ) n = strlen(z);
00490   while( n > 0  ){
00491     h = (h<<3) ^ h ^ UpperToLower[(unsigned char)*z++];
00492     n--;
00493   }
00494   return h & 0x7fffffff;
00495 }
00496 
00497 /*
00498 ** Some systems have stricmp().  Others have strcasecmp().  Because
00499 ** there is no consistency, we will define our own.
00500 */
00501 int sqliteStrICmp(const char *zLeft, const char *zRight){
00502   register unsigned char *a, *b;
00503   a = (unsigned char *)zLeft;
00504   b = (unsigned char *)zRight;
00505   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
00506   return UpperToLower[*a] - UpperToLower[*b];
00507 }
00508 int sqliteStrNICmp(const char *zLeft, const char *zRight, int N){
00509   register unsigned char *a, *b;
00510   a = (unsigned char *)zLeft;
00511   b = (unsigned char *)zRight;
00512   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
00513   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
00514 }
00515 
00516 /*
00517 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
00518 ** string contains any character which is not part of a number.
00519 **
00520 ** Am empty string is considered non-numeric.
00521 */
00522 int sqliteIsNumber(const char *z){
00523   if( *z=='-' || *z=='+' ) z++;
00524   if( !isdigit(*z) ){
00525     return 0;
00526   }
00527   z++;
00528   while( isdigit(*z) ){ z++; }
00529   if( *z=='.' ){
00530     z++;
00531     if( !isdigit(*z) ) return 0;
00532     while( isdigit(*z) ){ z++; }
00533   }
00534   if( *z=='e' || *z=='E' ){
00535     z++;
00536     if( *z=='+' || *z=='-' ) z++;
00537     if( !isdigit(*z) ) return 0;
00538     while( isdigit(*z) ){ z++; }
00539   }
00540   return *z==0;
00541 }
00542 
00543 /*
00544 ** The string z[] is an ascii representation of a real number.
00545 ** Convert this string to a double.
00546 **
00547 ** This routine assumes that z[] really is a valid number.  If it
00548 ** is not, the result is undefined.
00549 **
00550 ** This routine is used instead of the library atof() function because
00551 ** the library atof() might want to use "," as the decimal point instead
00552 ** of "." depending on how locale is set.  But that would cause problems
00553 ** for SQL.  So this routine always uses "." regardless of locale.
00554 */
00555 double sqliteAtoF(const char *z, const char **pzEnd){
00556   int sign = 1;
00557   LONGDOUBLE_TYPE v1 = 0.0;
00558   if( *z=='-' ){
00559     sign = -1;
00560     z++;
00561   }else if( *z=='+' ){
00562     z++;
00563   }
00564   while( isdigit(*z) ){
00565     v1 = v1*10.0 + (*z - '0');
00566     z++;
00567   }
00568   if( *z=='.' ){
00569     LONGDOUBLE_TYPE divisor = 1.0;
00570     z++;
00571     while( isdigit(*z) ){
00572       v1 = v1*10.0 + (*z - '0');
00573       divisor *= 10.0;
00574       z++;
00575     }
00576     v1 /= divisor;
00577   }
00578   if( *z=='e' || *z=='E' ){
00579     int esign = 1;
00580     int eval = 0;
00581     LONGDOUBLE_TYPE scale = 1.0;
00582     z++;
00583     if( *z=='-' ){
00584       esign = -1;
00585       z++;
00586     }else if( *z=='+' ){
00587       z++;
00588     }
00589     while( isdigit(*z) ){
00590       eval = eval*10 + *z - '0';
00591       z++;
00592     }
00593     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
00594     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
00595     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
00596     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
00597     if( esign<0 ){
00598       v1 /= scale;
00599     }else{
00600       v1 *= scale;
00601     }
00602   }
00603   if( pzEnd ) *pzEnd = z;
00604   return sign<0 ? -v1 : v1;
00605 }
00606 
00607 /*
00608 ** The string zNum represents an integer.  There might be some other
00609 ** information following the integer too, but that part is ignored.
00610 ** If the integer that the prefix of zNum represents will fit in a
00611 ** 32-bit signed integer, return TRUE.  Otherwise return FALSE.
00612 **
00613 ** This routine returns FALSE for the string -2147483648 even that
00614 ** that number will, in theory fit in a 32-bit integer.  But positive
00615 ** 2147483648 will not fit in 32 bits.  So it seems safer to return
00616 ** false.
00617 */
00618 int sqliteFitsIn32Bits(const char *zNum){
00619   int i, c;
00620   if( *zNum=='-' || *zNum=='+' ) zNum++;
00621   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
00622   return i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0);
00623 }
00624 
00625 /* This comparison routine is what we use for comparison operations
00626 ** between numeric values in an SQL expression.  "Numeric" is a little
00627 ** bit misleading here.  What we mean is that the strings have a
00628 ** type of "numeric" from the point of view of SQL.  The strings
00629 ** do not necessarily contain numbers.  They could contain text.
00630 **
00631 ** If the input strings both look like actual numbers then they
00632 ** compare in numerical order.  Numerical strings are always less 
00633 ** than non-numeric strings so if one input string looks like a
00634 ** number and the other does not, then the one that looks like
00635 ** a number is the smaller.  Non-numeric strings compare in 
00636 ** lexigraphical order (the same order as strcmp()).
00637 */
00638 int sqliteCompare(const char *atext, const char *btext){
00639   int result;
00640   int isNumA, isNumB;
00641   if( atext==0 ){
00642     return -1;
00643   }else if( btext==0 ){
00644     return 1;
00645   }
00646   isNumA = sqliteIsNumber(atext);
00647   isNumB = sqliteIsNumber(btext);
00648   if( isNumA ){
00649     if( !isNumB ){
00650       result = -1;
00651     }else{
00652       double rA, rB;
00653       rA = sqliteAtoF(atext, 0);
00654       rB = sqliteAtoF(btext, 0);
00655       if( rA<rB ){
00656         result = -1;
00657       }else if( rA>rB ){
00658         result = +1;
00659       }else{
00660         result = 0;
00661       }
00662     }
00663   }else if( isNumB ){
00664     result = +1;
00665   }else {
00666     result = strcmp(atext, btext);
00667   }
00668   return result; 
00669 }
00670 
00671 /*
00672 ** This routine is used for sorting.  Each key is a list of one or more
00673 ** null-terminated elements.  The list is terminated by two nulls in
00674 ** a row.  For example, the following text is a key with three elements
00675 **
00676 **            Aone\000Dtwo\000Athree\000\000
00677 **
00678 ** All elements begin with one of the characters "+-AD" and end with "\000"
00679 ** with zero or more text elements in between.  Except, NULL elements
00680 ** consist of the special two-character sequence "N\000".
00681 **
00682 ** Both arguments will have the same number of elements.  This routine
00683 ** returns negative, zero, or positive if the first argument is less
00684 ** than, equal to, or greater than the first.  (Result is a-b).
00685 **
00686 ** Each element begins with one of the characters "+", "-", "A", "D".
00687 ** This character determines the sort order and collating sequence:
00688 **
00689 **     +      Sort numerically in ascending order
00690 **     -      Sort numerically in descending order
00691 **     A      Sort as strings in ascending order
00692 **     D      Sort as strings in descending order.
00693 **
00694 ** For the "+" and "-" sorting, pure numeric strings (strings for which the
00695 ** isNum() function above returns TRUE) always compare less than strings
00696 ** that are not pure numerics.  Non-numeric strings compare in memcmp()
00697 ** order.  This is the same sort order as the sqliteCompare() function
00698 ** above generates.
00699 **
00700 ** The last point is a change from version 2.6.3 to version 2.7.0.  In
00701 ** version 2.6.3 and earlier, substrings of digits compare in numerical 
00702 ** and case was used only to break a tie.
00703 **
00704 ** Elements that begin with 'A' or 'D' compare in memcmp() order regardless
00705 ** of whether or not they look like a number.
00706 **
00707 ** Note that the sort order imposed by the rules above is the same
00708 ** from the ordering defined by the "<", "<=", ">", and ">=" operators
00709 ** of expressions and for indices.  This was not the case for version
00710 ** 2.6.3 and earlier.
00711 */
00712 int sqliteSortCompare(const char *a, const char *b){
00713   int res = 0;
00714   int isNumA, isNumB;
00715   int dir = 0;
00716 
00717   while( res==0 && *a && *b ){
00718     if( a[0]=='N' || b[0]=='N' ){
00719       if( a[0]==b[0] ){
00720         a += 2;
00721         b += 2;
00722         continue;
00723       }
00724       if( a[0]=='N' ){
00725         dir = b[0];
00726         res = -1;
00727       }else{
00728         dir = a[0];
00729         res = +1;
00730       }
00731       break;
00732     }
00733     assert( a[0]==b[0] );
00734     if( (dir=a[0])=='A' || a[0]=='D' ){
00735       res = strcmp(&a[1],&b[1]);
00736       if( res ) break;
00737     }else{
00738       isNumA = sqliteIsNumber(&a[1]);
00739       isNumB = sqliteIsNumber(&b[1]);
00740       if( isNumA ){
00741         double rA, rB;
00742         if( !isNumB ){
00743           res = -1;
00744           break;
00745         }
00746         rA = sqliteAtoF(&a[1], 0);
00747         rB = sqliteAtoF(&b[1], 0);
00748         if( rA<rB ){
00749           res = -1;
00750           break;
00751         }
00752         if( rA>rB ){
00753           res = +1;
00754           break;
00755         }
00756       }else if( isNumB ){
00757         res = +1;
00758         break;
00759       }else{
00760         res = strcmp(&a[1],&b[1]);
00761         if( res ) break;
00762       }
00763     }
00764     a += strlen(&a[1]) + 2;
00765     b += strlen(&b[1]) + 2;
00766   }
00767   if( dir=='-' || dir=='D' ) res = -res;
00768   return res;
00769 }
00770 
00771 /*
00772 ** Some powers of 64.  These constants are needed in the
00773 ** sqliteRealToSortable() routine below.
00774 */
00775 #define _64e3  (64.0 * 64.0 * 64.0)
00776 #define _64e4  (64.0 * 64.0 * 64.0 * 64.0)
00777 #define _64e15 (_64e3 * _64e4 * _64e4 * _64e4)
00778 #define _64e16 (_64e4 * _64e4 * _64e4 * _64e4)
00779 #define _64e63 (_64e15 * _64e16 * _64e16 * _64e16)
00780 #define _64e64 (_64e16 * _64e16 * _64e16 * _64e16)
00781 
00782 /*
00783 ** The following procedure converts a double-precision floating point
00784 ** number into a string.  The resulting string has the property that
00785 ** two such strings comparied using strcmp() or memcmp() will give the
00786 ** same results as a numeric comparison of the original floating point
00787 ** numbers.
00788 **
00789 ** This routine is used to generate database keys from floating point
00790 ** numbers such that the keys sort in the same order as the original
00791 ** floating point numbers even though the keys are compared using
00792 ** memcmp().
00793 **
00794 ** The calling function should have allocated at least 14 characters
00795 ** of space for the buffer z[].
00796 */
00797 void sqliteRealToSortable(double r, char *z){
00798   int neg;
00799   int exp;
00800   int cnt = 0;
00801 
00802   /* This array maps integers between 0 and 63 into base-64 digits.
00803   ** The digits must be chosen such at their ASCII codes are increasing.
00804   ** This means we can not use the traditional base-64 digit set. */
00805   static const char zDigit[] = 
00806      "0123456789"
00807      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
00808      "abcdefghijklmnopqrstuvwxyz"
00809      "|~";
00810   if( r<0.0 ){
00811     neg = 1;
00812     r = -r;
00813     *z++ = '-';
00814   } else {
00815     neg = 0;
00816     *z++ = '0';
00817   }
00818   exp = 0;
00819 
00820   if( r==0.0 ){
00821     exp = -1024;
00822   }else if( r<(0.5/64.0) ){
00823     while( r < 0.5/_64e64 && exp > -961  ){ r *= _64e64;  exp -= 64; }
00824     while( r < 0.5/_64e16 && exp > -1009 ){ r *= _64e16;  exp -= 16; }
00825     while( r < 0.5/_64e4  && exp > -1021 ){ r *= _64e4;   exp -= 4; }
00826     while( r < 0.5/64.0   && exp > -1024 ){ r *= 64.0;    exp -= 1; }
00827   }else if( r>=0.5 ){
00828     while( r >= 0.5*_64e63 && exp < 960  ){ r *= 1.0/_64e64; exp += 64; }
00829     while( r >= 0.5*_64e15 && exp < 1008 ){ r *= 1.0/_64e16; exp += 16; }
00830     while( r >= 0.5*_64e3  && exp < 1020 ){ r *= 1.0/_64e4;  exp += 4; }
00831     while( r >= 0.5        && exp < 1023 ){ r *= 1.0/64.0;   exp += 1; }
00832   }
00833   if( neg ){
00834     exp = -exp;
00835     r = -r;
00836   }
00837   exp += 1024;
00838   r += 0.5;
00839   if( exp<0 ) return;
00840   if( exp>=2048 || r>=1.0 ){
00841     strcpy(z, "~~~~~~~~~~~~");
00842     return;
00843   }
00844   *z++ = zDigit[(exp>>6)&0x3f];
00845   *z++ = zDigit[exp & 0x3f];
00846   while( r>0.0 && cnt<10 ){
00847     int digit;
00848     r *= 64.0;
00849     digit = (int)r;
00850     assert( digit>=0 && digit<64 );
00851     *z++ = zDigit[digit & 0x3f];
00852     r -= digit;
00853     cnt++;
00854   }
00855   *z = 0;
00856 }
00857 
00858 #ifdef SQLITE_UTF8
00859 /*
00860 ** X is a pointer to the first byte of a UTF-8 character.  Increment
00861 ** X so that it points to the next character.  This only works right
00862 ** if X points to a well-formed UTF-8 string.
00863 */
00864 #define sqliteNextChar(X)  while( (0xc0&*++(X))==0x80 ){}
00865 #define sqliteCharVal(X)   sqlite_utf8_to_int(X)
00866 
00867 #else /* !defined(SQLITE_UTF8) */
00868 /*
00869 ** For iso8859 encoding, the next character is just the next byte.
00870 */
00871 #define sqliteNextChar(X)  (++(X));
00872 #define sqliteCharVal(X)   ((int)*(X))
00873 
00874 #endif /* defined(SQLITE_UTF8) */
00875 
00876 
00877 #ifdef SQLITE_UTF8
00878 /*
00879 ** Convert the UTF-8 character to which z points into a 31-bit
00880 ** UCS character.  This only works right if z points to a well-formed
00881 ** UTF-8 string.
00882 */
00883 static int sqlite_utf8_to_int(const unsigned char *z){
00884   int c;
00885   static const int initVal[] = {
00886       0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,
00887      15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25,  26,  27,  28,  29,
00888      30,  31,  32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,
00889      45,  46,  47,  48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,
00890      60,  61,  62,  63,  64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,
00891      75,  76,  77,  78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,
00892      90,  91,  92,  93,  94,  95,  96,  97,  98,  99, 100, 101, 102, 103, 104,
00893     105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
00894     120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
00895     135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
00896     150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
00897     165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
00898     180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,   0,   1,   2,
00899       3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,  15,  16,  17,
00900      18,  19,  20,  21,  22,  23,  24,  25,  26,  27,  28,  29,  30,  31,   0,
00901       1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,  15,
00902       0,   1,   2,   3,   4,   5,   6,   7,   0,   1,   2,   3,   0,   1, 254,
00903     255,
00904   };
00905   c = initVal[*(z++)];
00906   while( (0xc0&*z)==0x80 ){
00907     c = (c<<6) | (0x3f&*(z++));
00908   }
00909   return c;
00910 }
00911 #endif
00912 
00913 /*
00914 ** Compare two UTF-8 strings for equality where the first string can
00915 ** potentially be a "glob" expression.  Return true (1) if they
00916 ** are the same and false (0) if they are different.
00917 **
00918 ** Globbing rules:
00919 **
00920 **      '*'       Matches any sequence of zero or more characters.
00921 **
00922 **      '?'       Matches exactly one character.
00923 **
00924 **     [...]      Matches one character from the enclosed list of
00925 **                characters.
00926 **
00927 **     [^...]     Matches one character not in the enclosed list.
00928 **
00929 ** With the [...] and [^...] matching, a ']' character can be included
00930 ** in the list by making it the first character after '[' or '^'.  A
00931 ** range of characters can be specified using '-'.  Example:
00932 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
00933 ** it the last character in the list.
00934 **
00935 ** This routine is usually quick, but can be N**2 in the worst case.
00936 **
00937 ** Hints: to match '*' or '?', put them in "[]".  Like this:
00938 **
00939 **         abc[*]xyz        Matches "abc*xyz" only
00940 */
00941 int 
00942 sqliteGlobCompare(const unsigned char *zPattern, const unsigned char *zString){
00943   register int c;
00944   int invert;
00945   int seen;
00946   int c2;
00947 
00948   while( (c = *zPattern)!=0 ){
00949     switch( c ){
00950       case '*':
00951         while( (c=zPattern[1]) == '*' || c == '?' ){
00952           if( c=='?' ){
00953             if( *zString==0 ) return 0;
00954             sqliteNextChar(zString);
00955           }
00956           zPattern++;
00957         }
00958         if( c==0 ) return 1;
00959         if( c=='[' ){
00960           while( *zString && sqliteGlobCompare(&zPattern[1],zString)==0 ){
00961             sqliteNextChar(zString);
00962           }
00963           return *zString!=0;
00964         }else{
00965           while( (c2 = *zString)!=0 ){
00966             while( c2 != 0 && c2 != c ){ c2 = *++zString; }
00967             if( c2==0 ) return 0;
00968             if( sqliteGlobCompare(&zPattern[1],zString) ) return 1;
00969             sqliteNextChar(zString);
00970           }
00971           return 0;
00972         }
00973       case '?': {
00974         if( *zString==0 ) return 0;
00975         sqliteNextChar(zString);
00976         zPattern++;
00977         break;
00978       }
00979       case '[': {
00980         int prior_c = 0;
00981         seen = 0;
00982         invert = 0;
00983         c = sqliteCharVal(zString);
00984         if( c==0 ) return 0;
00985         c2 = *++zPattern;
00986         if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
00987         if( c2==']' ){
00988           if( c==']' ) seen = 1;
00989           c2 = *++zPattern;
00990         }
00991         while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
00992           if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
00993             zPattern++;
00994             c2 = sqliteCharVal(zPattern);
00995             if( c>=prior_c && c<=c2 ) seen = 1;
00996             prior_c = 0;
00997           }else if( c==c2 ){
00998             seen = 1;
00999             prior_c = c2;
01000           }else{
01001             prior_c = c2;
01002           }
01003           sqliteNextChar(zPattern);
01004         }
01005         if( c2==0 || (seen ^ invert)==0 ) return 0;
01006         sqliteNextChar(zString);
01007         zPattern++;
01008         break;
01009       }
01010       default: {
01011         if( c != *zString ) return 0;
01012         zPattern++;
01013         zString++;
01014         break;
01015       }
01016     }
01017   }
01018   return *zString==0;
01019 }
01020 
01021 /*
01022 ** Compare two UTF-8 strings for equality using the "LIKE" operator of
01023 ** SQL.  The '%' character matches any sequence of 0 or more
01024 ** characters and '_' matches any single character.  Case is
01025 ** not significant.
01026 **
01027 ** This routine is just an adaptation of the sqliteGlobCompare()
01028 ** routine above.
01029 */
01030 int 
01031 sqliteLikeCompare(const unsigned char *zPattern, const unsigned char *zString){
01032   register int c;
01033   int c2;
01034 
01035   while( (c = UpperToLower[*zPattern])!=0 ){
01036     switch( c ){
01037       case '%': {
01038         while( (c=zPattern[1]) == '%' || c == '_' ){
01039           if( c=='_' ){
01040             if( *zString==0 ) return 0;
01041             sqliteNextChar(zString);
01042           }
01043           zPattern++;
01044         }
01045         if( c==0 ) return 1;
01046         c = UpperToLower[c];
01047         while( (c2=UpperToLower[*zString])!=0 ){
01048           while( c2 != 0 && c2 != c ){ c2 = UpperToLower[*++zString]; }
01049           if( c2==0 ) return 0;
01050           if( sqliteLikeCompare(&zPattern[1],zString) ) return 1;
01051           sqliteNextChar(zString);
01052         }
01053         return 0;
01054       }
01055       case '_': {
01056         if( *zString==0 ) return 0;
01057         sqliteNextChar(zString);
01058         zPattern++;
01059         break;
01060       }
01061       default: {
01062         if( c != UpperToLower[*zString] ) return 0;
01063         zPattern++;
01064         zString++;
01065         break;
01066       }
01067     }
01068   }
01069   return *zString==0;
01070 }
01071 
01072 /*
01073 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
01074 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
01075 ** when this routine is called.
01076 **
01077 ** This routine is a attempt to detect if two threads use the
01078 ** same sqlite* pointer at the same time.  There is a race 
01079 ** condition so it is possible that the error is not detected.
01080 ** But usually the problem will be seen.  The result will be an
01081 ** error which can be used to debug the application that is
01082 ** using SQLite incorrectly.
01083 **
01084 ** Ticket #202:  If db->magic is not a valid open value, take care not
01085 ** to modify the db structure at all.  It could be that db is a stale
01086 ** pointer.  In other words, it could be that there has been a prior
01087 ** call to sqlite_close(db) and db has been deallocated.  And we do
01088 ** not want to write into deallocated memory.
01089 */
01090 int sqliteSafetyOn(sqlite *db){
01091   if( db->magic==SQLITE_MAGIC_OPEN ){
01092     db->magic = SQLITE_MAGIC_BUSY;
01093     return 0;
01094   }else if( db->magic==SQLITE_MAGIC_BUSY || db->magic==SQLITE_MAGIC_ERROR
01095              || db->want_to_close ){
01096     db->magic = SQLITE_MAGIC_ERROR;
01097     db->flags |= SQLITE_Interrupt;
01098   }
01099   return 1;
01100 }
01101 
01102 /*
01103 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
01104 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
01105 ** when this routine is called.
01106 */
01107 int sqliteSafetyOff(sqlite *db){
01108   if( db->magic==SQLITE_MAGIC_BUSY ){
01109     db->magic = SQLITE_MAGIC_OPEN;
01110     return 0;
01111   }else if( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ERROR
01112              || db->want_to_close ){
01113     db->magic = SQLITE_MAGIC_ERROR;
01114     db->flags |= SQLITE_Interrupt;
01115   }
01116   return 1;
01117 }
01118 
01119 /*
01120 ** Check to make sure we are not currently executing an sqlite_exec().
01121 ** If we are currently in an sqlite_exec(), return true and set
01122 ** sqlite.magic to SQLITE_MAGIC_ERROR.  This will cause a complete
01123 ** shutdown of the database.
01124 **
01125 ** This routine is used to try to detect when API routines are called
01126 ** at the wrong time or in the wrong sequence.
01127 */
01128 int sqliteSafetyCheck(sqlite *db){
01129   if( db->pVdbe!=0 ){
01130     db->magic = SQLITE_MAGIC_ERROR;
01131     return 1;
01132   }
01133   return 0;
01134 }

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