xref: /sqlite-3.40.0/src/util.c (revision 9bccde3d)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** Utility functions used throughout sqlite.
13 **
14 ** This file contains functions for allocating memory, comparing
15 ** strings, and stuff like that.
16 **
17 */
18 #include "sqliteInt.h"
19 #include <stdarg.h>
20 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
21 # include <math.h>
22 #endif
23 
24 /*
25 ** Routine needed to support the testcase() macro.
26 */
27 #ifdef SQLITE_COVERAGE_TEST
28 void sqlite3Coverage(int x){
29   static unsigned dummy = 0;
30   dummy += (unsigned)x;
31 }
32 #endif
33 
34 /*
35 ** Give a callback to the test harness that can be used to simulate faults
36 ** in places where it is difficult or expensive to do so purely by means
37 ** of inputs.
38 **
39 ** The intent of the integer argument is to let the fault simulator know
40 ** which of multiple sqlite3FaultSim() calls has been hit.
41 **
42 ** Return whatever integer value the test callback returns, or return
43 ** SQLITE_OK if no test callback is installed.
44 */
45 #ifndef SQLITE_OMIT_BUILTIN_TEST
46 int sqlite3FaultSim(int iTest){
47   int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
48   return xCallback ? xCallback(iTest) : SQLITE_OK;
49 }
50 #endif
51 
52 #ifndef SQLITE_OMIT_FLOATING_POINT
53 /*
54 ** Return true if the floating point value is Not a Number (NaN).
55 **
56 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
57 ** Otherwise, we have our own implementation that works on most systems.
58 */
59 int sqlite3IsNaN(double x){
60   int rc;   /* The value return */
61 #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
62   /*
63   ** Systems that support the isnan() library function should probably
64   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
65   ** found that many systems do not have a working isnan() function so
66   ** this implementation is provided as an alternative.
67   **
68   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
69   ** On the other hand, the use of -ffast-math comes with the following
70   ** warning:
71   **
72   **      This option [-ffast-math] should never be turned on by any
73   **      -O option since it can result in incorrect output for programs
74   **      which depend on an exact implementation of IEEE or ISO
75   **      rules/specifications for math functions.
76   **
77   ** Under MSVC, this NaN test may fail if compiled with a floating-
78   ** point precision mode other than /fp:precise.  From the MSDN
79   ** documentation:
80   **
81   **      The compiler [with /fp:precise] will properly handle comparisons
82   **      involving NaN. For example, x != x evaluates to true if x is NaN
83   **      ...
84   */
85 #ifdef __FAST_MATH__
86 # error SQLite will not work correctly with the -ffast-math option of GCC.
87 #endif
88   volatile double y = x;
89   volatile double z = y;
90   rc = (y!=z);
91 #else  /* if HAVE_ISNAN */
92   rc = isnan(x);
93 #endif /* HAVE_ISNAN */
94   testcase( rc );
95   return rc;
96 }
97 #endif /* SQLITE_OMIT_FLOATING_POINT */
98 
99 /*
100 ** Compute a string length that is limited to what can be stored in
101 ** lower 30 bits of a 32-bit signed integer.
102 **
103 ** The value returned will never be negative.  Nor will it ever be greater
104 ** than the actual length of the string.  For very long strings (greater
105 ** than 1GiB) the value returned might be less than the true string length.
106 */
107 int sqlite3Strlen30(const char *z){
108   if( z==0 ) return 0;
109   return 0x3fffffff & (int)strlen(z);
110 }
111 
112 /*
113 ** The string z[] is followed immediately by another string.  Return
114 ** a poiner to that other string.
115 */
116 const char *sqlite3StrNext(const char *z){
117   return z + strlen(z) + 1;
118 }
119 
120 /*
121 ** Set the current error code to err_code and clear any prior error message.
122 */
123 void sqlite3Error(sqlite3 *db, int err_code){
124   assert( db!=0 );
125   db->errCode = err_code;
126   if( db->pErr ) sqlite3ValueSetNull(db->pErr);
127 }
128 
129 /*
130 ** Set the most recent error code and error string for the sqlite
131 ** handle "db". The error code is set to "err_code".
132 **
133 ** If it is not NULL, string zFormat specifies the format of the
134 ** error string in the style of the printf functions: The following
135 ** format characters are allowed:
136 **
137 **      %s      Insert a string
138 **      %z      A string that should be freed after use
139 **      %d      Insert an integer
140 **      %T      Insert a token
141 **      %S      Insert the first element of a SrcList
142 **
143 ** zFormat and any string tokens that follow it are assumed to be
144 ** encoded in UTF-8.
145 **
146 ** To clear the most recent error for sqlite handle "db", sqlite3Error
147 ** should be called with err_code set to SQLITE_OK and zFormat set
148 ** to NULL.
149 */
150 void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
151   assert( db!=0 );
152   db->errCode = err_code;
153   if( zFormat==0 ){
154     sqlite3Error(db, err_code);
155   }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
156     char *z;
157     va_list ap;
158     va_start(ap, zFormat);
159     z = sqlite3VMPrintf(db, zFormat, ap);
160     va_end(ap);
161     sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
162   }
163 }
164 
165 /*
166 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
167 ** The following formatting characters are allowed:
168 **
169 **      %s      Insert a string
170 **      %z      A string that should be freed after use
171 **      %d      Insert an integer
172 **      %T      Insert a token
173 **      %S      Insert the first element of a SrcList
174 **
175 ** This function should be used to report any error that occurs while
176 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
177 ** last thing the sqlite3_prepare() function does is copy the error
178 ** stored by this function into the database handle using sqlite3Error().
179 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
180 ** during statement execution (sqlite3_step() etc.).
181 */
182 void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
183   char *zMsg;
184   va_list ap;
185   sqlite3 *db = pParse->db;
186   va_start(ap, zFormat);
187   zMsg = sqlite3VMPrintf(db, zFormat, ap);
188   va_end(ap);
189   if( db->suppressErr ){
190     sqlite3DbFree(db, zMsg);
191   }else{
192     pParse->nErr++;
193     sqlite3DbFree(db, pParse->zErrMsg);
194     pParse->zErrMsg = zMsg;
195     pParse->rc = SQLITE_ERROR;
196   }
197 }
198 
199 /*
200 ** Convert an SQL-style quoted string into a normal string by removing
201 ** the quote characters.  The conversion is done in-place.  If the
202 ** input does not begin with a quote character, then this routine
203 ** is a no-op.
204 **
205 ** The input string must be zero-terminated.  A new zero-terminator
206 ** is added to the dequoted string.
207 **
208 ** The return value is -1 if no dequoting occurs or the length of the
209 ** dequoted string, exclusive of the zero terminator, if dequoting does
210 ** occur.
211 **
212 ** 2002-Feb-14: This routine is extended to remove MS-Access style
213 ** brackets from around identifiers.  For example:  "[a-b-c]" becomes
214 ** "a-b-c".
215 */
216 int sqlite3Dequote(char *z){
217   char quote;
218   int i, j;
219   if( z==0 ) return -1;
220   quote = z[0];
221   switch( quote ){
222     case '\'':  break;
223     case '"':   break;
224     case '`':   break;                /* For MySQL compatibility */
225     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
226     default:    return -1;
227   }
228   for(i=1, j=0;; i++){
229     assert( z[i] );
230     if( z[i]==quote ){
231       if( z[i+1]==quote ){
232         z[j++] = quote;
233         i++;
234       }else{
235         break;
236       }
237     }else{
238       z[j++] = z[i];
239     }
240   }
241   z[j] = 0;
242   return j;
243 }
244 
245 /*
246 ** Generate a Token object from a string
247 */
248 void sqlite3TokenInit(Token *p, char *z){
249   p->z = z;
250   p->n = sqlite3Strlen30(z);
251 }
252 
253 /* Convenient short-hand */
254 #define UpperToLower sqlite3UpperToLower
255 
256 /*
257 ** Some systems have stricmp().  Others have strcasecmp().  Because
258 ** there is no consistency, we will define our own.
259 **
260 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
261 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
262 ** the contents of two buffers containing UTF-8 strings in a
263 ** case-independent fashion, using the same definition of "case
264 ** independence" that SQLite uses internally when comparing identifiers.
265 */
266 int sqlite3_stricmp(const char *zLeft, const char *zRight){
267   if( zLeft==0 ){
268     return zRight ? -1 : 0;
269   }else if( zRight==0 ){
270     return 1;
271   }
272   return sqlite3StrICmp(zLeft, zRight);
273 }
274 int sqlite3StrICmp(const char *zLeft, const char *zRight){
275   unsigned char *a, *b;
276   int c;
277   a = (unsigned char *)zLeft;
278   b = (unsigned char *)zRight;
279   for(;;){
280     c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
281     if( c || *a==0 ) break;
282     a++;
283     b++;
284   }
285   return c;
286 }
287 int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
288   register unsigned char *a, *b;
289   if( zLeft==0 ){
290     return zRight ? -1 : 0;
291   }else if( zRight==0 ){
292     return 1;
293   }
294   a = (unsigned char *)zLeft;
295   b = (unsigned char *)zRight;
296   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
297   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
298 }
299 
300 /*
301 ** The string z[] is an text representation of a real number.
302 ** Convert this string to a double and write it into *pResult.
303 **
304 ** The string z[] is length bytes in length (bytes, not characters) and
305 ** uses the encoding enc.  The string is not necessarily zero-terminated.
306 **
307 ** Return TRUE if the result is a valid real number (or integer) and FALSE
308 ** if the string is empty or contains extraneous text.  Valid numbers
309 ** are in one of these formats:
310 **
311 **    [+-]digits[E[+-]digits]
312 **    [+-]digits.[digits][E[+-]digits]
313 **    [+-].digits[E[+-]digits]
314 **
315 ** Leading and trailing whitespace is ignored for the purpose of determining
316 ** validity.
317 **
318 ** If some prefix of the input string is a valid number, this routine
319 ** returns FALSE but it still converts the prefix and writes the result
320 ** into *pResult.
321 */
322 int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
323 #ifndef SQLITE_OMIT_FLOATING_POINT
324   int incr;
325   const char *zEnd = z + length;
326   /* sign * significand * (10 ^ (esign * exponent)) */
327   int sign = 1;    /* sign of significand */
328   i64 s = 0;       /* significand */
329   int d = 0;       /* adjust exponent for shifting decimal point */
330   int esign = 1;   /* sign of exponent */
331   int e = 0;       /* exponent */
332   int eValid = 1;  /* True exponent is either not used or is well-formed */
333   double result;
334   int nDigits = 0;
335   int nonNum = 0;
336 
337   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
338   *pResult = 0.0;   /* Default return value, in case of an error */
339 
340   if( enc==SQLITE_UTF8 ){
341     incr = 1;
342   }else{
343     int i;
344     incr = 2;
345     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
346     for(i=3-enc; i<length && z[i]==0; i+=2){}
347     nonNum = i<length;
348     zEnd = z+i+enc-3;
349     z += (enc&1);
350   }
351 
352   /* skip leading spaces */
353   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
354   if( z>=zEnd ) return 0;
355 
356   /* get sign of significand */
357   if( *z=='-' ){
358     sign = -1;
359     z+=incr;
360   }else if( *z=='+' ){
361     z+=incr;
362   }
363 
364   /* skip leading zeroes */
365   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
366 
367   /* copy max significant digits to significand */
368   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
369     s = s*10 + (*z - '0');
370     z+=incr, nDigits++;
371   }
372 
373   /* skip non-significant significand digits
374   ** (increase exponent by d to shift decimal left) */
375   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
376   if( z>=zEnd ) goto do_atof_calc;
377 
378   /* if decimal point is present */
379   if( *z=='.' ){
380     z+=incr;
381     /* copy digits from after decimal to significand
382     ** (decrease exponent by d to shift decimal right) */
383     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
384       s = s*10 + (*z - '0');
385       z+=incr, nDigits++, d--;
386     }
387     /* skip non-significant digits */
388     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
389   }
390   if( z>=zEnd ) goto do_atof_calc;
391 
392   /* if exponent is present */
393   if( *z=='e' || *z=='E' ){
394     z+=incr;
395     eValid = 0;
396     if( z>=zEnd ) goto do_atof_calc;
397     /* get sign of exponent */
398     if( *z=='-' ){
399       esign = -1;
400       z+=incr;
401     }else if( *z=='+' ){
402       z+=incr;
403     }
404     /* copy digits to exponent */
405     while( z<zEnd && sqlite3Isdigit(*z) ){
406       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
407       z+=incr;
408       eValid = 1;
409     }
410   }
411 
412   /* skip trailing spaces */
413   if( nDigits && eValid ){
414     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
415   }
416 
417 do_atof_calc:
418   /* adjust exponent by d, and update sign */
419   e = (e*esign) + d;
420   if( e<0 ) {
421     esign = -1;
422     e *= -1;
423   } else {
424     esign = 1;
425   }
426 
427   /* if 0 significand */
428   if( !s ) {
429     /* In the IEEE 754 standard, zero is signed.
430     ** Add the sign if we've seen at least one digit */
431     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
432   } else {
433     /* attempt to reduce exponent */
434     if( esign>0 ){
435       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
436     }else{
437       while( !(s%10) && e>0 ) e--,s/=10;
438     }
439 
440     /* adjust the sign of significand */
441     s = sign<0 ? -s : s;
442 
443     /* if exponent, scale significand as appropriate
444     ** and store in result. */
445     if( e ){
446       LONGDOUBLE_TYPE scale = 1.0;
447       /* attempt to handle extremely small/large numbers better */
448       if( e>307 && e<342 ){
449         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
450         if( esign<0 ){
451           result = s / scale;
452           result /= 1.0e+308;
453         }else{
454           result = s * scale;
455           result *= 1.0e+308;
456         }
457       }else if( e>=342 ){
458         if( esign<0 ){
459           result = 0.0*s;
460         }else{
461           result = 1e308*1e308*s;  /* Infinity */
462         }
463       }else{
464         /* 1.0e+22 is the largest power of 10 than can be
465         ** represented exactly. */
466         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
467         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
468         if( esign<0 ){
469           result = s / scale;
470         }else{
471           result = s * scale;
472         }
473       }
474     } else {
475       result = (double)s;
476     }
477   }
478 
479   /* store the result */
480   *pResult = result;
481 
482   /* return true if number and no extra non-whitespace chracters after */
483   return z>=zEnd && nDigits>0 && eValid && nonNum==0;
484 #else
485   return !sqlite3Atoi64(z, pResult, length, enc);
486 #endif /* SQLITE_OMIT_FLOATING_POINT */
487 }
488 
489 /*
490 ** Compare the 19-character string zNum against the text representation
491 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
492 ** if zNum is less than, equal to, or greater than the string.
493 ** Note that zNum must contain exactly 19 characters.
494 **
495 ** Unlike memcmp() this routine is guaranteed to return the difference
496 ** in the values of the last digit if the only difference is in the
497 ** last digit.  So, for example,
498 **
499 **      compare2pow63("9223372036854775800", 1)
500 **
501 ** will return -8.
502 */
503 static int compare2pow63(const char *zNum, int incr){
504   int c = 0;
505   int i;
506                     /* 012345678901234567 */
507   const char *pow63 = "922337203685477580";
508   for(i=0; c==0 && i<18; i++){
509     c = (zNum[i*incr]-pow63[i])*10;
510   }
511   if( c==0 ){
512     c = zNum[18*incr] - '8';
513     testcase( c==(-1) );
514     testcase( c==0 );
515     testcase( c==(+1) );
516   }
517   return c;
518 }
519 
520 /*
521 ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
522 ** routine does *not* accept hexadecimal notation.
523 **
524 ** If the zNum value is representable as a 64-bit twos-complement
525 ** integer, then write that value into *pNum and return 0.
526 **
527 ** If zNum is exactly 9223372036854775808, return 2.  This special
528 ** case is broken out because while 9223372036854775808 cannot be a
529 ** signed 64-bit integer, its negative -9223372036854775808 can be.
530 **
531 ** If zNum is too big for a 64-bit integer and is not
532 ** 9223372036854775808  or if zNum contains any non-numeric text,
533 ** then return 1.
534 **
535 ** length is the number of bytes in the string (bytes, not characters).
536 ** The string is not necessarily zero-terminated.  The encoding is
537 ** given by enc.
538 */
539 int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
540   int incr;
541   u64 u = 0;
542   int neg = 0; /* assume positive */
543   int i;
544   int c = 0;
545   int nonNum = 0;
546   const char *zStart;
547   const char *zEnd = zNum + length;
548   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
549   if( enc==SQLITE_UTF8 ){
550     incr = 1;
551   }else{
552     incr = 2;
553     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
554     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
555     nonNum = i<length;
556     zEnd = zNum+i+enc-3;
557     zNum += (enc&1);
558   }
559   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
560   if( zNum<zEnd ){
561     if( *zNum=='-' ){
562       neg = 1;
563       zNum+=incr;
564     }else if( *zNum=='+' ){
565       zNum+=incr;
566     }
567   }
568   zStart = zNum;
569   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
570   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
571     u = u*10 + c - '0';
572   }
573   if( u>LARGEST_INT64 ){
574     *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
575   }else if( neg ){
576     *pNum = -(i64)u;
577   }else{
578     *pNum = (i64)u;
579   }
580   testcase( i==18 );
581   testcase( i==19 );
582   testcase( i==20 );
583   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum)
584        || i>19*incr || nonNum ){
585     /* zNum is empty or contains non-numeric text or is longer
586     ** than 19 digits (thus guaranteeing that it is too large) */
587     return 1;
588   }else if( i<19*incr ){
589     /* Less than 19 digits, so we know that it fits in 64 bits */
590     assert( u<=LARGEST_INT64 );
591     return 0;
592   }else{
593     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
594     c = compare2pow63(zNum, incr);
595     if( c<0 ){
596       /* zNum is less than 9223372036854775808 so it fits */
597       assert( u<=LARGEST_INT64 );
598       return 0;
599     }else if( c>0 ){
600       /* zNum is greater than 9223372036854775808 so it overflows */
601       return 1;
602     }else{
603       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
604       ** special case 2 overflow if positive */
605       assert( u-1==LARGEST_INT64 );
606       return neg ? 0 : 2;
607     }
608   }
609 }
610 
611 /*
612 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
613 ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
614 ** whereas sqlite3Atoi64() does not.
615 **
616 ** Returns:
617 **
618 **     0    Successful transformation.  Fits in a 64-bit signed integer.
619 **     1    Integer too large for a 64-bit signed integer or is malformed
620 **     2    Special case of 9223372036854775808
621 */
622 int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
623 #ifndef SQLITE_OMIT_HEX_INTEGER
624   if( z[0]=='0'
625    && (z[1]=='x' || z[1]=='X')
626    && sqlite3Isxdigit(z[2])
627   ){
628     u64 u = 0;
629     int i, k;
630     for(i=2; z[i]=='0'; i++){}
631     for(k=i; sqlite3Isxdigit(z[k]); k++){
632       u = u*16 + sqlite3HexToInt(z[k]);
633     }
634     memcpy(pOut, &u, 8);
635     return (z[k]==0 && k-i<=16) ? 0 : 1;
636   }else
637 #endif /* SQLITE_OMIT_HEX_INTEGER */
638   {
639     return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
640   }
641 }
642 
643 /*
644 ** If zNum represents an integer that will fit in 32-bits, then set
645 ** *pValue to that integer and return true.  Otherwise return false.
646 **
647 ** This routine accepts both decimal and hexadecimal notation for integers.
648 **
649 ** Any non-numeric characters that following zNum are ignored.
650 ** This is different from sqlite3Atoi64() which requires the
651 ** input number to be zero-terminated.
652 */
653 int sqlite3GetInt32(const char *zNum, int *pValue){
654   sqlite_int64 v = 0;
655   int i, c;
656   int neg = 0;
657   if( zNum[0]=='-' ){
658     neg = 1;
659     zNum++;
660   }else if( zNum[0]=='+' ){
661     zNum++;
662   }
663 #ifndef SQLITE_OMIT_HEX_INTEGER
664   else if( zNum[0]=='0'
665         && (zNum[1]=='x' || zNum[1]=='X')
666         && sqlite3Isxdigit(zNum[2])
667   ){
668     u32 u = 0;
669     zNum += 2;
670     while( zNum[0]=='0' ) zNum++;
671     for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
672       u = u*16 + sqlite3HexToInt(zNum[i]);
673     }
674     if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
675       memcpy(pValue, &u, 4);
676       return 1;
677     }else{
678       return 0;
679     }
680   }
681 #endif
682   while( zNum[0]=='0' ) zNum++;
683   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
684     v = v*10 + c;
685   }
686 
687   /* The longest decimal representation of a 32 bit integer is 10 digits:
688   **
689   **             1234567890
690   **     2^31 -> 2147483648
691   */
692   testcase( i==10 );
693   if( i>10 ){
694     return 0;
695   }
696   testcase( v-neg==2147483647 );
697   if( v-neg>2147483647 ){
698     return 0;
699   }
700   if( neg ){
701     v = -v;
702   }
703   *pValue = (int)v;
704   return 1;
705 }
706 
707 /*
708 ** Return a 32-bit integer value extracted from a string.  If the
709 ** string is not an integer, just return 0.
710 */
711 int sqlite3Atoi(const char *z){
712   int x = 0;
713   if( z ) sqlite3GetInt32(z, &x);
714   return x;
715 }
716 
717 /*
718 ** The variable-length integer encoding is as follows:
719 **
720 ** KEY:
721 **         A = 0xxxxxxx    7 bits of data and one flag bit
722 **         B = 1xxxxxxx    7 bits of data and one flag bit
723 **         C = xxxxxxxx    8 bits of data
724 **
725 **  7 bits - A
726 ** 14 bits - BA
727 ** 21 bits - BBA
728 ** 28 bits - BBBA
729 ** 35 bits - BBBBA
730 ** 42 bits - BBBBBA
731 ** 49 bits - BBBBBBA
732 ** 56 bits - BBBBBBBA
733 ** 64 bits - BBBBBBBBC
734 */
735 
736 /*
737 ** Write a 64-bit variable-length integer to memory starting at p[0].
738 ** The length of data write will be between 1 and 9 bytes.  The number
739 ** of bytes written is returned.
740 **
741 ** A variable-length integer consists of the lower 7 bits of each byte
742 ** for all bytes that have the 8th bit set and one byte with the 8th
743 ** bit clear.  Except, if we get to the 9th byte, it stores the full
744 ** 8 bits and is the last byte.
745 */
746 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
747   int i, j, n;
748   u8 buf[10];
749   if( v & (((u64)0xff000000)<<32) ){
750     p[8] = (u8)v;
751     v >>= 8;
752     for(i=7; i>=0; i--){
753       p[i] = (u8)((v & 0x7f) | 0x80);
754       v >>= 7;
755     }
756     return 9;
757   }
758   n = 0;
759   do{
760     buf[n++] = (u8)((v & 0x7f) | 0x80);
761     v >>= 7;
762   }while( v!=0 );
763   buf[0] &= 0x7f;
764   assert( n<=9 );
765   for(i=0, j=n-1; j>=0; j--, i++){
766     p[i] = buf[j];
767   }
768   return n;
769 }
770 int sqlite3PutVarint(unsigned char *p, u64 v){
771   if( v<=0x7f ){
772     p[0] = v&0x7f;
773     return 1;
774   }
775   if( v<=0x3fff ){
776     p[0] = ((v>>7)&0x7f)|0x80;
777     p[1] = v&0x7f;
778     return 2;
779   }
780   return putVarint64(p,v);
781 }
782 
783 /*
784 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
785 ** are defined here rather than simply putting the constant expressions
786 ** inline in order to work around bugs in the RVT compiler.
787 **
788 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
789 **
790 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
791 */
792 #define SLOT_2_0     0x001fc07f
793 #define SLOT_4_2_0   0xf01fc07f
794 
795 
796 /*
797 ** Read a 64-bit variable-length integer from memory starting at p[0].
798 ** Return the number of bytes read.  The value is stored in *v.
799 */
800 u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
801   u32 a,b,s;
802 
803   a = *p;
804   /* a: p0 (unmasked) */
805   if (!(a&0x80))
806   {
807     *v = a;
808     return 1;
809   }
810 
811   p++;
812   b = *p;
813   /* b: p1 (unmasked) */
814   if (!(b&0x80))
815   {
816     a &= 0x7f;
817     a = a<<7;
818     a |= b;
819     *v = a;
820     return 2;
821   }
822 
823   /* Verify that constants are precomputed correctly */
824   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
825   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
826 
827   p++;
828   a = a<<14;
829   a |= *p;
830   /* a: p0<<14 | p2 (unmasked) */
831   if (!(a&0x80))
832   {
833     a &= SLOT_2_0;
834     b &= 0x7f;
835     b = b<<7;
836     a |= b;
837     *v = a;
838     return 3;
839   }
840 
841   /* CSE1 from below */
842   a &= SLOT_2_0;
843   p++;
844   b = b<<14;
845   b |= *p;
846   /* b: p1<<14 | p3 (unmasked) */
847   if (!(b&0x80))
848   {
849     b &= SLOT_2_0;
850     /* moved CSE1 up */
851     /* a &= (0x7f<<14)|(0x7f); */
852     a = a<<7;
853     a |= b;
854     *v = a;
855     return 4;
856   }
857 
858   /* a: p0<<14 | p2 (masked) */
859   /* b: p1<<14 | p3 (unmasked) */
860   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
861   /* moved CSE1 up */
862   /* a &= (0x7f<<14)|(0x7f); */
863   b &= SLOT_2_0;
864   s = a;
865   /* s: p0<<14 | p2 (masked) */
866 
867   p++;
868   a = a<<14;
869   a |= *p;
870   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
871   if (!(a&0x80))
872   {
873     /* we can skip these cause they were (effectively) done above
874     ** while calculating s */
875     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
876     /* b &= (0x7f<<14)|(0x7f); */
877     b = b<<7;
878     a |= b;
879     s = s>>18;
880     *v = ((u64)s)<<32 | a;
881     return 5;
882   }
883 
884   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
885   s = s<<7;
886   s |= b;
887   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
888 
889   p++;
890   b = b<<14;
891   b |= *p;
892   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
893   if (!(b&0x80))
894   {
895     /* we can skip this cause it was (effectively) done above in calc'ing s */
896     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
897     a &= SLOT_2_0;
898     a = a<<7;
899     a |= b;
900     s = s>>18;
901     *v = ((u64)s)<<32 | a;
902     return 6;
903   }
904 
905   p++;
906   a = a<<14;
907   a |= *p;
908   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
909   if (!(a&0x80))
910   {
911     a &= SLOT_4_2_0;
912     b &= SLOT_2_0;
913     b = b<<7;
914     a |= b;
915     s = s>>11;
916     *v = ((u64)s)<<32 | a;
917     return 7;
918   }
919 
920   /* CSE2 from below */
921   a &= SLOT_2_0;
922   p++;
923   b = b<<14;
924   b |= *p;
925   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
926   if (!(b&0x80))
927   {
928     b &= SLOT_4_2_0;
929     /* moved CSE2 up */
930     /* a &= (0x7f<<14)|(0x7f); */
931     a = a<<7;
932     a |= b;
933     s = s>>4;
934     *v = ((u64)s)<<32 | a;
935     return 8;
936   }
937 
938   p++;
939   a = a<<15;
940   a |= *p;
941   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
942 
943   /* moved CSE2 up */
944   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
945   b &= SLOT_2_0;
946   b = b<<8;
947   a |= b;
948 
949   s = s<<4;
950   b = p[-4];
951   b &= 0x7f;
952   b = b>>3;
953   s |= b;
954 
955   *v = ((u64)s)<<32 | a;
956 
957   return 9;
958 }
959 
960 /*
961 ** Read a 32-bit variable-length integer from memory starting at p[0].
962 ** Return the number of bytes read.  The value is stored in *v.
963 **
964 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
965 ** integer, then set *v to 0xffffffff.
966 **
967 ** A MACRO version, getVarint32, is provided which inlines the
968 ** single-byte case.  All code should use the MACRO version as
969 ** this function assumes the single-byte case has already been handled.
970 */
971 u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
972   u32 a,b;
973 
974   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
975   ** by the getVarin32() macro */
976   a = *p;
977   /* a: p0 (unmasked) */
978 #ifndef getVarint32
979   if (!(a&0x80))
980   {
981     /* Values between 0 and 127 */
982     *v = a;
983     return 1;
984   }
985 #endif
986 
987   /* The 2-byte case */
988   p++;
989   b = *p;
990   /* b: p1 (unmasked) */
991   if (!(b&0x80))
992   {
993     /* Values between 128 and 16383 */
994     a &= 0x7f;
995     a = a<<7;
996     *v = a | b;
997     return 2;
998   }
999 
1000   /* The 3-byte case */
1001   p++;
1002   a = a<<14;
1003   a |= *p;
1004   /* a: p0<<14 | p2 (unmasked) */
1005   if (!(a&0x80))
1006   {
1007     /* Values between 16384 and 2097151 */
1008     a &= (0x7f<<14)|(0x7f);
1009     b &= 0x7f;
1010     b = b<<7;
1011     *v = a | b;
1012     return 3;
1013   }
1014 
1015   /* A 32-bit varint is used to store size information in btrees.
1016   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
1017   ** A 3-byte varint is sufficient, for example, to record the size
1018   ** of a 1048569-byte BLOB or string.
1019   **
1020   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
1021   ** rare larger cases can be handled by the slower 64-bit varint
1022   ** routine.
1023   */
1024 #if 1
1025   {
1026     u64 v64;
1027     u8 n;
1028 
1029     p -= 2;
1030     n = sqlite3GetVarint(p, &v64);
1031     assert( n>3 && n<=9 );
1032     if( (v64 & SQLITE_MAX_U32)!=v64 ){
1033       *v = 0xffffffff;
1034     }else{
1035       *v = (u32)v64;
1036     }
1037     return n;
1038   }
1039 
1040 #else
1041   /* For following code (kept for historical record only) shows an
1042   ** unrolling for the 3- and 4-byte varint cases.  This code is
1043   ** slightly faster, but it is also larger and much harder to test.
1044   */
1045   p++;
1046   b = b<<14;
1047   b |= *p;
1048   /* b: p1<<14 | p3 (unmasked) */
1049   if (!(b&0x80))
1050   {
1051     /* Values between 2097152 and 268435455 */
1052     b &= (0x7f<<14)|(0x7f);
1053     a &= (0x7f<<14)|(0x7f);
1054     a = a<<7;
1055     *v = a | b;
1056     return 4;
1057   }
1058 
1059   p++;
1060   a = a<<14;
1061   a |= *p;
1062   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1063   if (!(a&0x80))
1064   {
1065     /* Values  between 268435456 and 34359738367 */
1066     a &= SLOT_4_2_0;
1067     b &= SLOT_4_2_0;
1068     b = b<<7;
1069     *v = a | b;
1070     return 5;
1071   }
1072 
1073   /* We can only reach this point when reading a corrupt database
1074   ** file.  In that case we are not in any hurry.  Use the (relatively
1075   ** slow) general-purpose sqlite3GetVarint() routine to extract the
1076   ** value. */
1077   {
1078     u64 v64;
1079     u8 n;
1080 
1081     p -= 4;
1082     n = sqlite3GetVarint(p, &v64);
1083     assert( n>5 && n<=9 );
1084     *v = (u32)v64;
1085     return n;
1086   }
1087 #endif
1088 }
1089 
1090 /*
1091 ** Return the number of bytes that will be needed to store the given
1092 ** 64-bit integer.
1093 */
1094 int sqlite3VarintLen(u64 v){
1095   int i;
1096   for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
1097   return i;
1098 }
1099 
1100 
1101 /*
1102 ** Read or write a four-byte big-endian integer value.
1103 */
1104 u32 sqlite3Get4byte(const u8 *p){
1105 #if SQLITE_BYTEORDER==4321
1106   u32 x;
1107   memcpy(&x,p,4);
1108   return x;
1109 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1110     && defined(__GNUC__) && GCC_VERSION>=4003000
1111   u32 x;
1112   memcpy(&x,p,4);
1113   return __builtin_bswap32(x);
1114 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1115     && defined(_MSC_VER) && _MSC_VER>=1300
1116   u32 x;
1117   memcpy(&x,p,4);
1118   return _byteswap_ulong(x);
1119 #else
1120   testcase( p[0]&0x80 );
1121   return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
1122 #endif
1123 }
1124 void sqlite3Put4byte(unsigned char *p, u32 v){
1125 #if SQLITE_BYTEORDER==4321
1126   memcpy(p,&v,4);
1127 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1128     && defined(__GNUC__) && GCC_VERSION>=4003000
1129   u32 x = __builtin_bswap32(v);
1130   memcpy(p,&x,4);
1131 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1132     && defined(_MSC_VER) && _MSC_VER>=1300
1133   u32 x = _byteswap_ulong(v);
1134   memcpy(p,&x,4);
1135 #else
1136   p[0] = (u8)(v>>24);
1137   p[1] = (u8)(v>>16);
1138   p[2] = (u8)(v>>8);
1139   p[3] = (u8)v;
1140 #endif
1141 }
1142 
1143 
1144 
1145 /*
1146 ** Translate a single byte of Hex into an integer.
1147 ** This routine only works if h really is a valid hexadecimal
1148 ** character:  0..9a..fA..F
1149 */
1150 u8 sqlite3HexToInt(int h){
1151   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
1152 #ifdef SQLITE_ASCII
1153   h += 9*(1&(h>>6));
1154 #endif
1155 #ifdef SQLITE_EBCDIC
1156   h += 9*(1&~(h>>4));
1157 #endif
1158   return (u8)(h & 0xf);
1159 }
1160 
1161 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
1162 /*
1163 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
1164 ** value.  Return a pointer to its binary value.  Space to hold the
1165 ** binary value has been obtained from malloc and must be freed by
1166 ** the calling routine.
1167 */
1168 void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
1169   char *zBlob;
1170   int i;
1171 
1172   zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
1173   n--;
1174   if( zBlob ){
1175     for(i=0; i<n; i+=2){
1176       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
1177     }
1178     zBlob[i/2] = 0;
1179   }
1180   return zBlob;
1181 }
1182 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
1183 
1184 /*
1185 ** Log an error that is an API call on a connection pointer that should
1186 ** not have been used.  The "type" of connection pointer is given as the
1187 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
1188 */
1189 static void logBadConnection(const char *zType){
1190   sqlite3_log(SQLITE_MISUSE,
1191      "API call with %s database connection pointer",
1192      zType
1193   );
1194 }
1195 
1196 /*
1197 ** Check to make sure we have a valid db pointer.  This test is not
1198 ** foolproof but it does provide some measure of protection against
1199 ** misuse of the interface such as passing in db pointers that are
1200 ** NULL or which have been previously closed.  If this routine returns
1201 ** 1 it means that the db pointer is valid and 0 if it should not be
1202 ** dereferenced for any reason.  The calling function should invoke
1203 ** SQLITE_MISUSE immediately.
1204 **
1205 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
1206 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
1207 ** open properly and is not fit for general use but which can be
1208 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
1209 */
1210 int sqlite3SafetyCheckOk(sqlite3 *db){
1211   u32 magic;
1212   if( db==0 ){
1213     logBadConnection("NULL");
1214     return 0;
1215   }
1216   magic = db->magic;
1217   if( magic!=SQLITE_MAGIC_OPEN ){
1218     if( sqlite3SafetyCheckSickOrOk(db) ){
1219       testcase( sqlite3GlobalConfig.xLog!=0 );
1220       logBadConnection("unopened");
1221     }
1222     return 0;
1223   }else{
1224     return 1;
1225   }
1226 }
1227 int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
1228   u32 magic;
1229   magic = db->magic;
1230   if( magic!=SQLITE_MAGIC_SICK &&
1231       magic!=SQLITE_MAGIC_OPEN &&
1232       magic!=SQLITE_MAGIC_BUSY ){
1233     testcase( sqlite3GlobalConfig.xLog!=0 );
1234     logBadConnection("invalid");
1235     return 0;
1236   }else{
1237     return 1;
1238   }
1239 }
1240 
1241 /*
1242 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
1243 ** the other 64-bit signed integer at *pA and store the result in *pA.
1244 ** Return 0 on success.  Or if the operation would have resulted in an
1245 ** overflow, leave *pA unchanged and return 1.
1246 */
1247 int sqlite3AddInt64(i64 *pA, i64 iB){
1248   i64 iA = *pA;
1249   testcase( iA==0 ); testcase( iA==1 );
1250   testcase( iB==-1 ); testcase( iB==0 );
1251   if( iB>=0 ){
1252     testcase( iA>0 && LARGEST_INT64 - iA == iB );
1253     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
1254     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
1255   }else{
1256     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
1257     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
1258     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
1259   }
1260   *pA += iB;
1261   return 0;
1262 }
1263 int sqlite3SubInt64(i64 *pA, i64 iB){
1264   testcase( iB==SMALLEST_INT64+1 );
1265   if( iB==SMALLEST_INT64 ){
1266     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
1267     if( (*pA)>=0 ) return 1;
1268     *pA -= iB;
1269     return 0;
1270   }else{
1271     return sqlite3AddInt64(pA, -iB);
1272   }
1273 }
1274 #define TWOPOWER32 (((i64)1)<<32)
1275 #define TWOPOWER31 (((i64)1)<<31)
1276 int sqlite3MulInt64(i64 *pA, i64 iB){
1277   i64 iA = *pA;
1278   i64 iA1, iA0, iB1, iB0, r;
1279 
1280   iA1 = iA/TWOPOWER32;
1281   iA0 = iA % TWOPOWER32;
1282   iB1 = iB/TWOPOWER32;
1283   iB0 = iB % TWOPOWER32;
1284   if( iA1==0 ){
1285     if( iB1==0 ){
1286       *pA *= iB;
1287       return 0;
1288     }
1289     r = iA0*iB1;
1290   }else if( iB1==0 ){
1291     r = iA1*iB0;
1292   }else{
1293     /* If both iA1 and iB1 are non-zero, overflow will result */
1294     return 1;
1295   }
1296   testcase( r==(-TWOPOWER31)-1 );
1297   testcase( r==(-TWOPOWER31) );
1298   testcase( r==TWOPOWER31 );
1299   testcase( r==TWOPOWER31-1 );
1300   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
1301   r *= TWOPOWER32;
1302   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
1303   *pA = r;
1304   return 0;
1305 }
1306 
1307 /*
1308 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or
1309 ** if the integer has a value of -2147483648, return +2147483647
1310 */
1311 int sqlite3AbsInt32(int x){
1312   if( x>=0 ) return x;
1313   if( x==(int)0x80000000 ) return 0x7fffffff;
1314   return -x;
1315 }
1316 
1317 #ifdef SQLITE_ENABLE_8_3_NAMES
1318 /*
1319 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
1320 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
1321 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
1322 ** three characters, then shorten the suffix on z[] to be the last three
1323 ** characters of the original suffix.
1324 **
1325 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
1326 ** do the suffix shortening regardless of URI parameter.
1327 **
1328 ** Examples:
1329 **
1330 **     test.db-journal    =>   test.nal
1331 **     test.db-wal        =>   test.wal
1332 **     test.db-shm        =>   test.shm
1333 **     test.db-mj7f3319fa =>   test.9fa
1334 */
1335 void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
1336 #if SQLITE_ENABLE_8_3_NAMES<2
1337   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
1338 #endif
1339   {
1340     int i, sz;
1341     sz = sqlite3Strlen30(z);
1342     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
1343     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
1344   }
1345 }
1346 #endif
1347 
1348 /*
1349 ** Find (an approximate) sum of two LogEst values.  This computation is
1350 ** not a simple "+" operator because LogEst is stored as a logarithmic
1351 ** value.
1352 **
1353 */
1354 LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
1355   static const unsigned char x[] = {
1356      10, 10,                         /* 0,1 */
1357       9, 9,                          /* 2,3 */
1358       8, 8,                          /* 4,5 */
1359       7, 7, 7,                       /* 6,7,8 */
1360       6, 6, 6,                       /* 9,10,11 */
1361       5, 5, 5,                       /* 12-14 */
1362       4, 4, 4, 4,                    /* 15-18 */
1363       3, 3, 3, 3, 3, 3,              /* 19-24 */
1364       2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
1365   };
1366   if( a>=b ){
1367     if( a>b+49 ) return a;
1368     if( a>b+31 ) return a+1;
1369     return a+x[a-b];
1370   }else{
1371     if( b>a+49 ) return b;
1372     if( b>a+31 ) return b+1;
1373     return b+x[b-a];
1374   }
1375 }
1376 
1377 /*
1378 ** Convert an integer into a LogEst.  In other words, compute an
1379 ** approximation for 10*log2(x).
1380 */
1381 LogEst sqlite3LogEst(u64 x){
1382   static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1383   LogEst y = 40;
1384   if( x<8 ){
1385     if( x<2 ) return 0;
1386     while( x<8 ){  y -= 10; x <<= 1; }
1387   }else{
1388     while( x>255 ){ y += 40; x >>= 4; }
1389     while( x>15 ){  y += 10; x >>= 1; }
1390   }
1391   return a[x&7] + y - 10;
1392 }
1393 
1394 #ifndef SQLITE_OMIT_VIRTUALTABLE
1395 /*
1396 ** Convert a double into a LogEst
1397 ** In other words, compute an approximation for 10*log2(x).
1398 */
1399 LogEst sqlite3LogEstFromDouble(double x){
1400   u64 a;
1401   LogEst e;
1402   assert( sizeof(x)==8 && sizeof(a)==8 );
1403   if( x<=1 ) return 0;
1404   if( x<=2000000000 ) return sqlite3LogEst((u64)x);
1405   memcpy(&a, &x, 8);
1406   e = (a>>52) - 1022;
1407   return e*10;
1408 }
1409 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1410 
1411 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
1412     defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
1413     defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
1414 /*
1415 ** Convert a LogEst into an integer.
1416 **
1417 ** Note that this routine is only used when one or more of various
1418 ** non-standard compile-time options is enabled.
1419 */
1420 u64 sqlite3LogEstToInt(LogEst x){
1421   u64 n;
1422   if( x<10 ) return 1;
1423   n = x%10;
1424   x /= 10;
1425   if( n>=5 ) n -= 2;
1426   else if( n>=1 ) n -= 1;
1427 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
1428     defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
1429   if( x>60 ) return (u64)LARGEST_INT64;
1430 #else
1431   /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
1432   ** possible to this routine is 310, resulting in a maximum x of 31 */
1433   assert( x<=60 );
1434 #endif
1435   return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
1436 }
1437 #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
1438