xref: /sqlite-3.40.0/src/util.c (revision 173b418e)
175897234Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
375897234Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
675897234Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
1075897234Sdrh **
1175897234Sdrh *************************************************************************
1275897234Sdrh ** Utility functions used throughout sqlite.
1375897234Sdrh **
1475897234Sdrh ** This file contains functions for allocating memory, comparing
1575897234Sdrh ** strings, and stuff like that.
1675897234Sdrh **
1775897234Sdrh */
1875897234Sdrh #include "sqliteInt.h"
1975897234Sdrh #include <stdarg.h>
20ef9f719dSdrh #ifndef SQLITE_OMIT_FLOATING_POINT
21cf9b1752Sdrh #include <math.h>
22ef9f719dSdrh #endif
2375897234Sdrh 
2475897234Sdrh /*
25ce059e52Sdrh ** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
26ce059e52Sdrh ** or to bypass normal error detection during testing in order to let
27ce059e52Sdrh ** execute proceed futher downstream.
28c007f61bSdrh **
29ce059e52Sdrh ** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0).  The
30ce059e52Sdrh ** sqlite3FaultSim() function only returns non-zero during testing.
31c007f61bSdrh **
32ce059e52Sdrh ** During testing, if the test harness has set a fault-sim callback using
33ce059e52Sdrh ** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
34ce059e52Sdrh ** each call to sqlite3FaultSim() is relayed to that application-supplied
35ce059e52Sdrh ** callback and the integer return value form the application-supplied
36ce059e52Sdrh ** callback is returned by sqlite3FaultSim().
37ce059e52Sdrh **
38ce059e52Sdrh ** The integer argument to sqlite3FaultSim() is a code to identify which
39ce059e52Sdrh ** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
40ce059e52Sdrh ** should have a unique code.  To prevent legacy testing applications from
41ce059e52Sdrh ** breaking, the codes should not be changed or reused.
42c007f61bSdrh */
43d12602a9Sdrh #ifndef SQLITE_UNTESTABLE
sqlite3FaultSim(int iTest)44c007f61bSdrh int sqlite3FaultSim(int iTest){
45c007f61bSdrh   int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
46c007f61bSdrh   return xCallback ? xCallback(iTest) : SQLITE_OK;
47c007f61bSdrh }
48c007f61bSdrh #endif
49c007f61bSdrh 
5085c8f291Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
5147c3b3e0Sdrh /*
52791ea93fSshane ** Return true if the floating point value is Not a Number (NaN).
53e534c7b9Sdrh **
54e534c7b9Sdrh ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
55e534c7b9Sdrh ** Otherwise, we have our own implementation that works on most systems.
560de3ae95Sdrh */
sqlite3IsNaN(double x)570de3ae95Sdrh int sqlite3IsNaN(double x){
58e534c7b9Sdrh   int rc;   /* The value return */
59e534c7b9Sdrh #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
6005921223Sdrh   u64 y;
6105921223Sdrh   memcpy(&y,&x,sizeof(y));
62e534c7b9Sdrh   rc = IsNaN(y);
63e534c7b9Sdrh #else
64e534c7b9Sdrh   rc = isnan(x);
65e534c7b9Sdrh #endif /* HAVE_ISNAN */
66e534c7b9Sdrh   testcase( rc );
67e534c7b9Sdrh   return rc;
680de3ae95Sdrh }
6985c8f291Sdrh #endif /* SQLITE_OMIT_FLOATING_POINT */
700de3ae95Sdrh 
710de3ae95Sdrh /*
724f21c4afSdrh ** Compute a string length that is limited to what can be stored in
734f21c4afSdrh ** lower 30 bits of a 32-bit signed integer.
74dee0e404Sdrh **
75dee0e404Sdrh ** The value returned will never be negative.  Nor will it ever be greater
76dee0e404Sdrh ** than the actual length of the string.  For very long strings (greater
77dee0e404Sdrh ** than 1GiB) the value returned might be less than the true string length.
784f21c4afSdrh */
sqlite3Strlen30(const char * z)794f21c4afSdrh int sqlite3Strlen30(const char *z){
8085119c32Sdrh   if( z==0 ) return 0;
811116bf13Sdrh   return 0x3fffffff & (int)strlen(z);
824f21c4afSdrh }
834f21c4afSdrh 
844f21c4afSdrh /*
85d7564865Sdrh ** Return the declared type of a column.  Or return zDflt if the column
86d7564865Sdrh ** has no declared type.
87d7564865Sdrh **
88d7564865Sdrh ** The column type is an extra string stored after the zero-terminator on
89d7564865Sdrh ** the column name if and only if the COLFLAG_HASTYPE flag is set.
9094eaafa9Sdrh */
sqlite3ColumnType(Column * pCol,char * zDflt)91d7564865Sdrh char *sqlite3ColumnType(Column *pCol, char *zDflt){
9277441fafSdrh   if( pCol->colFlags & COLFLAG_HASTYPE ){
93cf9d36d1Sdrh     return pCol->zCnName + strlen(pCol->zCnName) + 1;
94b70f2eabSdrh   }else if( pCol->eCType ){
95b70f2eabSdrh     assert( pCol->eCType<=SQLITE_N_STDTYPE );
96b70f2eabSdrh     return (char*)sqlite3StdType[pCol->eCType-1];
9777441fafSdrh   }else{
9877441fafSdrh     return zDflt;
9977441fafSdrh   }
10094eaafa9Sdrh }
10194eaafa9Sdrh 
10294eaafa9Sdrh /*
10380fbee09Sdrh ** Helper function for sqlite3Error() - called rarely.  Broken out into
10480fbee09Sdrh ** a separate routine to avoid unnecessary register saves on entry to
10580fbee09Sdrh ** sqlite3Error().
10613f40da3Sdrh */
sqlite3ErrorFinish(sqlite3 * db,int err_code)1078d2f41ccSdrh static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
1088d2f41ccSdrh   if( db->pErr ) sqlite3ValueSetNull(db->pErr);
1098d2f41ccSdrh   sqlite3SystemError(db, err_code);
1108d2f41ccSdrh }
11180fbee09Sdrh 
11280fbee09Sdrh /*
11380fbee09Sdrh ** Set the current error code to err_code and clear any prior error message.
11480fbee09Sdrh ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
11580fbee09Sdrh ** that would be appropriate.
11680fbee09Sdrh */
sqlite3Error(sqlite3 * db,int err_code)11713f40da3Sdrh void sqlite3Error(sqlite3 *db, int err_code){
11813f40da3Sdrh   assert( db!=0 );
11913f40da3Sdrh   db->errCode = err_code;
120f62641e9Sdrh   if( err_code || db->pErr ){
121f62641e9Sdrh     sqlite3ErrorFinish(db, err_code);
122f62641e9Sdrh   }else{
123f62641e9Sdrh     db->errByteOffset = -1;
124f62641e9Sdrh   }
12513f40da3Sdrh }
12613f40da3Sdrh 
12713f40da3Sdrh /*
12888efc796Sdrh ** The equivalent of sqlite3Error(db, SQLITE_OK).  Clear the error state
12988efc796Sdrh ** and error message.
13088efc796Sdrh */
sqlite3ErrorClear(sqlite3 * db)13188efc796Sdrh void sqlite3ErrorClear(sqlite3 *db){
13288efc796Sdrh   assert( db!=0 );
13388efc796Sdrh   db->errCode = SQLITE_OK;
134f62641e9Sdrh   db->errByteOffset = -1;
13588efc796Sdrh   if( db->pErr ) sqlite3ValueSetNull(db->pErr);
13688efc796Sdrh }
13788efc796Sdrh 
13888efc796Sdrh /*
1391b9f2141Sdrh ** Load the sqlite3.iSysErrno field if that is an appropriate thing
1401b9f2141Sdrh ** to do based on the SQLite error code in rc.
1411b9f2141Sdrh */
sqlite3SystemError(sqlite3 * db,int rc)1421b9f2141Sdrh void sqlite3SystemError(sqlite3 *db, int rc){
1431b9f2141Sdrh   if( rc==SQLITE_IOERR_NOMEM ) return;
1441b9f2141Sdrh   rc &= 0xff;
1451b9f2141Sdrh   if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
1461b9f2141Sdrh     db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
1471b9f2141Sdrh   }
1481b9f2141Sdrh }
1491b9f2141Sdrh 
1501b9f2141Sdrh /*
1516622cce3Sdanielk1977 ** Set the most recent error code and error string for the sqlite
1526622cce3Sdanielk1977 ** handle "db". The error code is set to "err_code".
1536622cce3Sdanielk1977 **
1546622cce3Sdanielk1977 ** If it is not NULL, string zFormat specifies the format of the
155f62641e9Sdrh ** error string.  zFormat and any string tokens that follow it are
156f62641e9Sdrh ** assumed to be encoded in UTF-8.
1576622cce3Sdanielk1977 **
1580bb8f36dSdanielk1977 ** To clear the most recent error for sqlite handle "db", sqlite3Error
1596622cce3Sdanielk1977 ** should be called with err_code set to SQLITE_OK and zFormat set
1606622cce3Sdanielk1977 ** to NULL.
1616622cce3Sdanielk1977 */
sqlite3ErrorWithMsg(sqlite3 * db,int err_code,const char * zFormat,...)16213f40da3Sdrh void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
163a3cc007dSdrh   assert( db!=0 );
1646622cce3Sdanielk1977   db->errCode = err_code;
1658d2f41ccSdrh   sqlite3SystemError(db, err_code);
16613f40da3Sdrh   if( zFormat==0 ){
16713f40da3Sdrh     sqlite3Error(db, err_code);
16813f40da3Sdrh   }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
169bfd6cce5Sdanielk1977     char *z;
1706622cce3Sdanielk1977     va_list ap;
1716622cce3Sdanielk1977     va_start(ap, zFormat);
1721e536953Sdanielk1977     z = sqlite3VMPrintf(db, zFormat, ap);
1736622cce3Sdanielk1977     va_end(ap);
174633e6d57Sdrh     sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
1756622cce3Sdanielk1977   }
1766622cce3Sdanielk1977 }
1776622cce3Sdanielk1977 
1786622cce3Sdanielk1977 /*
179da93d238Sdrh ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
1809e6db7d7Sdanielk1977 **
18113f40da3Sdrh ** This function should be used to report any error that occurs while
1829e6db7d7Sdanielk1977 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
1839e6db7d7Sdanielk1977 ** last thing the sqlite3_prepare() function does is copy the error
1849e6db7d7Sdanielk1977 ** stored by this function into the database handle using sqlite3Error().
18513f40da3Sdrh ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
18613f40da3Sdrh ** during statement execution (sqlite3_step() etc.).
187da93d238Sdrh */
sqlite3ErrorMsg(Parse * pParse,const char * zFormat,...)1884adee20fSdanielk1977 void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
189a7564663Sdrh   char *zMsg;
190da93d238Sdrh   va_list ap;
191633e6d57Sdrh   sqlite3 *db = pParse->db;
192c692df27Sdrh   assert( db!=0 );
193*173b418eSdrh   assert( db->pParse==pParse || db->pParse->pToplevel==pParse );
194f62641e9Sdrh   db->errByteOffset = -2;
195a7564663Sdrh   va_start(ap, zFormat);
196a7564663Sdrh   zMsg = sqlite3VMPrintf(db, zFormat, ap);
197a7564663Sdrh   va_end(ap);
198f62641e9Sdrh   if( db->errByteOffset<-1 ) db->errByteOffset = -1;
199a7564663Sdrh   if( db->suppressErr ){
200a7564663Sdrh     sqlite3DbFree(db, zMsg);
2010c7d3d39Sdrh     if( db->mallocFailed ){
2020c7d3d39Sdrh       pParse->nErr++;
2030c7d3d39Sdrh       pParse->rc = SQLITE_NOMEM;
2040c7d3d39Sdrh     }
205a7564663Sdrh   }else{
206da93d238Sdrh     pParse->nErr++;
207633e6d57Sdrh     sqlite3DbFree(db, pParse->zErrMsg);
208a7564663Sdrh     pParse->zErrMsg = zMsg;
2097e326c09Sdrh     pParse->rc = SQLITE_ERROR;
21046a31cdfSdrh     pParse->pWith = 0;
2117e326c09Sdrh   }
212a073384fSdrh }
213a073384fSdrh 
214a073384fSdrh /*
215c3dcdba3Sdrh ** If database connection db is currently parsing SQL, then transfer
216c3dcdba3Sdrh ** error code errCode to that parser if the parser has not already
217c3dcdba3Sdrh ** encountered some other kind of error.
218c3dcdba3Sdrh */
sqlite3ErrorToParser(sqlite3 * db,int errCode)219c3dcdba3Sdrh int sqlite3ErrorToParser(sqlite3 *db, int errCode){
220c3dcdba3Sdrh   Parse *pParse;
221c3dcdba3Sdrh   if( db==0 || (pParse = db->pParse)==0 ) return errCode;
222c3dcdba3Sdrh   pParse->rc = errCode;
223c3dcdba3Sdrh   pParse->nErr++;
224c3dcdba3Sdrh   return errCode;
225c3dcdba3Sdrh }
226c3dcdba3Sdrh 
227c3dcdba3Sdrh /*
228982cef7eSdrh ** Convert an SQL-style quoted string into a normal string by removing
229982cef7eSdrh ** the quote characters.  The conversion is done in-place.  If the
230982cef7eSdrh ** input does not begin with a quote character, then this routine
231982cef7eSdrh ** is a no-op.
2322f4392ffSdrh **
23324fb627aSdrh ** The input string must be zero-terminated.  A new zero-terminator
23424fb627aSdrh ** is added to the dequoted string.
23524fb627aSdrh **
23624fb627aSdrh ** The return value is -1 if no dequoting occurs or the length of the
23724fb627aSdrh ** dequoted string, exclusive of the zero terminator, if dequoting does
23824fb627aSdrh ** occur.
23924fb627aSdrh **
24051d35b0fSdrh ** 2002-02-14: This routine is extended to remove MS-Access style
24160ec914cSpeter.d.reid ** brackets from around identifiers.  For example:  "[a-b-c]" becomes
2422f4392ffSdrh ** "a-b-c".
243982cef7eSdrh */
sqlite3Dequote(char * z)244244b9d6eSdrh void sqlite3Dequote(char *z){
245aa78bec9Sdrh   char quote;
246982cef7eSdrh   int i, j;
247244b9d6eSdrh   if( z==0 ) return;
248982cef7eSdrh   quote = z[0];
249244b9d6eSdrh   if( !sqlite3Isquote(quote) ) return;
250244b9d6eSdrh   if( quote=='[' ) quote = ']';
2519ccd8659Sdrh   for(i=1, j=0;; i++){
2529ccd8659Sdrh     assert( z[i] );
253982cef7eSdrh     if( z[i]==quote ){
254982cef7eSdrh       if( z[i+1]==quote ){
255982cef7eSdrh         z[j++] = quote;
256982cef7eSdrh         i++;
257982cef7eSdrh       }else{
258982cef7eSdrh         break;
259982cef7eSdrh       }
260982cef7eSdrh     }else{
261982cef7eSdrh       z[j++] = z[i];
262982cef7eSdrh     }
263982cef7eSdrh   }
26424fb627aSdrh   z[j] = 0;
265982cef7eSdrh }
sqlite3DequoteExpr(Expr * p)26651d35b0fSdrh void sqlite3DequoteExpr(Expr *p){
267f9751074Sdrh   assert( !ExprHasProperty(p, EP_IntValue) );
26851d35b0fSdrh   assert( sqlite3Isquote(p->u.zToken[0]) );
26951d35b0fSdrh   p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
27051d35b0fSdrh   sqlite3Dequote(p->u.zToken);
27151d35b0fSdrh }
272982cef7eSdrh 
27340aced5cSdrh /*
27477441fafSdrh ** If the input token p is quoted, try to adjust the token to remove
27577441fafSdrh ** the quotes.  This is not always possible:
27677441fafSdrh **
27777441fafSdrh **     "abc"     ->   abc
27877441fafSdrh **     "ab""cd"  ->   (not possible because of the interior "")
27977441fafSdrh **
28077441fafSdrh ** Remove the quotes if possible.  This is a optimization.  The overall
28177441fafSdrh ** system should still return the correct answer even if this routine
28277441fafSdrh ** is always a no-op.
28377441fafSdrh */
sqlite3DequoteToken(Token * p)28477441fafSdrh void sqlite3DequoteToken(Token *p){
28515482bc3Sdrh   unsigned int i;
28677441fafSdrh   if( p->n<2 ) return;
28777441fafSdrh   if( !sqlite3Isquote(p->z[0]) ) return;
28877441fafSdrh   for(i=1; i<p->n-1; i++){
28977441fafSdrh     if( sqlite3Isquote(p->z[i]) ) return;
29077441fafSdrh   }
29177441fafSdrh   p->n -= 2;
29277441fafSdrh   p->z++;
29377441fafSdrh }
29477441fafSdrh 
29577441fafSdrh /*
29640aced5cSdrh ** Generate a Token object from a string
29740aced5cSdrh */
sqlite3TokenInit(Token * p,char * z)29840aced5cSdrh void sqlite3TokenInit(Token *p, char *z){
29940aced5cSdrh   p->z = z;
30040aced5cSdrh   p->n = sqlite3Strlen30(z);
30140aced5cSdrh }
30240aced5cSdrh 
30340257ffdSdrh /* Convenient short-hand */
3044e5ffc5fSdrh #define UpperToLower sqlite3UpperToLower
30575897234Sdrh 
30675897234Sdrh /*
30775897234Sdrh ** Some systems have stricmp().  Others have strcasecmp().  Because
30875897234Sdrh ** there is no consistency, we will define our own.
3099f129f46Sdrh **
3100299b40fSdrh ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
3110299b40fSdrh ** sqlite3_strnicmp() APIs allow applications and extensions to compare
3120299b40fSdrh ** the contents of two buffers containing UTF-8 strings in a
3130299b40fSdrh ** case-independent fashion, using the same definition of "case
3140299b40fSdrh ** independence" that SQLite uses internally when comparing identifiers.
31575897234Sdrh */
sqlite3_stricmp(const char * zLeft,const char * zRight)3163fa97302Sdrh int sqlite3_stricmp(const char *zLeft, const char *zRight){
3179ca95730Sdrh   if( zLeft==0 ){
3189ca95730Sdrh     return zRight ? -1 : 0;
3199ca95730Sdrh   }else if( zRight==0 ){
3209ca95730Sdrh     return 1;
3219ca95730Sdrh   }
32280738d9cSdrh   return sqlite3StrICmp(zLeft, zRight);
32380738d9cSdrh }
sqlite3StrICmp(const char * zLeft,const char * zRight)32480738d9cSdrh int sqlite3StrICmp(const char *zLeft, const char *zRight){
32580738d9cSdrh   unsigned char *a, *b;
3267e427337Sdrh   int c, x;
32775897234Sdrh   a = (unsigned char *)zLeft;
32875897234Sdrh   b = (unsigned char *)zRight;
32980738d9cSdrh   for(;;){
3307e427337Sdrh     c = *a;
3317e427337Sdrh     x = *b;
3327e427337Sdrh     if( c==x ){
3337e427337Sdrh       if( c==0 ) break;
3347e427337Sdrh     }else{
3357e427337Sdrh       c = (int)UpperToLower[c] - (int)UpperToLower[x];
3367e427337Sdrh       if( c ) break;
3377e427337Sdrh     }
33880738d9cSdrh     a++;
33980738d9cSdrh     b++;
34080738d9cSdrh   }
34180738d9cSdrh   return c;
34275897234Sdrh }
sqlite3_strnicmp(const char * zLeft,const char * zRight,int N)343ee0484c1Sdanielk1977 int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
34475897234Sdrh   register unsigned char *a, *b;
3459ca95730Sdrh   if( zLeft==0 ){
3469ca95730Sdrh     return zRight ? -1 : 0;
3479ca95730Sdrh   }else if( zRight==0 ){
3489ca95730Sdrh     return 1;
3499ca95730Sdrh   }
35075897234Sdrh   a = (unsigned char *)zLeft;
35175897234Sdrh   b = (unsigned char *)zRight;
35275897234Sdrh   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
3530202b29eSdanielk1977   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
35475897234Sdrh }
35575897234Sdrh 
356a5c2ad06Sdrh /*
357d44390c8Sdrh ** Compute an 8-bit hash on a string that is insensitive to case differences
358d44390c8Sdrh */
sqlite3StrIHash(const char * z)359d44390c8Sdrh u8 sqlite3StrIHash(const char *z){
360d44390c8Sdrh   u8 h = 0;
361d44390c8Sdrh   if( z==0 ) return 0;
362d44390c8Sdrh   while( z[0] ){
363d44390c8Sdrh     h += UpperToLower[(unsigned char)z[0]];
364d44390c8Sdrh     z++;
365d44390c8Sdrh   }
366d44390c8Sdrh   return h;
367d44390c8Sdrh }
368d44390c8Sdrh 
369d44390c8Sdrh /*
37002a43f6dSdrh ** Compute 10 to the E-th power.  Examples:  E==1 results in 10.
37102a43f6dSdrh ** E==2 results in 100.  E==50 results in 1.0e50.
37202a43f6dSdrh **
37302a43f6dSdrh ** This routine only works for values of E between 1 and 341.
37402a43f6dSdrh */
sqlite3Pow10(int E)37502a43f6dSdrh static LONGDOUBLE_TYPE sqlite3Pow10(int E){
3763dc97277Sdrh #if defined(_MSC_VER)
3773dc97277Sdrh   static const LONGDOUBLE_TYPE x[] = {
37838a59af4Sdrh     1.0e+001L,
37938a59af4Sdrh     1.0e+002L,
38038a59af4Sdrh     1.0e+004L,
38138a59af4Sdrh     1.0e+008L,
38238a59af4Sdrh     1.0e+016L,
38338a59af4Sdrh     1.0e+032L,
38438a59af4Sdrh     1.0e+064L,
38538a59af4Sdrh     1.0e+128L,
38638a59af4Sdrh     1.0e+256L
3873dc97277Sdrh   };
3883dc97277Sdrh   LONGDOUBLE_TYPE r = 1.0;
3893dc97277Sdrh   int i;
3903dc97277Sdrh   assert( E>=0 && E<=307 );
3913dc97277Sdrh   for(i=0; E!=0; i++, E >>=1){
3923dc97277Sdrh     if( E & 1 ) r *= x[i];
3933dc97277Sdrh   }
3943dc97277Sdrh   return r;
3953dc97277Sdrh #else
39602a43f6dSdrh   LONGDOUBLE_TYPE x = 10.0;
39702a43f6dSdrh   LONGDOUBLE_TYPE r = 1.0;
39802a43f6dSdrh   while(1){
39902a43f6dSdrh     if( E & 1 ) r *= x;
40002a43f6dSdrh     E >>= 1;
40102a43f6dSdrh     if( E==0 ) break;
40202a43f6dSdrh     x *= x;
40302a43f6dSdrh   }
40402a43f6dSdrh   return r;
4053dc97277Sdrh #endif
40602a43f6dSdrh }
40702a43f6dSdrh 
40802a43f6dSdrh /*
4099339da1fSdrh ** The string z[] is an text representation of a real number.
410025586a2Sdrh ** Convert this string to a double and write it into *pResult.
41193a5c6bdSdrh **
4129339da1fSdrh ** The string z[] is length bytes in length (bytes, not characters) and
4139339da1fSdrh ** uses the encoding enc.  The string is not necessarily zero-terminated.
41493a5c6bdSdrh **
4159339da1fSdrh ** Return TRUE if the result is a valid real number (or integer) and FALSE
4168a3884efSdrh ** if the string is empty or contains extraneous text.  More specifically
4178a3884efSdrh ** return
4188a3884efSdrh **      1          =>  The input string is a pure integer
4198a3884efSdrh **      2 or more  =>  The input has a decimal point or eNNN clause
4209a278229Sdrh **      0 or less  =>  The input string is not a valid number
4219a278229Sdrh **     -1          =>  Not a valid number, but has a valid prefix which
4229a278229Sdrh **                     includes a decimal point and/or an eNNN clause
4238a3884efSdrh **
4248a3884efSdrh ** Valid numbers are in one of these formats:
425025586a2Sdrh **
426025586a2Sdrh **    [+-]digits[E[+-]digits]
427025586a2Sdrh **    [+-]digits.[digits][E[+-]digits]
428025586a2Sdrh **    [+-].digits[E[+-]digits]
429025586a2Sdrh **
430025586a2Sdrh ** Leading and trailing whitespace is ignored for the purpose of determining
431025586a2Sdrh ** validity.
432025586a2Sdrh **
433025586a2Sdrh ** If some prefix of the input string is a valid number, this routine
434025586a2Sdrh ** returns FALSE but it still converts the prefix and writes the result
435025586a2Sdrh ** into *pResult.
43693a5c6bdSdrh */
4376dcf9a45Smistachkin #if defined(_MSC_VER)
4386dcf9a45Smistachkin #pragma warning(disable : 4756)
4396dcf9a45Smistachkin #endif
sqlite3AtoF(const char * z,double * pResult,int length,u8 enc)4409339da1fSdrh int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
441b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
4420e5fba79Sdrh   int incr;
443e3a4f2cfSdrh   const char *zEnd;
4446085f5e0Sshane   /* sign * significand * (10 ^ (esign * exponent)) */
4456085f5e0Sshane   int sign = 1;    /* sign of significand */
4466085f5e0Sshane   i64 s = 0;       /* significand */
4476085f5e0Sshane   int d = 0;       /* adjust exponent for shifting decimal point */
4486085f5e0Sshane   int esign = 1;   /* sign of exponent */
4496085f5e0Sshane   int e = 0;       /* exponent */
450025586a2Sdrh   int eValid = 1;  /* True exponent is either not used or is well-formed */
4516085f5e0Sshane   double result;
452c2b893a7Sdrh   int nDigit = 0;  /* Number of digits processed */
4538a3884efSdrh   int eType = 1;   /* 1: pure integer,  2+: fractional  -1 or less: bad UTF16 */
4546085f5e0Sshane 
4550e5fba79Sdrh   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
456025586a2Sdrh   *pResult = 0.0;   /* Default return value, in case of an error */
457e3a4f2cfSdrh   if( length==0 ) return 0;
458025586a2Sdrh 
4590e5fba79Sdrh   if( enc==SQLITE_UTF8 ){
4600e5fba79Sdrh     incr = 1;
461e3a4f2cfSdrh     zEnd = z + length;
4620e5fba79Sdrh   }else{
4630e5fba79Sdrh     int i;
4640e5fba79Sdrh     incr = 2;
46587969b2aSdrh     length &= ~1;
4660e5fba79Sdrh     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
46784422db9Sdrh     testcase( enc==SQLITE_UTF16LE );
46884422db9Sdrh     testcase( enc==SQLITE_UTF16BE );
4690e5fba79Sdrh     for(i=3-enc; i<length && z[i]==0; i+=2){}
4708a3884efSdrh     if( i<length ) eType = -100;
471ad975d53Sdrh     zEnd = &z[i^1];
4720e5fba79Sdrh     z += (enc&1);
4730e5fba79Sdrh   }
4749339da1fSdrh 
4756085f5e0Sshane   /* skip leading spaces */
4769339da1fSdrh   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
477025586a2Sdrh   if( z>=zEnd ) return 0;
4789339da1fSdrh 
4796085f5e0Sshane   /* get sign of significand */
48093a5c6bdSdrh   if( *z=='-' ){
48193a5c6bdSdrh     sign = -1;
4829339da1fSdrh     z+=incr;
48393a5c6bdSdrh   }else if( *z=='+' ){
4849339da1fSdrh     z+=incr;
48593a5c6bdSdrh   }
4869339da1fSdrh 
4876085f5e0Sshane   /* copy max significant digits to significand */
488c2b893a7Sdrh   while( z<zEnd && sqlite3Isdigit(*z) ){
4896085f5e0Sshane     s = s*10 + (*z - '0');
490c2b893a7Sdrh     z+=incr; nDigit++;
491c2b893a7Sdrh     if( s>=((LARGEST_INT64-9)/10) ){
4926085f5e0Sshane       /* skip non-significant significand digits
4936085f5e0Sshane       ** (increase exponent by d to shift decimal left) */
494c2b893a7Sdrh       while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; }
495c2b893a7Sdrh     }
496c2b893a7Sdrh   }
4979339da1fSdrh   if( z>=zEnd ) goto do_atof_calc;
4986085f5e0Sshane 
4996085f5e0Sshane   /* if decimal point is present */
50093a5c6bdSdrh   if( *z=='.' ){
5019339da1fSdrh     z+=incr;
5028a3884efSdrh     eType++;
5036085f5e0Sshane     /* copy digits from after decimal to significand
5046085f5e0Sshane     ** (decrease exponent by d to shift decimal right) */
50515af62acSdrh     while( z<zEnd && sqlite3Isdigit(*z) ){
50615af62acSdrh       if( s<((LARGEST_INT64-9)/10) ){
5076085f5e0Sshane         s = s*10 + (*z - '0');
50815af62acSdrh         d--;
509c2b893a7Sdrh         nDigit++;
510a06f17feSdrh       }
511c2b893a7Sdrh       z+=incr;
51215af62acSdrh     }
513a06f17feSdrh   }
5149339da1fSdrh   if( z>=zEnd ) goto do_atof_calc;
5156085f5e0Sshane 
5166085f5e0Sshane   /* if exponent is present */
51793a5c6bdSdrh   if( *z=='e' || *z=='E' ){
5189339da1fSdrh     z+=incr;
519025586a2Sdrh     eValid = 0;
5208a3884efSdrh     eType++;
521ad975d53Sdrh 
522ad975d53Sdrh     /* This branch is needed to avoid a (harmless) buffer overread.  The
523ad975d53Sdrh     ** special comment alerts the mutation tester that the correct answer
524ad975d53Sdrh     ** is obtained even if the branch is omitted */
525ad975d53Sdrh     if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
526ad975d53Sdrh 
5276085f5e0Sshane     /* get sign of exponent */
52893a5c6bdSdrh     if( *z=='-' ){
52993a5c6bdSdrh       esign = -1;
5309339da1fSdrh       z+=incr;
53193a5c6bdSdrh     }else if( *z=='+' ){
5329339da1fSdrh       z+=incr;
53393a5c6bdSdrh     }
5346085f5e0Sshane     /* copy digits to exponent */
5359339da1fSdrh     while( z<zEnd && sqlite3Isdigit(*z) ){
53657db4a75Sdrh       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
5379339da1fSdrh       z+=incr;
538025586a2Sdrh       eValid = 1;
53993a5c6bdSdrh     }
5406085f5e0Sshane   }
5416085f5e0Sshane 
542025586a2Sdrh   /* skip trailing spaces */
543025586a2Sdrh   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
544025586a2Sdrh 
5459339da1fSdrh do_atof_calc:
5466085f5e0Sshane   /* adjust exponent by d, and update sign */
5476085f5e0Sshane   e = (e*esign) + d;
5486085f5e0Sshane   if( e<0 ) {
5496085f5e0Sshane     esign = -1;
5506085f5e0Sshane     e *= -1;
55193a5c6bdSdrh   } else {
5526085f5e0Sshane     esign = 1;
5536085f5e0Sshane   }
5546085f5e0Sshane 
555ad975d53Sdrh   if( s==0 ) {
556ad975d53Sdrh     /* In the IEEE 754 standard, zero is signed. */
557c6daa01cSdrh     result = sign<0 ? -(double)0 : (double)0;
5586085f5e0Sshane   } else {
559ad975d53Sdrh     /* Attempt to reduce exponent.
560ad975d53Sdrh     **
561ad975d53Sdrh     ** Branches that are not required for the correct answer but which only
562ad975d53Sdrh     ** help to obtain the correct answer faster are marked with special
563ad975d53Sdrh     ** comments, as a hint to the mutation tester.
564ad975d53Sdrh     */
565ad975d53Sdrh     while( e>0 ){                                       /*OPTIMIZATION-IF-TRUE*/
5666085f5e0Sshane       if( esign>0 ){
567ad975d53Sdrh         if( s>=(LARGEST_INT64/10) ) break;             /*OPTIMIZATION-IF-FALSE*/
568ad975d53Sdrh         s *= 10;
569dcabfceeSshane       }else{
570ad975d53Sdrh         if( s%10!=0 ) break;                           /*OPTIMIZATION-IF-FALSE*/
571ad975d53Sdrh         s /= 10;
572ad975d53Sdrh       }
573ad975d53Sdrh       e--;
5746085f5e0Sshane     }
5756085f5e0Sshane 
5766085f5e0Sshane     /* adjust the sign of significand */
5776085f5e0Sshane     s = sign<0 ? -s : s;
5786085f5e0Sshane 
579ad975d53Sdrh     if( e==0 ){                                         /*OPTIMIZATION-IF-TRUE*/
580ad975d53Sdrh       result = (double)s;
581ad975d53Sdrh     }else{
582e025d1d7Sshane       /* attempt to handle extremely small/large numbers better */
583ad975d53Sdrh       if( e>307 ){                                      /*OPTIMIZATION-IF-TRUE*/
584ad975d53Sdrh         if( e<342 ){                                    /*OPTIMIZATION-IF-TRUE*/
58502a43f6dSdrh           LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
586e025d1d7Sshane           if( esign<0 ){
587e025d1d7Sshane             result = s / scale;
588e025d1d7Sshane             result /= 1.0e+308;
589e025d1d7Sshane           }else{
590e025d1d7Sshane             result = s * scale;
591e025d1d7Sshane             result *= 1.0e+308;
592e025d1d7Sshane           }
593ad975d53Sdrh         }else{ assert( e>=342 );
5942458a2e7Sdrh           if( esign<0 ){
5952458a2e7Sdrh             result = 0.0*s;
5962458a2e7Sdrh           }else{
597b9772e7fSdrh #ifdef INFINITY
5983ba18addSdrh             result = INFINITY*s;
599b9772e7fSdrh #else
6002458a2e7Sdrh             result = 1e308*1e308*s;  /* Infinity */
601b9772e7fSdrh #endif
6022458a2e7Sdrh           }
603ad975d53Sdrh         }
604e025d1d7Sshane       }else{
60502a43f6dSdrh         LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
6066085f5e0Sshane         if( esign<0 ){
6076085f5e0Sshane           result = s / scale;
6086085f5e0Sshane         }else{
6096085f5e0Sshane           result = s * scale;
6106085f5e0Sshane         }
611e025d1d7Sshane       }
61293a5c6bdSdrh     }
61393a5c6bdSdrh   }
6146085f5e0Sshane 
6156085f5e0Sshane   /* store the result */
6166085f5e0Sshane   *pResult = result;
6176085f5e0Sshane 
618025586a2Sdrh   /* return true if number and no extra non-whitespace chracters after */
6199a278229Sdrh   if( z==zEnd && nDigit>0 && eValid && eType>0 ){
6209a278229Sdrh     return eType;
621378a7d35Sdrh   }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){
6229a278229Sdrh     return -1;
6239a278229Sdrh   }else{
6249a278229Sdrh     return 0;
6259a278229Sdrh   }
626b37df7b9Sdrh #else
6275f1d6b61Sshaneh   return !sqlite3Atoi64(z, pResult, length, enc);
628b37df7b9Sdrh #endif /* SQLITE_OMIT_FLOATING_POINT */
62993a5c6bdSdrh }
6306dcf9a45Smistachkin #if defined(_MSC_VER)
6316dcf9a45Smistachkin #pragma warning(default : 4756)
6326dcf9a45Smistachkin #endif
63393a5c6bdSdrh 
634202b2df7Sdrh /*
63582b0f106Sdrh ** Render an signed 64-bit integer as text.  Store the result in zOut[].
63682b0f106Sdrh **
63782b0f106Sdrh ** The caller must ensure that zOut[] is at least 21 bytes in size.
63882b0f106Sdrh */
sqlite3Int64ToText(i64 v,char * zOut)63982b0f106Sdrh void sqlite3Int64ToText(i64 v, char *zOut){
64082b0f106Sdrh   int i;
64182b0f106Sdrh   u64 x;
64282b0f106Sdrh   char zTemp[22];
64382b0f106Sdrh   if( v<0 ){
6448deae5adSdrh     x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v;
64582b0f106Sdrh   }else{
64682b0f106Sdrh     x = v;
64782b0f106Sdrh   }
64882b0f106Sdrh   i = sizeof(zTemp)-2;
64982b0f106Sdrh   zTemp[sizeof(zTemp)-1] = 0;
65082b0f106Sdrh   do{
65182b0f106Sdrh     zTemp[i--] = (x%10) + '0';
65282b0f106Sdrh     x = x/10;
65382b0f106Sdrh   }while( x );
65482b0f106Sdrh   if( v<0 ) zTemp[i--] = '-';
65582b0f106Sdrh   memcpy(zOut, &zTemp[i+1], sizeof(zTemp)-1-i);
65682b0f106Sdrh }
65782b0f106Sdrh 
65882b0f106Sdrh /*
659217f4909Sdrh ** Compare the 19-character string zNum against the text representation
660217f4909Sdrh ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
661217f4909Sdrh ** if zNum is less than, equal to, or greater than the string.
6625f1d6b61Sshaneh ** Note that zNum must contain exactly 19 characters.
663217f4909Sdrh **
664217f4909Sdrh ** Unlike memcmp() this routine is guaranteed to return the difference
665217f4909Sdrh ** in the values of the last digit if the only difference is in the
666217f4909Sdrh ** last digit.  So, for example,
667217f4909Sdrh **
6689339da1fSdrh **      compare2pow63("9223372036854775800", 1)
669217f4909Sdrh **
670217f4909Sdrh ** will return -8.
671217f4909Sdrh */
compare2pow63(const char * zNum,int incr)6729339da1fSdrh static int compare2pow63(const char *zNum, int incr){
6739339da1fSdrh   int c = 0;
6749339da1fSdrh   int i;
6759339da1fSdrh                     /* 012345678901234567 */
6769339da1fSdrh   const char *pow63 = "922337203685477580";
6779339da1fSdrh   for(i=0; c==0 && i<18; i++){
6789339da1fSdrh     c = (zNum[i*incr]-pow63[i])*10;
6799339da1fSdrh   }
680217f4909Sdrh   if( c==0 ){
6819339da1fSdrh     c = zNum[18*incr] - '8';
68244dbca83Sdrh     testcase( c==(-1) );
68344dbca83Sdrh     testcase( c==0 );
68444dbca83Sdrh     testcase( c==(+1) );
685217f4909Sdrh   }
686217f4909Sdrh   return c;
687217f4909Sdrh }
688217f4909Sdrh 
689217f4909Sdrh /*
6909296c18aSdrh ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
6919296c18aSdrh ** routine does *not* accept hexadecimal notation.
692158b9cb9Sdrh **
69384d4f1a3Sdrh ** Returns:
694158b9cb9Sdrh **
6959a278229Sdrh **    -1    Not even a prefix of the input text looks like an integer
69684d4f1a3Sdrh **     0    Successful transformation.  Fits in a 64-bit signed integer.
6974eb57cefSdrh **     1    Excess non-space text after the integer value
69884d4f1a3Sdrh **     2    Integer too large for a 64-bit signed integer or is malformed
69984d4f1a3Sdrh **     3    Special case of 9223372036854775808
700fec19aadSdrh **
7019339da1fSdrh ** length is the number of bytes in the string (bytes, not characters).
7029339da1fSdrh ** The string is not necessarily zero-terminated.  The encoding is
7039339da1fSdrh ** given by enc.
704fec19aadSdrh */
sqlite3Atoi64(const char * zNum,i64 * pNum,int length,u8 enc)7059339da1fSdrh int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
7060e5fba79Sdrh   int incr;
707158b9cb9Sdrh   u64 u = 0;
7085f1d6b61Sshaneh   int neg = 0; /* assume positive */
7099339da1fSdrh   int i;
7109339da1fSdrh   int c = 0;
711609d5846Sdrh   int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
71284d4f1a3Sdrh   int rc;          /* Baseline return code */
7134b81592aSdrh   const char *zStart;
7149339da1fSdrh   const char *zEnd = zNum + length;
7150e5fba79Sdrh   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
7160e5fba79Sdrh   if( enc==SQLITE_UTF8 ){
7170e5fba79Sdrh     incr = 1;
7180e5fba79Sdrh   }else{
7190e5fba79Sdrh     incr = 2;
720359941bdSdrh     length &= ~1;
7210e5fba79Sdrh     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
7220e5fba79Sdrh     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
7230e5fba79Sdrh     nonNum = i<length;
724609d5846Sdrh     zEnd = &zNum[i^1];
7250e5fba79Sdrh     zNum += (enc&1);
7260e5fba79Sdrh   }
7279339da1fSdrh   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
728158b9cb9Sdrh   if( zNum<zEnd ){
729fec19aadSdrh     if( *zNum=='-' ){
730fec19aadSdrh       neg = 1;
7319339da1fSdrh       zNum+=incr;
732fec19aadSdrh     }else if( *zNum=='+' ){
7339339da1fSdrh       zNum+=incr;
734fec19aadSdrh     }
735158b9cb9Sdrh   }
7364b81592aSdrh   zStart = zNum;
7379339da1fSdrh   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
7389339da1fSdrh   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
739158b9cb9Sdrh     u = u*10 + c - '0';
740fec19aadSdrh   }
7414eb57cefSdrh   testcase( i==18*incr );
7424eb57cefSdrh   testcase( i==19*incr );
7434eb57cefSdrh   testcase( i==20*incr );
7441822ebf9Sdrh   if( u>LARGEST_INT64 ){
7451822ebf9Sdrh     /* This test and assignment is needed only to suppress UB warnings
7461822ebf9Sdrh     ** from clang and -fsanitize=undefined.  This test and assignment make
7471822ebf9Sdrh     ** the code a little larger and slower, and no harm comes from omitting
7481822ebf9Sdrh     ** them, but we must appaise the undefined-behavior pharisees. */
7491822ebf9Sdrh     *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
7501822ebf9Sdrh   }else if( neg ){
751158b9cb9Sdrh     *pNum = -(i64)u;
752158b9cb9Sdrh   }else{
753158b9cb9Sdrh     *pNum = (i64)u;
754158b9cb9Sdrh   }
7554eb57cefSdrh   rc = 0;
7569a278229Sdrh   if( i==0 && zStart==zNum ){    /* No digits */
7579a278229Sdrh     rc = -1;
7589a278229Sdrh   }else if( nonNum ){            /* UTF16 with high-order bytes non-zero */
75984d4f1a3Sdrh     rc = 1;
7604eb57cefSdrh   }else if( &zNum[i]<zEnd ){     /* Extra bytes at the end */
7614eb57cefSdrh     int jj = i;
7624eb57cefSdrh     do{
7634eb57cefSdrh       if( !sqlite3Isspace(zNum[jj]) ){
7644eb57cefSdrh         rc = 1;          /* Extra non-space text after the integer */
7654eb57cefSdrh         break;
76684d4f1a3Sdrh       }
7674eb57cefSdrh       jj += incr;
7684eb57cefSdrh     }while( &zNum[jj]<zEnd );
7694eb57cefSdrh   }
7704eb57cefSdrh   if( i<19*incr ){
771217f4909Sdrh     /* Less than 19 digits, so we know that it fits in 64 bits */
772158b9cb9Sdrh     assert( u<=LARGEST_INT64 );
77384d4f1a3Sdrh     return rc;
774217f4909Sdrh   }else{
775158b9cb9Sdrh     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
7764eb57cefSdrh     c = i>19*incr ? 1 : compare2pow63(zNum, incr);
777158b9cb9Sdrh     if( c<0 ){
778158b9cb9Sdrh       /* zNum is less than 9223372036854775808 so it fits */
779158b9cb9Sdrh       assert( u<=LARGEST_INT64 );
78084d4f1a3Sdrh       return rc;
7814eb57cefSdrh     }else{
7824eb57cefSdrh       *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
7834eb57cefSdrh       if( c>0 ){
784158b9cb9Sdrh         /* zNum is greater than 9223372036854775808 so it overflows */
78584d4f1a3Sdrh         return 2;
786158b9cb9Sdrh       }else{
787158b9cb9Sdrh         /* zNum is exactly 9223372036854775808.  Fits if negative.  The
788158b9cb9Sdrh         ** special case 2 overflow if positive */
789158b9cb9Sdrh         assert( u-1==LARGEST_INT64 );
79084d4f1a3Sdrh         return neg ? rc : 3;
791158b9cb9Sdrh       }
792217f4909Sdrh     }
793fec19aadSdrh   }
7944eb57cefSdrh }
795fec19aadSdrh 
796217f4909Sdrh /*
7979296c18aSdrh ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
7989296c18aSdrh ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
7999296c18aSdrh ** whereas sqlite3Atoi64() does not.
8009296c18aSdrh **
8019296c18aSdrh ** Returns:
8029296c18aSdrh **
8039296c18aSdrh **     0    Successful transformation.  Fits in a 64-bit signed integer.
80484d4f1a3Sdrh **     1    Excess text after the integer value
80584d4f1a3Sdrh **     2    Integer too large for a 64-bit signed integer or is malformed
80684d4f1a3Sdrh **     3    Special case of 9223372036854775808
8079296c18aSdrh */
sqlite3DecOrHexToI64(const char * z,i64 * pOut)8089296c18aSdrh int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
8099296c18aSdrh #ifndef SQLITE_OMIT_HEX_INTEGER
8109296c18aSdrh   if( z[0]=='0'
8119296c18aSdrh    && (z[1]=='x' || z[1]=='X')
8129296c18aSdrh   ){
8139296c18aSdrh     u64 u = 0;
8149296c18aSdrh     int i, k;
8159296c18aSdrh     for(i=2; z[i]=='0'; i++){}
8169296c18aSdrh     for(k=i; sqlite3Isxdigit(z[k]); k++){
8179296c18aSdrh       u = u*16 + sqlite3HexToInt(z[k]);
8189296c18aSdrh     }
8199296c18aSdrh     memcpy(pOut, &u, 8);
82084d4f1a3Sdrh     return (z[k]==0 && k-i<=16) ? 0 : 2;
8219296c18aSdrh   }else
8229296c18aSdrh #endif /* SQLITE_OMIT_HEX_INTEGER */
8239296c18aSdrh   {
8249296c18aSdrh     return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
8259296c18aSdrh   }
8269296c18aSdrh }
8279296c18aSdrh 
8289296c18aSdrh /*
829217f4909Sdrh ** If zNum represents an integer that will fit in 32-bits, then set
830217f4909Sdrh ** *pValue to that integer and return true.  Otherwise return false.
831217f4909Sdrh **
8329296c18aSdrh ** This routine accepts both decimal and hexadecimal notation for integers.
8339296c18aSdrh **
834217f4909Sdrh ** Any non-numeric characters that following zNum are ignored.
835b6a9eceaSdrh ** This is different from sqlite3Atoi64() which requires the
836217f4909Sdrh ** input number to be zero-terminated.
837217f4909Sdrh */
sqlite3GetInt32(const char * zNum,int * pValue)838217f4909Sdrh int sqlite3GetInt32(const char *zNum, int *pValue){
839217f4909Sdrh   sqlite_int64 v = 0;
840217f4909Sdrh   int i, c;
841217f4909Sdrh   int neg = 0;
842217f4909Sdrh   if( zNum[0]=='-' ){
843217f4909Sdrh     neg = 1;
844217f4909Sdrh     zNum++;
845217f4909Sdrh   }else if( zNum[0]=='+' ){
846217f4909Sdrh     zNum++;
847217f4909Sdrh   }
84828e048c6Sdrh #ifndef SQLITE_OMIT_HEX_INTEGER
84928e048c6Sdrh   else if( zNum[0]=='0'
85028e048c6Sdrh         && (zNum[1]=='x' || zNum[1]=='X')
85128e048c6Sdrh         && sqlite3Isxdigit(zNum[2])
85228e048c6Sdrh   ){
85328e048c6Sdrh     u32 u = 0;
85428e048c6Sdrh     zNum += 2;
855217f4909Sdrh     while( zNum[0]=='0' ) zNum++;
85628e048c6Sdrh     for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
85728e048c6Sdrh       u = u*16 + sqlite3HexToInt(zNum[i]);
85828e048c6Sdrh     }
85928e048c6Sdrh     if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
86028e048c6Sdrh       memcpy(pValue, &u, 4);
86128e048c6Sdrh       return 1;
86228e048c6Sdrh     }else{
86328e048c6Sdrh       return 0;
86428e048c6Sdrh     }
86528e048c6Sdrh   }
86628e048c6Sdrh #endif
867313e6fd2Sdrh   if( !sqlite3Isdigit(zNum[0]) ) return 0;
868935f2e70Sdrh   while( zNum[0]=='0' ) zNum++;
869b8cdbec2Sdanielk1977   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
870217f4909Sdrh     v = v*10 + c;
871217f4909Sdrh   }
872b8cdbec2Sdanielk1977 
873b8cdbec2Sdanielk1977   /* The longest decimal representation of a 32 bit integer is 10 digits:
874b8cdbec2Sdanielk1977   **
875b8cdbec2Sdanielk1977   **             1234567890
876b8cdbec2Sdanielk1977   **     2^31 -> 2147483648
877b8cdbec2Sdanielk1977   */
87844dbca83Sdrh   testcase( i==10 );
879b8cdbec2Sdanielk1977   if( i>10 ){
880217f4909Sdrh     return 0;
881217f4909Sdrh   }
88244dbca83Sdrh   testcase( v-neg==2147483647 );
883217f4909Sdrh   if( v-neg>2147483647 ){
884217f4909Sdrh     return 0;
885217f4909Sdrh   }
886217f4909Sdrh   if( neg ){
887217f4909Sdrh     v = -v;
888217f4909Sdrh   }
889217f4909Sdrh   *pValue = (int)v;
890217f4909Sdrh   return 1;
891217f4909Sdrh }
892dce2cbe6Sdrh 
893dce2cbe6Sdrh /*
89460ac3f42Sdrh ** Return a 32-bit integer value extracted from a string.  If the
89560ac3f42Sdrh ** string is not an integer, just return 0.
89660ac3f42Sdrh */
sqlite3Atoi(const char * z)89760ac3f42Sdrh int sqlite3Atoi(const char *z){
89860ac3f42Sdrh   int x = 0;
89948bf2d72Sdrh   sqlite3GetInt32(z, &x);
90060ac3f42Sdrh   return x;
90160ac3f42Sdrh }
90260ac3f42Sdrh 
90360ac3f42Sdrh /*
904abc38158Sdrh ** Try to convert z into an unsigned 32-bit integer.  Return true on
905abc38158Sdrh ** success and false if there is an error.
906abc38158Sdrh **
907abc38158Sdrh ** Only decimal notation is accepted.
908abc38158Sdrh */
sqlite3GetUInt32(const char * z,u32 * pI)909abc38158Sdrh int sqlite3GetUInt32(const char *z, u32 *pI){
910abc38158Sdrh   u64 v = 0;
911abc38158Sdrh   int i;
912abc38158Sdrh   for(i=0; sqlite3Isdigit(z[i]); i++){
913abc38158Sdrh     v = v*10 + z[i] - '0';
91469306bf4Sdrh     if( v>4294967296LL ){ *pI = 0; return 0; }
915abc38158Sdrh   }
91669306bf4Sdrh   if( i==0 || z[i]!=0 ){ *pI = 0; return 0; }
917abc38158Sdrh   *pI = (u32)v;
918abc38158Sdrh   return 1;
919abc38158Sdrh }
920abc38158Sdrh 
921abc38158Sdrh /*
922d8820e80Sdrh ** The variable-length integer encoding is as follows:
923d8820e80Sdrh **
924d8820e80Sdrh ** KEY:
925d8820e80Sdrh **         A = 0xxxxxxx    7 bits of data and one flag bit
926d8820e80Sdrh **         B = 1xxxxxxx    7 bits of data and one flag bit
927d8820e80Sdrh **         C = xxxxxxxx    8 bits of data
928d8820e80Sdrh **
929d8820e80Sdrh **  7 bits - A
930d8820e80Sdrh ** 14 bits - BA
931d8820e80Sdrh ** 21 bits - BBA
932d8820e80Sdrh ** 28 bits - BBBA
933d8820e80Sdrh ** 35 bits - BBBBA
934d8820e80Sdrh ** 42 bits - BBBBBA
935d8820e80Sdrh ** 49 bits - BBBBBBA
936d8820e80Sdrh ** 56 bits - BBBBBBBA
937d8820e80Sdrh ** 64 bits - BBBBBBBBC
938d8820e80Sdrh */
939d8820e80Sdrh 
940d8820e80Sdrh /*
9416d2fb154Sdrh ** Write a 64-bit variable-length integer to memory starting at p[0].
9426d2fb154Sdrh ** The length of data write will be between 1 and 9 bytes.  The number
9436d2fb154Sdrh ** of bytes written is returned.
9446d2fb154Sdrh **
9456d2fb154Sdrh ** A variable-length integer consists of the lower 7 bits of each byte
9466d2fb154Sdrh ** for all bytes that have the 8th bit set and one byte with the 8th
947d8820e80Sdrh ** bit clear.  Except, if we get to the 9th byte, it stores the full
948d8820e80Sdrh ** 8 bits and is the last byte.
9496d2fb154Sdrh */
putVarint64(unsigned char * p,u64 v)9502f2b2b85Sdrh static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
9516d2fb154Sdrh   int i, j, n;
9526d2fb154Sdrh   u8 buf[10];
953fe2093d7Sdrh   if( v & (((u64)0xff000000)<<32) ){
954aa78bec9Sdrh     p[8] = (u8)v;
955d8820e80Sdrh     v >>= 8;
956d8820e80Sdrh     for(i=7; i>=0; i--){
957aa78bec9Sdrh       p[i] = (u8)((v & 0x7f) | 0x80);
958d8820e80Sdrh       v >>= 7;
959d8820e80Sdrh     }
960d8820e80Sdrh     return 9;
961d8820e80Sdrh   }
9626d2fb154Sdrh   n = 0;
963192ac1dcSdanielk1977   do{
964aa78bec9Sdrh     buf[n++] = (u8)((v & 0x7f) | 0x80);
965192ac1dcSdanielk1977     v >>= 7;
966192ac1dcSdanielk1977   }while( v!=0 );
9676d2fb154Sdrh   buf[0] &= 0x7f;
968d8820e80Sdrh   assert( n<=9 );
9696d2fb154Sdrh   for(i=0, j=n-1; j>=0; j--, i++){
9706d2fb154Sdrh     p[i] = buf[j];
9716d2fb154Sdrh   }
9726d2fb154Sdrh   return n;
973192ac1dcSdanielk1977 }
sqlite3PutVarint(unsigned char * p,u64 v)9742f2b2b85Sdrh int sqlite3PutVarint(unsigned char *p, u64 v){
9752f2b2b85Sdrh   if( v<=0x7f ){
9762f2b2b85Sdrh     p[0] = v&0x7f;
97735b5a33eSdrh     return 1;
978952856adSshane   }
9792f2b2b85Sdrh   if( v<=0x3fff ){
9802f2b2b85Sdrh     p[0] = ((v>>7)&0x7f)|0x80;
9812f2b2b85Sdrh     p[1] = v&0x7f;
98235b5a33eSdrh     return 2;
98335b5a33eSdrh   }
9842f2b2b85Sdrh   return putVarint64(p,v);
98535b5a33eSdrh }
98635b5a33eSdrh 
98735b5a33eSdrh /*
9880b2864cbSdrh ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
9890b2864cbSdrh ** are defined here rather than simply putting the constant expressions
9900b2864cbSdrh ** inline in order to work around bugs in the RVT compiler.
9910b2864cbSdrh **
9920b2864cbSdrh ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
9930b2864cbSdrh **
9940b2864cbSdrh ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
9950b2864cbSdrh */
9960b2864cbSdrh #define SLOT_2_0     0x001fc07f
9970b2864cbSdrh #define SLOT_4_2_0   0xf01fc07f
9980b2864cbSdrh 
9990b2864cbSdrh 
10000b2864cbSdrh /*
10016d2fb154Sdrh ** Read a 64-bit variable-length integer from memory starting at p[0].
10026d2fb154Sdrh ** Return the number of bytes read.  The value is stored in *v.
10036d2fb154Sdrh */
sqlite3GetVarint(const unsigned char * p,u64 * v)10041bd10f8aSdrh u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
1005356574e9Sshane   u32 a,b,s;
1006356574e9Sshane 
1007698c86f4Sdrh   if( ((signed char*)p)[0]>=0 ){
1008698c86f4Sdrh     *v = *p;
10096d2fb154Sdrh     return 1;
10106d2fb154Sdrh   }
1011698c86f4Sdrh   if( ((signed char*)p)[1]>=0 ){
1012698c86f4Sdrh     *v = ((u32)(p[0]&0x7f)<<7) | p[1];
10136d2fb154Sdrh     return 2;
10146d2fb154Sdrh   }
1015356574e9Sshane 
10160b2864cbSdrh   /* Verify that constants are precomputed correctly */
10170b2864cbSdrh   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
10181da207e6Sshaneh   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
10190b2864cbSdrh 
1020698c86f4Sdrh   a = ((u32)p[0])<<14;
1021698c86f4Sdrh   b = p[1];
1022698c86f4Sdrh   p += 2;
1023356574e9Sshane   a |= *p;
1024022e8afeSshane   /* a: p0<<14 | p2 (unmasked) */
1025356574e9Sshane   if (!(a&0x80))
1026356574e9Sshane   {
10270b2864cbSdrh     a &= SLOT_2_0;
1028356574e9Sshane     b &= 0x7f;
1029356574e9Sshane     b = b<<7;
1030356574e9Sshane     a |= b;
1031356574e9Sshane     *v = a;
10326d2fb154Sdrh     return 3;
10336d2fb154Sdrh   }
1034356574e9Sshane 
1035022e8afeSshane   /* CSE1 from below */
10360b2864cbSdrh   a &= SLOT_2_0;
1037356574e9Sshane   p++;
1038356574e9Sshane   b = b<<14;
1039356574e9Sshane   b |= *p;
1040022e8afeSshane   /* b: p1<<14 | p3 (unmasked) */
1041356574e9Sshane   if (!(b&0x80))
1042356574e9Sshane   {
10430b2864cbSdrh     b &= SLOT_2_0;
1044022e8afeSshane     /* moved CSE1 up */
1045022e8afeSshane     /* a &= (0x7f<<14)|(0x7f); */
1046356574e9Sshane     a = a<<7;
1047356574e9Sshane     a |= b;
1048356574e9Sshane     *v = a;
10496d2fb154Sdrh     return 4;
10506d2fb154Sdrh   }
1051356574e9Sshane 
1052022e8afeSshane   /* a: p0<<14 | p2 (masked) */
1053022e8afeSshane   /* b: p1<<14 | p3 (unmasked) */
1054022e8afeSshane   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
1055022e8afeSshane   /* moved CSE1 up */
1056022e8afeSshane   /* a &= (0x7f<<14)|(0x7f); */
10570b2864cbSdrh   b &= SLOT_2_0;
1058356574e9Sshane   s = a;
1059022e8afeSshane   /* s: p0<<14 | p2 (masked) */
1060356574e9Sshane 
1061356574e9Sshane   p++;
1062356574e9Sshane   a = a<<14;
1063356574e9Sshane   a |= *p;
1064022e8afeSshane   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1065356574e9Sshane   if (!(a&0x80))
1066356574e9Sshane   {
106762aaa6caSdrh     /* we can skip these cause they were (effectively) done above
106862aaa6caSdrh     ** while calculating s */
1069022e8afeSshane     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
1070022e8afeSshane     /* b &= (0x7f<<14)|(0x7f); */
1071356574e9Sshane     b = b<<7;
1072356574e9Sshane     a |= b;
1073356574e9Sshane     s = s>>18;
1074356574e9Sshane     *v = ((u64)s)<<32 | a;
1075356574e9Sshane     return 5;
1076d8820e80Sdrh   }
1077356574e9Sshane 
1078022e8afeSshane   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
1079356574e9Sshane   s = s<<7;
1080356574e9Sshane   s |= b;
1081022e8afeSshane   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
1082356574e9Sshane 
1083356574e9Sshane   p++;
1084356574e9Sshane   b = b<<14;
1085356574e9Sshane   b |= *p;
1086022e8afeSshane   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
1087356574e9Sshane   if (!(b&0x80))
1088356574e9Sshane   {
1089022e8afeSshane     /* we can skip this cause it was (effectively) done above in calc'ing s */
1090022e8afeSshane     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
10910b2864cbSdrh     a &= SLOT_2_0;
1092356574e9Sshane     a = a<<7;
1093356574e9Sshane     a |= b;
1094356574e9Sshane     s = s>>18;
1095356574e9Sshane     *v = ((u64)s)<<32 | a;
1096356574e9Sshane     return 6;
1097356574e9Sshane   }
1098356574e9Sshane 
1099356574e9Sshane   p++;
1100356574e9Sshane   a = a<<14;
1101356574e9Sshane   a |= *p;
1102022e8afeSshane   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
1103356574e9Sshane   if (!(a&0x80))
1104356574e9Sshane   {
11050b2864cbSdrh     a &= SLOT_4_2_0;
11060b2864cbSdrh     b &= SLOT_2_0;
1107356574e9Sshane     b = b<<7;
1108356574e9Sshane     a |= b;
1109356574e9Sshane     s = s>>11;
1110356574e9Sshane     *v = ((u64)s)<<32 | a;
1111356574e9Sshane     return 7;
1112356574e9Sshane   }
1113356574e9Sshane 
1114022e8afeSshane   /* CSE2 from below */
11150b2864cbSdrh   a &= SLOT_2_0;
1116356574e9Sshane   p++;
1117356574e9Sshane   b = b<<14;
1118356574e9Sshane   b |= *p;
1119022e8afeSshane   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
1120356574e9Sshane   if (!(b&0x80))
1121356574e9Sshane   {
11220b2864cbSdrh     b &= SLOT_4_2_0;
1123022e8afeSshane     /* moved CSE2 up */
1124022e8afeSshane     /* a &= (0x7f<<14)|(0x7f); */
1125356574e9Sshane     a = a<<7;
1126356574e9Sshane     a |= b;
1127356574e9Sshane     s = s>>4;
1128356574e9Sshane     *v = ((u64)s)<<32 | a;
1129356574e9Sshane     return 8;
1130356574e9Sshane   }
1131356574e9Sshane 
1132356574e9Sshane   p++;
1133356574e9Sshane   a = a<<15;
1134356574e9Sshane   a |= *p;
1135022e8afeSshane   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
1136356574e9Sshane 
1137022e8afeSshane   /* moved CSE2 up */
1138022e8afeSshane   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
11390b2864cbSdrh   b &= SLOT_2_0;
1140356574e9Sshane   b = b<<8;
1141356574e9Sshane   a |= b;
1142356574e9Sshane 
1143356574e9Sshane   s = s<<4;
1144356574e9Sshane   b = p[-4];
1145356574e9Sshane   b &= 0x7f;
1146356574e9Sshane   b = b>>3;
1147356574e9Sshane   s |= b;
1148356574e9Sshane 
1149356574e9Sshane   *v = ((u64)s)<<32 | a;
1150356574e9Sshane 
1151356574e9Sshane   return 9;
11526d2fb154Sdrh }
11536d2fb154Sdrh 
11546d2fb154Sdrh /*
11556d2fb154Sdrh ** Read a 32-bit variable-length integer from memory starting at p[0].
11566d2fb154Sdrh ** Return the number of bytes read.  The value is stored in *v.
115735cd643cSdrh **
115835cd643cSdrh ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
115935cd643cSdrh ** integer, then set *v to 0xffffffff.
116035cd643cSdrh **
1161952856adSshane ** A MACRO version, getVarint32, is provided which inlines the
1162952856adSshane ** single-byte case.  All code should use the MACRO version as
1163952856adSshane ** this function assumes the single-byte case has already been handled.
11646d2fb154Sdrh */
sqlite3GetVarint32(const unsigned char * p,u32 * v)11651bd10f8aSdrh u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
1166356574e9Sshane   u32 a,b;
1167356574e9Sshane 
1168dee0e404Sdrh   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
1169dee0e404Sdrh   ** by the getVarin32() macro */
1170356574e9Sshane   a = *p;
1171022e8afeSshane   /* a: p0 (unmasked) */
1172952856adSshane #ifndef getVarint32
1173356574e9Sshane   if (!(a&0x80))
1174356574e9Sshane   {
1175dee0e404Sdrh     /* Values between 0 and 127 */
1176356574e9Sshane     *v = a;
1177e6f85e71Sdrh     return 1;
1178e6f85e71Sdrh   }
1179952856adSshane #endif
1180356574e9Sshane 
1181dee0e404Sdrh   /* The 2-byte case */
1182356574e9Sshane   p++;
1183356574e9Sshane   b = *p;
1184022e8afeSshane   /* b: p1 (unmasked) */
1185356574e9Sshane   if (!(b&0x80))
1186356574e9Sshane   {
1187dee0e404Sdrh     /* Values between 128 and 16383 */
1188356574e9Sshane     a &= 0x7f;
1189356574e9Sshane     a = a<<7;
1190356574e9Sshane     *v = a | b;
1191e6f85e71Sdrh     return 2;
1192e6f85e71Sdrh   }
1193356574e9Sshane 
1194dee0e404Sdrh   /* The 3-byte case */
1195356574e9Sshane   p++;
1196356574e9Sshane   a = a<<14;
1197356574e9Sshane   a |= *p;
1198022e8afeSshane   /* a: p0<<14 | p2 (unmasked) */
1199356574e9Sshane   if (!(a&0x80))
1200356574e9Sshane   {
1201dee0e404Sdrh     /* Values between 16384 and 2097151 */
1202356574e9Sshane     a &= (0x7f<<14)|(0x7f);
1203356574e9Sshane     b &= 0x7f;
1204356574e9Sshane     b = b<<7;
1205356574e9Sshane     *v = a | b;
1206356574e9Sshane     return 3;
1207356574e9Sshane   }
1208356574e9Sshane 
1209dee0e404Sdrh   /* A 32-bit varint is used to store size information in btrees.
1210dee0e404Sdrh   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
1211dee0e404Sdrh   ** A 3-byte varint is sufficient, for example, to record the size
1212dee0e404Sdrh   ** of a 1048569-byte BLOB or string.
1213dee0e404Sdrh   **
1214dee0e404Sdrh   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
1215dee0e404Sdrh   ** rare larger cases can be handled by the slower 64-bit varint
1216dee0e404Sdrh   ** routine.
1217dee0e404Sdrh   */
1218dee0e404Sdrh #if 1
1219dee0e404Sdrh   {
1220dee0e404Sdrh     u64 v64;
1221dee0e404Sdrh     u8 n;
1222dee0e404Sdrh 
122315cedda9Sdrh     n = sqlite3GetVarint(p-2, &v64);
1224dee0e404Sdrh     assert( n>3 && n<=9 );
122535cd643cSdrh     if( (v64 & SQLITE_MAX_U32)!=v64 ){
122635cd643cSdrh       *v = 0xffffffff;
122735cd643cSdrh     }else{
1228dee0e404Sdrh       *v = (u32)v64;
122935cd643cSdrh     }
1230dee0e404Sdrh     return n;
1231dee0e404Sdrh   }
1232dee0e404Sdrh 
1233dee0e404Sdrh #else
1234dee0e404Sdrh   /* For following code (kept for historical record only) shows an
1235dee0e404Sdrh   ** unrolling for the 3- and 4-byte varint cases.  This code is
1236dee0e404Sdrh   ** slightly faster, but it is also larger and much harder to test.
1237dee0e404Sdrh   */
1238356574e9Sshane   p++;
1239356574e9Sshane   b = b<<14;
1240356574e9Sshane   b |= *p;
1241022e8afeSshane   /* b: p1<<14 | p3 (unmasked) */
1242356574e9Sshane   if (!(b&0x80))
1243356574e9Sshane   {
1244dee0e404Sdrh     /* Values between 2097152 and 268435455 */
1245356574e9Sshane     b &= (0x7f<<14)|(0x7f);
1246356574e9Sshane     a &= (0x7f<<14)|(0x7f);
1247356574e9Sshane     a = a<<7;
1248356574e9Sshane     *v = a | b;
1249356574e9Sshane     return 4;
1250356574e9Sshane   }
1251356574e9Sshane 
1252356574e9Sshane   p++;
1253356574e9Sshane   a = a<<14;
1254356574e9Sshane   a |= *p;
1255022e8afeSshane   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1256356574e9Sshane   if (!(a&0x80))
1257356574e9Sshane   {
12583bbe761cSdan     /* Values  between 268435456 and 34359738367 */
12593bbe761cSdan     a &= SLOT_4_2_0;
12603bbe761cSdan     b &= SLOT_4_2_0;
1261356574e9Sshane     b = b<<7;
1262356574e9Sshane     *v = a | b;
1263356574e9Sshane     return 5;
1264356574e9Sshane   }
1265356574e9Sshane 
1266cec3e3eeSdrh   /* We can only reach this point when reading a corrupt database
1267cec3e3eeSdrh   ** file.  In that case we are not in any hurry.  Use the (relatively
1268cec3e3eeSdrh   ** slow) general-purpose sqlite3GetVarint() routine to extract the
1269cec3e3eeSdrh   ** value. */
1270356574e9Sshane   {
1271cec3e3eeSdrh     u64 v64;
12721bd10f8aSdrh     u8 n;
1273cec3e3eeSdrh 
1274cec3e3eeSdrh     p -= 4;
1275cec3e3eeSdrh     n = sqlite3GetVarint(p, &v64);
1276cec3e3eeSdrh     assert( n>5 && n<=9 );
1277cec3e3eeSdrh     *v = (u32)v64;
1278cec3e3eeSdrh     return n;
1279356574e9Sshane   }
1280dee0e404Sdrh #endif
1281192ac1dcSdanielk1977 }
1282192ac1dcSdanielk1977 
12836d2fb154Sdrh /*
12846d2fb154Sdrh ** Return the number of bytes that will be needed to store the given
12856d2fb154Sdrh ** 64-bit integer.
12866d2fb154Sdrh */
sqlite3VarintLen(u64 v)1287192ac1dcSdanielk1977 int sqlite3VarintLen(u64 v){
128859a5364cSdrh   int i;
12896f17c09fSdrh   for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
1290192ac1dcSdanielk1977   return i;
1291192ac1dcSdanielk1977 }
1292c572ef7fSdanielk1977 
1293a3152895Sdrh 
1294a3152895Sdrh /*
12951cc5ed81Sdanielk1977 ** Read or write a four-byte big-endian integer value.
1296a3152895Sdrh */
sqlite3Get4byte(const u8 * p)1297a3152895Sdrh u32 sqlite3Get4byte(const u8 *p){
12985372e4d4Sdrh #if SQLITE_BYTEORDER==4321
12995372e4d4Sdrh   u32 x;
13005372e4d4Sdrh   memcpy(&x,p,4);
13015372e4d4Sdrh   return x;
1302dc5ece86Sdrh #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
13035372e4d4Sdrh   u32 x;
13045372e4d4Sdrh   memcpy(&x,p,4);
13055372e4d4Sdrh   return __builtin_bswap32(x);
1306a39284bfSdrh #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
1307647ca46fSmistachkin   u32 x;
1308647ca46fSmistachkin   memcpy(&x,p,4);
1309647ca46fSmistachkin   return _byteswap_ulong(x);
13105372e4d4Sdrh #else
1311693e6719Sdrh   testcase( p[0]&0x80 );
1312693e6719Sdrh   return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
13135372e4d4Sdrh #endif
1314a3152895Sdrh }
sqlite3Put4byte(unsigned char * p,u32 v)1315a3152895Sdrh void sqlite3Put4byte(unsigned char *p, u32 v){
13165372e4d4Sdrh #if SQLITE_BYTEORDER==4321
13175372e4d4Sdrh   memcpy(p,&v,4);
1318dc5ece86Sdrh #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
13195372e4d4Sdrh   u32 x = __builtin_bswap32(v);
13205372e4d4Sdrh   memcpy(p,&x,4);
1321a39284bfSdrh #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
1322647ca46fSmistachkin   u32 x = _byteswap_ulong(v);
1323647ca46fSmistachkin   memcpy(p,&x,4);
13245372e4d4Sdrh #else
1325aa78bec9Sdrh   p[0] = (u8)(v>>24);
1326aa78bec9Sdrh   p[1] = (u8)(v>>16);
1327aa78bec9Sdrh   p[2] = (u8)(v>>8);
1328aa78bec9Sdrh   p[3] = (u8)v;
13295372e4d4Sdrh #endif
1330a3152895Sdrh }
1331a3152895Sdrh 
13329296c18aSdrh 
13339296c18aSdrh 
13349296c18aSdrh /*
13359296c18aSdrh ** Translate a single byte of Hex into an integer.
13369296c18aSdrh ** This routine only works if h really is a valid hexadecimal
13379296c18aSdrh ** character:  0..9a..fA..F
13389296c18aSdrh */
sqlite3HexToInt(int h)13399296c18aSdrh u8 sqlite3HexToInt(int h){
13409296c18aSdrh   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
13419296c18aSdrh #ifdef SQLITE_ASCII
13429296c18aSdrh   h += 9*(1&(h>>6));
13439296c18aSdrh #endif
13449296c18aSdrh #ifdef SQLITE_EBCDIC
13459296c18aSdrh   h += 9*(1&~(h>>4));
13469296c18aSdrh #endif
13479296c18aSdrh   return (u8)(h & 0xf);
13489296c18aSdrh }
13499296c18aSdrh 
1350b48c0d59Sdrh #if !defined(SQLITE_OMIT_BLOB_LITERAL)
13519d213ef0Sdrh /*
13529d213ef0Sdrh ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
13539d213ef0Sdrh ** value.  Return a pointer to its binary value.  Space to hold the
13549d213ef0Sdrh ** binary value has been obtained from malloc and must be freed by
13559d213ef0Sdrh ** the calling routine.
13569d213ef0Sdrh */
sqlite3HexToBlob(sqlite3 * db,const char * z,int n)1357ca48c90fSdrh void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
1358c572ef7fSdanielk1977   char *zBlob;
1359c572ef7fSdanielk1977   int i;
1360c572ef7fSdanielk1977 
1361575fad65Sdrh   zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
1362ca48c90fSdrh   n--;
136376f80796Sdrh   if( zBlob ){
13649d213ef0Sdrh     for(i=0; i<n; i+=2){
1365cd74b611Sdan       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
1366c572ef7fSdanielk1977     }
1367ca48c90fSdrh     zBlob[i/2] = 0;
136876f80796Sdrh   }
13693fd0a736Sdanielk1977   return zBlob;
1370c572ef7fSdanielk1977 }
1371b48c0d59Sdrh #endif /* !SQLITE_OMIT_BLOB_LITERAL */
1372fe63d1c9Sdrh 
1373413c3d36Sdrh /*
1374413c3d36Sdrh ** Log an error that is an API call on a connection pointer that should
1375413c3d36Sdrh ** not have been used.  The "type" of connection pointer is given as the
1376413c3d36Sdrh ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
1377413c3d36Sdrh */
logBadConnection(const char * zType)1378413c3d36Sdrh static void logBadConnection(const char *zType){
1379413c3d36Sdrh   sqlite3_log(SQLITE_MISUSE,
1380413c3d36Sdrh      "API call with %s database connection pointer",
1381413c3d36Sdrh      zType
1382413c3d36Sdrh   );
1383413c3d36Sdrh }
1384a3152895Sdrh 
1385fe63d1c9Sdrh /*
138655176259Sdrh ** Check to make sure we have a valid db pointer.  This test is not
138755176259Sdrh ** foolproof but it does provide some measure of protection against
138855176259Sdrh ** misuse of the interface such as passing in db pointers that are
138955176259Sdrh ** NULL or which have been previously closed.  If this routine returns
13907e8b848aSdrh ** 1 it means that the db pointer is valid and 0 if it should not be
139155176259Sdrh ** dereferenced for any reason.  The calling function should invoke
139255176259Sdrh ** SQLITE_MISUSE immediately.
13937e8b848aSdrh **
13947e8b848aSdrh ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
13957e8b848aSdrh ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
13967e8b848aSdrh ** open properly and is not fit for general use but which can be
13977e8b848aSdrh ** used as an argument to sqlite3_errmsg() or sqlite3_close().
139855176259Sdrh */
sqlite3SafetyCheckOk(sqlite3 * db)13997e8b848aSdrh int sqlite3SafetyCheckOk(sqlite3 *db){
14005f9de6ecSdrh   u8 eOpenState;
1401413c3d36Sdrh   if( db==0 ){
1402413c3d36Sdrh     logBadConnection("NULL");
1403413c3d36Sdrh     return 0;
1404413c3d36Sdrh   }
14055f9de6ecSdrh   eOpenState = db->eOpenState;
14065f9de6ecSdrh   if( eOpenState!=SQLITE_STATE_OPEN ){
1407e294da02Sdrh     if( sqlite3SafetyCheckSickOrOk(db) ){
1408e294da02Sdrh       testcase( sqlite3GlobalConfig.xLog!=0 );
1409413c3d36Sdrh       logBadConnection("unopened");
1410413c3d36Sdrh     }
1411dee0e404Sdrh     return 0;
1412dee0e404Sdrh   }else{
14137e8b848aSdrh     return 1;
14147e8b848aSdrh   }
1415dee0e404Sdrh }
sqlite3SafetyCheckSickOrOk(sqlite3 * db)14167e8b848aSdrh int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
14175f9de6ecSdrh   u8 eOpenState;
14185f9de6ecSdrh   eOpenState = db->eOpenState;
14195f9de6ecSdrh   if( eOpenState!=SQLITE_STATE_SICK &&
14205f9de6ecSdrh       eOpenState!=SQLITE_STATE_OPEN &&
14215f9de6ecSdrh       eOpenState!=SQLITE_STATE_BUSY ){
1422e294da02Sdrh     testcase( sqlite3GlobalConfig.xLog!=0 );
1423af46dc12Sdrh     logBadConnection("invalid");
1424413c3d36Sdrh     return 0;
1425413c3d36Sdrh   }else{
14267e8b848aSdrh     return 1;
142755176259Sdrh   }
1428413c3d36Sdrh }
1429158b9cb9Sdrh 
1430158b9cb9Sdrh /*
1431158b9cb9Sdrh ** Attempt to add, substract, or multiply the 64-bit signed value iB against
1432158b9cb9Sdrh ** the other 64-bit signed integer at *pA and store the result in *pA.
1433158b9cb9Sdrh ** Return 0 on success.  Or if the operation would have resulted in an
1434158b9cb9Sdrh ** overflow, leave *pA unchanged and return 1.
1435158b9cb9Sdrh */
sqlite3AddInt64(i64 * pA,i64 iB)1436158b9cb9Sdrh int sqlite3AddInt64(i64 *pA, i64 iB){
1437b9772e7fSdrh #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
14384a47761eSdrh   return __builtin_add_overflow(*pA, iB, pA);
14394a47761eSdrh #else
1440158b9cb9Sdrh   i64 iA = *pA;
1441158b9cb9Sdrh   testcase( iA==0 ); testcase( iA==1 );
1442158b9cb9Sdrh   testcase( iB==-1 ); testcase( iB==0 );
1443158b9cb9Sdrh   if( iB>=0 ){
1444158b9cb9Sdrh     testcase( iA>0 && LARGEST_INT64 - iA == iB );
1445158b9cb9Sdrh     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
1446158b9cb9Sdrh     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
1447158b9cb9Sdrh   }else{
1448158b9cb9Sdrh     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
1449158b9cb9Sdrh     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
1450158b9cb9Sdrh     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
1451158b9cb9Sdrh   }
145253a6eb3fSdrh   *pA += iB;
1453158b9cb9Sdrh   return 0;
14544a47761eSdrh #endif
1455158b9cb9Sdrh }
sqlite3SubInt64(i64 * pA,i64 iB)1456158b9cb9Sdrh int sqlite3SubInt64(i64 *pA, i64 iB){
1457b9772e7fSdrh #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
14584a47761eSdrh   return __builtin_sub_overflow(*pA, iB, pA);
14594a47761eSdrh #else
1460158b9cb9Sdrh   testcase( iB==SMALLEST_INT64+1 );
1461158b9cb9Sdrh   if( iB==SMALLEST_INT64 ){
1462158b9cb9Sdrh     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
1463158b9cb9Sdrh     if( (*pA)>=0 ) return 1;
1464158b9cb9Sdrh     *pA -= iB;
1465158b9cb9Sdrh     return 0;
1466158b9cb9Sdrh   }else{
1467158b9cb9Sdrh     return sqlite3AddInt64(pA, -iB);
1468158b9cb9Sdrh   }
14694a47761eSdrh #endif
1470158b9cb9Sdrh }
sqlite3MulInt64(i64 * pA,i64 iB)1471158b9cb9Sdrh int sqlite3MulInt64(i64 *pA, i64 iB){
1472b9772e7fSdrh #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
14734a47761eSdrh   return __builtin_mul_overflow(*pA, iB, pA);
14744a47761eSdrh #else
1475158b9cb9Sdrh   i64 iA = *pA;
147609952c64Sdrh   if( iB>0 ){
147709952c64Sdrh     if( iA>LARGEST_INT64/iB ) return 1;
147809952c64Sdrh     if( iA<SMALLEST_INT64/iB ) return 1;
147909952c64Sdrh   }else if( iB<0 ){
148009952c64Sdrh     if( iA>0 ){
148109952c64Sdrh       if( iB<SMALLEST_INT64/iA ) return 1;
148209952c64Sdrh     }else if( iA<0 ){
148309952c64Sdrh       if( iB==SMALLEST_INT64 ) return 1;
148409952c64Sdrh       if( iA==SMALLEST_INT64 ) return 1;
148509952c64Sdrh       if( -iA>LARGEST_INT64/-iB ) return 1;
148653a6eb3fSdrh     }
148753a6eb3fSdrh   }
148809952c64Sdrh   *pA = iA*iB;
1489158b9cb9Sdrh   return 0;
14904a47761eSdrh #endif
1491158b9cb9Sdrh }
1492d50ffc41Sdrh 
1493d50ffc41Sdrh /*
1494d50ffc41Sdrh ** Compute the absolute value of a 32-bit signed integer, of possible.  Or
1495d50ffc41Sdrh ** if the integer has a value of -2147483648, return +2147483647
1496d50ffc41Sdrh */
sqlite3AbsInt32(int x)1497d50ffc41Sdrh int sqlite3AbsInt32(int x){
1498d50ffc41Sdrh   if( x>=0 ) return x;
149987e79aefSdrh   if( x==(int)0x80000000 ) return 0x7fffffff;
1500d50ffc41Sdrh   return -x;
1501d50ffc41Sdrh }
150281cc5163Sdrh 
150381cc5163Sdrh #ifdef SQLITE_ENABLE_8_3_NAMES
150481cc5163Sdrh /*
1505b51bf439Sdrh ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
150681cc5163Sdrh ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
150781cc5163Sdrh ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
150881cc5163Sdrh ** three characters, then shorten the suffix on z[] to be the last three
150981cc5163Sdrh ** characters of the original suffix.
151081cc5163Sdrh **
1511b51bf439Sdrh ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
1512b51bf439Sdrh ** do the suffix shortening regardless of URI parameter.
1513b51bf439Sdrh **
151481cc5163Sdrh ** Examples:
151581cc5163Sdrh **
151681cc5163Sdrh **     test.db-journal    =>   test.nal
151781cc5163Sdrh **     test.db-wal        =>   test.wal
151881cc5163Sdrh **     test.db-shm        =>   test.shm
1519f580860fSdrh **     test.db-mj7f3319fa =>   test.9fa
152081cc5163Sdrh */
sqlite3FileSuffix3(const char * zBaseFilename,char * z)152181cc5163Sdrh void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
1522b51bf439Sdrh #if SQLITE_ENABLE_8_3_NAMES<2
15237d39e17eSdrh   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
1524b51bf439Sdrh #endif
1525b51bf439Sdrh   {
152681cc5163Sdrh     int i, sz;
152781cc5163Sdrh     sz = sqlite3Strlen30(z);
1528c83f2d47Sdrh     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
1529c02a43afSdrh     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
153081cc5163Sdrh   }
153181cc5163Sdrh }
153281cc5163Sdrh #endif
1533bf539c4dSdrh 
1534bf539c4dSdrh /*
1535bf539c4dSdrh ** Find (an approximate) sum of two LogEst values.  This computation is
1536bf539c4dSdrh ** not a simple "+" operator because LogEst is stored as a logarithmic
1537bf539c4dSdrh ** value.
1538bf539c4dSdrh **
1539bf539c4dSdrh */
sqlite3LogEstAdd(LogEst a,LogEst b)1540bf539c4dSdrh LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
1541bf539c4dSdrh   static const unsigned char x[] = {
1542bf539c4dSdrh      10, 10,                         /* 0,1 */
1543bf539c4dSdrh       9, 9,                          /* 2,3 */
1544bf539c4dSdrh       8, 8,                          /* 4,5 */
1545bf539c4dSdrh       7, 7, 7,                       /* 6,7,8 */
1546bf539c4dSdrh       6, 6, 6,                       /* 9,10,11 */
1547bf539c4dSdrh       5, 5, 5,                       /* 12-14 */
1548bf539c4dSdrh       4, 4, 4, 4,                    /* 15-18 */
1549bf539c4dSdrh       3, 3, 3, 3, 3, 3,              /* 19-24 */
1550bf539c4dSdrh       2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
1551bf539c4dSdrh   };
1552bf539c4dSdrh   if( a>=b ){
1553bf539c4dSdrh     if( a>b+49 ) return a;
1554bf539c4dSdrh     if( a>b+31 ) return a+1;
1555bf539c4dSdrh     return a+x[a-b];
1556bf539c4dSdrh   }else{
1557bf539c4dSdrh     if( b>a+49 ) return b;
1558bf539c4dSdrh     if( b>a+31 ) return b+1;
1559bf539c4dSdrh     return b+x[b-a];
1560bf539c4dSdrh   }
1561bf539c4dSdrh }
1562bf539c4dSdrh 
1563bf539c4dSdrh /*
1564224155ddSdrh ** Convert an integer into a LogEst.  In other words, compute an
1565224155ddSdrh ** approximation for 10*log2(x).
1566bf539c4dSdrh */
sqlite3LogEst(u64 x)1567bf539c4dSdrh LogEst sqlite3LogEst(u64 x){
1568bf539c4dSdrh   static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1569bf539c4dSdrh   LogEst y = 40;
1570bf539c4dSdrh   if( x<8 ){
1571bf539c4dSdrh     if( x<2 ) return 0;
1572bf539c4dSdrh     while( x<8 ){  y -= 10; x <<= 1; }
1573bf539c4dSdrh   }else{
1574ceb4b1dbSdrh #if GCC_VERSION>=5004000
1575ceb4b1dbSdrh     int i = 60 - __builtin_clzll(x);
1576ceb4b1dbSdrh     y += i*10;
1577ceb4b1dbSdrh     x >>= i;
1578ceb4b1dbSdrh #else
157975ab50ceSdrh     while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/
1580bf539c4dSdrh     while( x>15 ){  y += 10; x >>= 1; }
1581ceb4b1dbSdrh #endif
1582bf539c4dSdrh   }
1583bf539c4dSdrh   return a[x&7] + y - 10;
1584bf539c4dSdrh }
1585bf539c4dSdrh 
1586bf539c4dSdrh /*
1587bf539c4dSdrh ** Convert a double into a LogEst
1588bf539c4dSdrh ** In other words, compute an approximation for 10*log2(x).
1589bf539c4dSdrh */
sqlite3LogEstFromDouble(double x)1590bf539c4dSdrh LogEst sqlite3LogEstFromDouble(double x){
1591bf539c4dSdrh   u64 a;
1592bf539c4dSdrh   LogEst e;
1593bf539c4dSdrh   assert( sizeof(x)==8 && sizeof(a)==8 );
1594bf539c4dSdrh   if( x<=1 ) return 0;
1595bf539c4dSdrh   if( x<=2000000000 ) return sqlite3LogEst((u64)x);
1596bf539c4dSdrh   memcpy(&a, &x, 8);
1597bf539c4dSdrh   e = (a>>52) - 1022;
1598bf539c4dSdrh   return e*10;
1599bf539c4dSdrh }
1600bf539c4dSdrh 
1601bf539c4dSdrh /*
1602bf539c4dSdrh ** Convert a LogEst into an integer.
1603bf539c4dSdrh */
sqlite3LogEstToInt(LogEst x)1604bf539c4dSdrh u64 sqlite3LogEstToInt(LogEst x){
1605bf539c4dSdrh   u64 n;
1606bf539c4dSdrh   n = x%10;
1607bf539c4dSdrh   x /= 10;
1608bf539c4dSdrh   if( n>=5 ) n -= 2;
1609bf539c4dSdrh   else if( n>=1 ) n -= 1;
1610ecdf20d3Sdrh   if( x>60 ) return (u64)LARGEST_INT64;
1611ecdf20d3Sdrh   return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
1612bf539c4dSdrh }
16139bf755ccSdrh 
16149bf755ccSdrh /*
16159bf755ccSdrh ** Add a new name/number pair to a VList.  This might require that the
16169bf755ccSdrh ** VList object be reallocated, so return the new VList.  If an OOM
1617ce1bbe51Sdrh ** error occurs, the original VList returned and the
16189bf755ccSdrh ** db->mallocFailed flag is set.
16199bf755ccSdrh **
16209bf755ccSdrh ** A VList is really just an array of integers.  To destroy a VList,
16219bf755ccSdrh ** simply pass it to sqlite3DbFree().
16229bf755ccSdrh **
16239bf755ccSdrh ** The first integer is the number of integers allocated for the whole
16249bf755ccSdrh ** VList.  The second integer is the number of integers actually used.
16259bf755ccSdrh ** Each name/number pair is encoded by subsequent groups of 3 or more
16269bf755ccSdrh ** integers.
16279bf755ccSdrh **
1628ce1bbe51Sdrh ** Each name/number pair starts with two integers which are the numeric
16299bf755ccSdrh ** value for the pair and the size of the name/number pair, respectively.
16309bf755ccSdrh ** The text name overlays one or more following integers.  The text name
16319bf755ccSdrh ** is always zero-terminated.
16329bf755ccSdrh **
1633ce1bbe51Sdrh ** Conceptually:
1634ce1bbe51Sdrh **
1635ce1bbe51Sdrh **    struct VList {
1636ce1bbe51Sdrh **      int nAlloc;   // Number of allocated slots
1637ce1bbe51Sdrh **      int nUsed;    // Number of used slots
1638ce1bbe51Sdrh **      struct VListEntry {
1639ce1bbe51Sdrh **        int iValue;    // Value for this entry
1640ce1bbe51Sdrh **        int nSlot;     // Slots used by this entry
1641ce1bbe51Sdrh **        // ... variable name goes here
1642ce1bbe51Sdrh **      } a[0];
1643ce1bbe51Sdrh **    }
1644ce1bbe51Sdrh **
1645ce1bbe51Sdrh ** During code generation, pointers to the variable names within the
1646ce1bbe51Sdrh ** VList are taken.  When that happens, nAlloc is set to zero as an
1647ce1bbe51Sdrh ** indication that the VList may never again be enlarged, since the
1648ce1bbe51Sdrh ** accompanying realloc() would invalidate the pointers.
16499bf755ccSdrh */
sqlite3VListAdd(sqlite3 * db,VList * pIn,const char * zName,int nName,int iVal)16509bf755ccSdrh VList *sqlite3VListAdd(
16519bf755ccSdrh   sqlite3 *db,           /* The database connection used for malloc() */
16529bf755ccSdrh   VList *pIn,            /* The input VList.  Might be NULL */
16539bf755ccSdrh   const char *zName,     /* Name of symbol to add */
16549bf755ccSdrh   int nName,             /* Bytes of text in zName */
16559bf755ccSdrh   int iVal               /* Value to associate with zName */
16569bf755ccSdrh ){
16579bf755ccSdrh   int nInt;              /* number of sizeof(int) objects needed for zName */
1658ce1bbe51Sdrh   char *z;               /* Pointer to where zName will be stored */
1659ce1bbe51Sdrh   int i;                 /* Index in pIn[] where zName is stored */
16609bf755ccSdrh 
16619bf755ccSdrh   nInt = nName/4 + 3;
1662ce1bbe51Sdrh   assert( pIn==0 || pIn[0]>=3 );  /* Verify ok to add new elements */
16639bf755ccSdrh   if( pIn==0 || pIn[1]+nInt > pIn[0] ){
16649bf755ccSdrh     /* Enlarge the allocation */
16650aa3231fSdrh     sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
16669bf755ccSdrh     VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
1667ce1bbe51Sdrh     if( pOut==0 ) return pIn;
16689bf755ccSdrh     if( pIn==0 ) pOut[1] = 2;
16699bf755ccSdrh     pIn = pOut;
16709bf755ccSdrh     pIn[0] = nAlloc;
16719bf755ccSdrh   }
16729bf755ccSdrh   i = pIn[1];
16739bf755ccSdrh   pIn[i] = iVal;
16749bf755ccSdrh   pIn[i+1] = nInt;
16759bf755ccSdrh   z = (char*)&pIn[i+2];
16769bf755ccSdrh   pIn[1] = i+nInt;
16779bf755ccSdrh   assert( pIn[1]<=pIn[0] );
16789bf755ccSdrh   memcpy(z, zName, nName);
16799bf755ccSdrh   z[nName] = 0;
16809bf755ccSdrh   return pIn;
16819bf755ccSdrh }
16829bf755ccSdrh 
16839bf755ccSdrh /*
16849bf755ccSdrh ** Return a pointer to the name of a variable in the given VList that
16859bf755ccSdrh ** has the value iVal.  Or return a NULL if there is no such variable in
16869bf755ccSdrh ** the list
16879bf755ccSdrh */
sqlite3VListNumToName(VList * pIn,int iVal)16889bf755ccSdrh const char *sqlite3VListNumToName(VList *pIn, int iVal){
16899bf755ccSdrh   int i, mx;
16909bf755ccSdrh   if( pIn==0 ) return 0;
16919bf755ccSdrh   mx = pIn[1];
16929bf755ccSdrh   i = 2;
16939bf755ccSdrh   do{
16949bf755ccSdrh     if( pIn[i]==iVal ) return (char*)&pIn[i+2];
16959bf755ccSdrh     i += pIn[i+1];
16969bf755ccSdrh   }while( i<mx );
16979bf755ccSdrh   return 0;
16989bf755ccSdrh }
16999bf755ccSdrh 
17009bf755ccSdrh /*
17019bf755ccSdrh ** Return the number of the variable named zName, if it is in VList.
17029bf755ccSdrh ** or return 0 if there is no such variable.
17039bf755ccSdrh */
sqlite3VListNameToNum(VList * pIn,const char * zName,int nName)17049bf755ccSdrh int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
17059bf755ccSdrh   int i, mx;
17069bf755ccSdrh   if( pIn==0 ) return 0;
17079bf755ccSdrh   mx = pIn[1];
17089bf755ccSdrh   i = 2;
17099bf755ccSdrh   do{
17109bf755ccSdrh     const char *z = (const char*)&pIn[i+2];
17119bf755ccSdrh     if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
17129bf755ccSdrh     i += pIn[i+1];
17139bf755ccSdrh   }while( i<mx );
17149bf755ccSdrh   return 0;
17159bf755ccSdrh }
1716