xref: /sqlite-3.40.0/src/util.c (revision 60176fa9)
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 #ifdef 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 int dummy = 0;
30   dummy += x;
31 }
32 #endif
33 
34 #ifndef SQLITE_OMIT_FLOATING_POINT
35 /*
36 ** Return true if the floating point value is Not a Number (NaN).
37 **
38 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
39 ** Otherwise, we have our own implementation that works on most systems.
40 */
41 int sqlite3IsNaN(double x){
42   int rc;   /* The value return */
43 #if !defined(SQLITE_HAVE_ISNAN)
44   /*
45   ** Systems that support the isnan() library function should probably
46   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
47   ** found that many systems do not have a working isnan() function so
48   ** this implementation is provided as an alternative.
49   **
50   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
51   ** On the other hand, the use of -ffast-math comes with the following
52   ** warning:
53   **
54   **      This option [-ffast-math] should never be turned on by any
55   **      -O option since it can result in incorrect output for programs
56   **      which depend on an exact implementation of IEEE or ISO
57   **      rules/specifications for math functions.
58   **
59   ** Under MSVC, this NaN test may fail if compiled with a floating-
60   ** point precision mode other than /fp:precise.  From the MSDN
61   ** documentation:
62   **
63   **      The compiler [with /fp:precise] will properly handle comparisons
64   **      involving NaN. For example, x != x evaluates to true if x is NaN
65   **      ...
66   */
67 #ifdef __FAST_MATH__
68 # error SQLite will not work correctly with the -ffast-math option of GCC.
69 #endif
70   volatile double y = x;
71   volatile double z = y;
72   rc = (y!=z);
73 #else  /* if defined(SQLITE_HAVE_ISNAN) */
74   rc = isnan(x);
75 #endif /* SQLITE_HAVE_ISNAN */
76   testcase( rc );
77   return rc;
78 }
79 #endif /* SQLITE_OMIT_FLOATING_POINT */
80 
81 /*
82 ** Compute a string length that is limited to what can be stored in
83 ** lower 30 bits of a 32-bit signed integer.
84 **
85 ** The value returned will never be negative.  Nor will it ever be greater
86 ** than the actual length of the string.  For very long strings (greater
87 ** than 1GiB) the value returned might be less than the true string length.
88 */
89 int sqlite3Strlen30(const char *z){
90   const char *z2 = z;
91   if( z==0 ) return 0;
92   while( *z2 ){ z2++; }
93   return 0x3fffffff & (int)(z2 - z);
94 }
95 
96 /*
97 ** Set the most recent error code and error string for the sqlite
98 ** handle "db". The error code is set to "err_code".
99 **
100 ** If it is not NULL, string zFormat specifies the format of the
101 ** error string in the style of the printf functions: The following
102 ** format characters are allowed:
103 **
104 **      %s      Insert a string
105 **      %z      A string that should be freed after use
106 **      %d      Insert an integer
107 **      %T      Insert a token
108 **      %S      Insert the first element of a SrcList
109 **
110 ** zFormat and any string tokens that follow it are assumed to be
111 ** encoded in UTF-8.
112 **
113 ** To clear the most recent error for sqlite handle "db", sqlite3Error
114 ** should be called with err_code set to SQLITE_OK and zFormat set
115 ** to NULL.
116 */
117 void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
118   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
119     db->errCode = err_code;
120     if( zFormat ){
121       char *z;
122       va_list ap;
123       va_start(ap, zFormat);
124       z = sqlite3VMPrintf(db, zFormat, ap);
125       va_end(ap);
126       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
127     }else{
128       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
129     }
130   }
131 }
132 
133 /*
134 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
135 ** The following formatting 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 ** This function should be used to report any error that occurs whilst
144 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
145 ** last thing the sqlite3_prepare() function does is copy the error
146 ** stored by this function into the database handle using sqlite3Error().
147 ** Function sqlite3Error() should be used during statement execution
148 ** (sqlite3_step() etc.).
149 */
150 void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
151   char *zMsg;
152   va_list ap;
153   sqlite3 *db = pParse->db;
154   va_start(ap, zFormat);
155   zMsg = sqlite3VMPrintf(db, zFormat, ap);
156   va_end(ap);
157   if( db->suppressErr ){
158     sqlite3DbFree(db, zMsg);
159   }else{
160     pParse->nErr++;
161     sqlite3DbFree(db, pParse->zErrMsg);
162     pParse->zErrMsg = zMsg;
163     pParse->rc = SQLITE_ERROR;
164   }
165 }
166 
167 /*
168 ** Convert an SQL-style quoted string into a normal string by removing
169 ** the quote characters.  The conversion is done in-place.  If the
170 ** input does not begin with a quote character, then this routine
171 ** is a no-op.
172 **
173 ** The input string must be zero-terminated.  A new zero-terminator
174 ** is added to the dequoted string.
175 **
176 ** The return value is -1 if no dequoting occurs or the length of the
177 ** dequoted string, exclusive of the zero terminator, if dequoting does
178 ** occur.
179 **
180 ** 2002-Feb-14: This routine is extended to remove MS-Access style
181 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
182 ** "a-b-c".
183 */
184 int sqlite3Dequote(char *z){
185   char quote;
186   int i, j;
187   if( z==0 ) return -1;
188   quote = z[0];
189   switch( quote ){
190     case '\'':  break;
191     case '"':   break;
192     case '`':   break;                /* For MySQL compatibility */
193     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
194     default:    return -1;
195   }
196   for(i=1, j=0; ALWAYS(z[i]); i++){
197     if( z[i]==quote ){
198       if( z[i+1]==quote ){
199         z[j++] = quote;
200         i++;
201       }else{
202         break;
203       }
204     }else{
205       z[j++] = z[i];
206     }
207   }
208   z[j] = 0;
209   return j;
210 }
211 
212 /* Convenient short-hand */
213 #define UpperToLower sqlite3UpperToLower
214 
215 /*
216 ** Some systems have stricmp().  Others have strcasecmp().  Because
217 ** there is no consistency, we will define our own.
218 */
219 int sqlite3StrICmp(const char *zLeft, const char *zRight){
220   register unsigned char *a, *b;
221   a = (unsigned char *)zLeft;
222   b = (unsigned char *)zRight;
223   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
224   return UpperToLower[*a] - UpperToLower[*b];
225 }
226 int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
227   register unsigned char *a, *b;
228   a = (unsigned char *)zLeft;
229   b = (unsigned char *)zRight;
230   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
231   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
232 }
233 
234 /*
235 ** Return TRUE if z is a pure numeric string.  Return FALSE and leave
236 ** *realnum unchanged if the string contains any character which is not
237 ** part of a number.
238 **
239 ** If the string is pure numeric, set *realnum to TRUE if the string
240 ** contains the '.' character or an "E+000" style exponentiation suffix.
241 ** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
242 ** false does not mean that the number can be successfully converted into
243 ** an integer - it might be too big.
244 **
245 ** An empty string is considered non-numeric.
246 */
247 int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
248   int incr = (enc==SQLITE_UTF8?1:2);
249   if( enc==SQLITE_UTF16BE ) z++;
250   if( *z=='-' || *z=='+' ) z += incr;
251   if( !sqlite3Isdigit(*z) ){
252     return 0;
253   }
254   z += incr;
255   *realnum = 0;
256   while( sqlite3Isdigit(*z) ){ z += incr; }
257 #ifndef SQLITE_OMIT_FLOATING_POINT
258   if( *z=='.' ){
259     z += incr;
260     if( !sqlite3Isdigit(*z) ) return 0;
261     while( sqlite3Isdigit(*z) ){ z += incr; }
262     *realnum = 1;
263   }
264   if( *z=='e' || *z=='E' ){
265     z += incr;
266     if( *z=='+' || *z=='-' ) z += incr;
267     if( !sqlite3Isdigit(*z) ) return 0;
268     while( sqlite3Isdigit(*z) ){ z += incr; }
269     *realnum = 1;
270   }
271 #endif
272   return *z==0;
273 }
274 
275 /*
276 ** The string z[] is an ASCII representation of a real number.
277 ** Convert this string to a double.
278 **
279 ** This routine assumes that z[] really is a valid number.  If it
280 ** is not, the result is undefined.
281 **
282 ** This routine is used instead of the library atof() function because
283 ** the library atof() might want to use "," as the decimal point instead
284 ** of "." depending on how locale is set.  But that would cause problems
285 ** for SQL.  So this routine always uses "." regardless of locale.
286 */
287 int sqlite3AtoF(const char *z, double *pResult){
288 #ifndef SQLITE_OMIT_FLOATING_POINT
289   const char *zBegin = z;
290   /* sign * significand * (10 ^ (esign * exponent)) */
291   int sign = 1;   /* sign of significand */
292   i64 s = 0;      /* significand */
293   int d = 0;      /* adjust exponent for shifting decimal point */
294   int esign = 1;  /* sign of exponent */
295   int e = 0;      /* exponent */
296   double result;
297   int nDigits = 0;
298 
299   /* skip leading spaces */
300   while( sqlite3Isspace(*z) ) z++;
301   /* get sign of significand */
302   if( *z=='-' ){
303     sign = -1;
304     z++;
305   }else if( *z=='+' ){
306     z++;
307   }
308   /* skip leading zeroes */
309   while( z[0]=='0' ) z++, nDigits++;
310 
311   /* copy max significant digits to significand */
312   while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
313     s = s*10 + (*z - '0');
314     z++, nDigits++;
315   }
316   /* skip non-significant significand digits
317   ** (increase exponent by d to shift decimal left) */
318   while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
319 
320   /* if decimal point is present */
321   if( *z=='.' ){
322     z++;
323     /* copy digits from after decimal to significand
324     ** (decrease exponent by d to shift decimal right) */
325     while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
326       s = s*10 + (*z - '0');
327       z++, nDigits++, d--;
328     }
329     /* skip non-significant digits */
330     while( sqlite3Isdigit(*z) ) z++, nDigits++;
331   }
332 
333   /* if exponent is present */
334   if( *z=='e' || *z=='E' ){
335     z++;
336     /* get sign of exponent */
337     if( *z=='-' ){
338       esign = -1;
339       z++;
340     }else if( *z=='+' ){
341       z++;
342     }
343     /* copy digits to exponent */
344     while( sqlite3Isdigit(*z) ){
345       e = e*10 + (*z - '0');
346       z++;
347     }
348   }
349 
350   /* adjust exponent by d, and update sign */
351   e = (e*esign) + d;
352   if( e<0 ) {
353     esign = -1;
354     e *= -1;
355   } else {
356     esign = 1;
357   }
358 
359   /* if 0 significand */
360   if( !s ) {
361     /* In the IEEE 754 standard, zero is signed.
362     ** Add the sign if we've seen at least one digit */
363     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
364   } else {
365     /* attempt to reduce exponent */
366     if( esign>0 ){
367       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
368     }else{
369       while( !(s%10) && e>0 ) e--,s/=10;
370     }
371 
372     /* adjust the sign of significand */
373     s = sign<0 ? -s : s;
374 
375     /* if exponent, scale significand as appropriate
376     ** and store in result. */
377     if( e ){
378       double scale = 1.0;
379       /* attempt to handle extremely small/large numbers better */
380       if( e>307 && e<342 ){
381         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
382         if( esign<0 ){
383           result = s / scale;
384           result /= 1.0e+308;
385         }else{
386           result = s * scale;
387           result *= 1.0e+308;
388         }
389       }else{
390         /* 1.0e+22 is the largest power of 10 than can be
391         ** represented exactly. */
392         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
393         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
394         if( esign<0 ){
395           result = s / scale;
396         }else{
397           result = s * scale;
398         }
399       }
400     } else {
401       result = (double)s;
402     }
403   }
404 
405   /* store the result */
406   *pResult = result;
407 
408   /* return number of characters used */
409   return (int)(z - zBegin);
410 #else
411   return sqlite3Atoi64(z, pResult);
412 #endif /* SQLITE_OMIT_FLOATING_POINT */
413 }
414 
415 /*
416 ** Compare the 19-character string zNum against the text representation
417 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
418 ** if zNum is less than, equal to, or greater than the string.
419 **
420 ** Unlike memcmp() this routine is guaranteed to return the difference
421 ** in the values of the last digit if the only difference is in the
422 ** last digit.  So, for example,
423 **
424 **      compare2pow63("9223372036854775800")
425 **
426 ** will return -8.
427 */
428 static int compare2pow63(const char *zNum){
429   int c;
430   c = memcmp(zNum,"922337203685477580",18)*10;
431   if( c==0 ){
432     c = zNum[18] - '8';
433     testcase( c==(-1) );
434     testcase( c==0 );
435     testcase( c==(+1) );
436   }
437   return c;
438 }
439 
440 
441 /*
442 ** Return TRUE if zNum is a 64-bit signed integer and write
443 ** the value of the integer into *pNum.  If zNum is not an integer
444 ** or is an integer that is too large to be expressed with 64 bits,
445 ** then return false.
446 **
447 ** When this routine was originally written it dealt with only
448 ** 32-bit numbers.  At that time, it was much faster than the
449 ** atoi() library routine in RedHat 7.2.
450 */
451 int sqlite3Atoi64(const char *zNum, i64 *pNum){
452   i64 v = 0;
453   int neg;
454   int i, c;
455   const char *zStart;
456   while( sqlite3Isspace(*zNum) ) zNum++;
457   if( *zNum=='-' ){
458     neg = 1;
459     zNum++;
460   }else if( *zNum=='+' ){
461     neg = 0;
462     zNum++;
463   }else{
464     neg = 0;
465   }
466   zStart = zNum;
467   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
468   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
469     v = v*10 + c - '0';
470   }
471   *pNum = neg ? -v : v;
472   testcase( i==18 );
473   testcase( i==19 );
474   testcase( i==20 );
475   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
476     /* zNum is empty or contains non-numeric text or is longer
477     ** than 19 digits (thus guaranting that it is too large) */
478     return 0;
479   }else if( i<19 ){
480     /* Less than 19 digits, so we know that it fits in 64 bits */
481     return 1;
482   }else{
483     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
484     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
485     ** is 2^63. */
486     return compare2pow63(zNum)<neg;
487   }
488 }
489 
490 /*
491 ** The string zNum represents an unsigned integer.  The zNum string
492 ** consists of one or more digit characters and is terminated by
493 ** a zero character.  Any stray characters in zNum result in undefined
494 ** behavior.
495 **
496 ** If the unsigned integer that zNum represents will fit in a
497 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
498 **
499 ** If the negFlag parameter is true, that means that zNum really represents
500 ** a negative number.  (The leading "-" is omitted from zNum.)  This
501 ** parameter is needed to determine a boundary case.  A string
502 ** of "9223373036854775808" returns false if negFlag is false or true
503 ** if negFlag is true.
504 **
505 ** Leading zeros are ignored.
506 */
507 int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
508   int i;
509   int neg = 0;
510 
511   assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
512 
513   if( negFlag ) neg = 1-neg;
514   while( *zNum=='0' ){
515     zNum++;   /* Skip leading zeros.  Ticket #2454 */
516   }
517   for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
518   testcase( i==18 );
519   testcase( i==19 );
520   testcase( i==20 );
521   if( i<19 ){
522     /* Guaranteed to fit if less than 19 digits */
523     return 1;
524   }else if( i>19 ){
525     /* Guaranteed to be too big if greater than 19 digits */
526     return 0;
527   }else{
528     /* Compare against 2^63. */
529     return compare2pow63(zNum)<neg;
530   }
531 }
532 
533 /*
534 ** If zNum represents an integer that will fit in 32-bits, then set
535 ** *pValue to that integer and return true.  Otherwise return false.
536 **
537 ** Any non-numeric characters that following zNum are ignored.
538 ** This is different from sqlite3Atoi64() which requires the
539 ** input number to be zero-terminated.
540 */
541 int sqlite3GetInt32(const char *zNum, int *pValue){
542   sqlite_int64 v = 0;
543   int i, c;
544   int neg = 0;
545   if( zNum[0]=='-' ){
546     neg = 1;
547     zNum++;
548   }else if( zNum[0]=='+' ){
549     zNum++;
550   }
551   while( zNum[0]=='0' ) zNum++;
552   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
553     v = v*10 + c;
554   }
555 
556   /* The longest decimal representation of a 32 bit integer is 10 digits:
557   **
558   **             1234567890
559   **     2^31 -> 2147483648
560   */
561   testcase( i==10 );
562   if( i>10 ){
563     return 0;
564   }
565   testcase( v-neg==2147483647 );
566   if( v-neg>2147483647 ){
567     return 0;
568   }
569   if( neg ){
570     v = -v;
571   }
572   *pValue = (int)v;
573   return 1;
574 }
575 
576 /*
577 ** The variable-length integer encoding is as follows:
578 **
579 ** KEY:
580 **         A = 0xxxxxxx    7 bits of data and one flag bit
581 **         B = 1xxxxxxx    7 bits of data and one flag bit
582 **         C = xxxxxxxx    8 bits of data
583 **
584 **  7 bits - A
585 ** 14 bits - BA
586 ** 21 bits - BBA
587 ** 28 bits - BBBA
588 ** 35 bits - BBBBA
589 ** 42 bits - BBBBBA
590 ** 49 bits - BBBBBBA
591 ** 56 bits - BBBBBBBA
592 ** 64 bits - BBBBBBBBC
593 */
594 
595 /*
596 ** Write a 64-bit variable-length integer to memory starting at p[0].
597 ** The length of data write will be between 1 and 9 bytes.  The number
598 ** of bytes written is returned.
599 **
600 ** A variable-length integer consists of the lower 7 bits of each byte
601 ** for all bytes that have the 8th bit set and one byte with the 8th
602 ** bit clear.  Except, if we get to the 9th byte, it stores the full
603 ** 8 bits and is the last byte.
604 */
605 int sqlite3PutVarint(unsigned char *p, u64 v){
606   int i, j, n;
607   u8 buf[10];
608   if( v & (((u64)0xff000000)<<32) ){
609     p[8] = (u8)v;
610     v >>= 8;
611     for(i=7; i>=0; i--){
612       p[i] = (u8)((v & 0x7f) | 0x80);
613       v >>= 7;
614     }
615     return 9;
616   }
617   n = 0;
618   do{
619     buf[n++] = (u8)((v & 0x7f) | 0x80);
620     v >>= 7;
621   }while( v!=0 );
622   buf[0] &= 0x7f;
623   assert( n<=9 );
624   for(i=0, j=n-1; j>=0; j--, i++){
625     p[i] = buf[j];
626   }
627   return n;
628 }
629 
630 /*
631 ** This routine is a faster version of sqlite3PutVarint() that only
632 ** works for 32-bit positive integers and which is optimized for
633 ** the common case of small integers.  A MACRO version, putVarint32,
634 ** is provided which inlines the single-byte case.  All code should use
635 ** the MACRO version as this function assumes the single-byte case has
636 ** already been handled.
637 */
638 int sqlite3PutVarint32(unsigned char *p, u32 v){
639 #ifndef putVarint32
640   if( (v & ~0x7f)==0 ){
641     p[0] = v;
642     return 1;
643   }
644 #endif
645   if( (v & ~0x3fff)==0 ){
646     p[0] = (u8)((v>>7) | 0x80);
647     p[1] = (u8)(v & 0x7f);
648     return 2;
649   }
650   return sqlite3PutVarint(p, v);
651 }
652 
653 /*
654 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
655 ** are defined here rather than simply putting the constant expressions
656 ** inline in order to work around bugs in the RVT compiler.
657 **
658 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
659 **
660 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
661 */
662 #define SLOT_2_0     0x001fc07f
663 #define SLOT_4_2_0   0xf01fc07f
664 
665 
666 /*
667 ** Read a 64-bit variable-length integer from memory starting at p[0].
668 ** Return the number of bytes read.  The value is stored in *v.
669 */
670 u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
671   u32 a,b,s;
672 
673   a = *p;
674   /* a: p0 (unmasked) */
675   if (!(a&0x80))
676   {
677     *v = a;
678     return 1;
679   }
680 
681   p++;
682   b = *p;
683   /* b: p1 (unmasked) */
684   if (!(b&0x80))
685   {
686     a &= 0x7f;
687     a = a<<7;
688     a |= b;
689     *v = a;
690     return 2;
691   }
692 
693   /* Verify that constants are precomputed correctly */
694   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
695   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
696 
697   p++;
698   a = a<<14;
699   a |= *p;
700   /* a: p0<<14 | p2 (unmasked) */
701   if (!(a&0x80))
702   {
703     a &= SLOT_2_0;
704     b &= 0x7f;
705     b = b<<7;
706     a |= b;
707     *v = a;
708     return 3;
709   }
710 
711   /* CSE1 from below */
712   a &= SLOT_2_0;
713   p++;
714   b = b<<14;
715   b |= *p;
716   /* b: p1<<14 | p3 (unmasked) */
717   if (!(b&0x80))
718   {
719     b &= SLOT_2_0;
720     /* moved CSE1 up */
721     /* a &= (0x7f<<14)|(0x7f); */
722     a = a<<7;
723     a |= b;
724     *v = a;
725     return 4;
726   }
727 
728   /* a: p0<<14 | p2 (masked) */
729   /* b: p1<<14 | p3 (unmasked) */
730   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
731   /* moved CSE1 up */
732   /* a &= (0x7f<<14)|(0x7f); */
733   b &= SLOT_2_0;
734   s = a;
735   /* s: p0<<14 | p2 (masked) */
736 
737   p++;
738   a = a<<14;
739   a |= *p;
740   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
741   if (!(a&0x80))
742   {
743     /* we can skip these cause they were (effectively) done above in calc'ing s */
744     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
745     /* b &= (0x7f<<14)|(0x7f); */
746     b = b<<7;
747     a |= b;
748     s = s>>18;
749     *v = ((u64)s)<<32 | a;
750     return 5;
751   }
752 
753   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
754   s = s<<7;
755   s |= b;
756   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
757 
758   p++;
759   b = b<<14;
760   b |= *p;
761   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
762   if (!(b&0x80))
763   {
764     /* we can skip this cause it was (effectively) done above in calc'ing s */
765     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
766     a &= SLOT_2_0;
767     a = a<<7;
768     a |= b;
769     s = s>>18;
770     *v = ((u64)s)<<32 | a;
771     return 6;
772   }
773 
774   p++;
775   a = a<<14;
776   a |= *p;
777   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
778   if (!(a&0x80))
779   {
780     a &= SLOT_4_2_0;
781     b &= SLOT_2_0;
782     b = b<<7;
783     a |= b;
784     s = s>>11;
785     *v = ((u64)s)<<32 | a;
786     return 7;
787   }
788 
789   /* CSE2 from below */
790   a &= SLOT_2_0;
791   p++;
792   b = b<<14;
793   b |= *p;
794   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
795   if (!(b&0x80))
796   {
797     b &= SLOT_4_2_0;
798     /* moved CSE2 up */
799     /* a &= (0x7f<<14)|(0x7f); */
800     a = a<<7;
801     a |= b;
802     s = s>>4;
803     *v = ((u64)s)<<32 | a;
804     return 8;
805   }
806 
807   p++;
808   a = a<<15;
809   a |= *p;
810   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
811 
812   /* moved CSE2 up */
813   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
814   b &= SLOT_2_0;
815   b = b<<8;
816   a |= b;
817 
818   s = s<<4;
819   b = p[-4];
820   b &= 0x7f;
821   b = b>>3;
822   s |= b;
823 
824   *v = ((u64)s)<<32 | a;
825 
826   return 9;
827 }
828 
829 /*
830 ** Read a 32-bit variable-length integer from memory starting at p[0].
831 ** Return the number of bytes read.  The value is stored in *v.
832 **
833 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
834 ** integer, then set *v to 0xffffffff.
835 **
836 ** A MACRO version, getVarint32, is provided which inlines the
837 ** single-byte case.  All code should use the MACRO version as
838 ** this function assumes the single-byte case has already been handled.
839 */
840 u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
841   u32 a,b;
842 
843   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
844   ** by the getVarin32() macro */
845   a = *p;
846   /* a: p0 (unmasked) */
847 #ifndef getVarint32
848   if (!(a&0x80))
849   {
850     /* Values between 0 and 127 */
851     *v = a;
852     return 1;
853   }
854 #endif
855 
856   /* The 2-byte case */
857   p++;
858   b = *p;
859   /* b: p1 (unmasked) */
860   if (!(b&0x80))
861   {
862     /* Values between 128 and 16383 */
863     a &= 0x7f;
864     a = a<<7;
865     *v = a | b;
866     return 2;
867   }
868 
869   /* The 3-byte case */
870   p++;
871   a = a<<14;
872   a |= *p;
873   /* a: p0<<14 | p2 (unmasked) */
874   if (!(a&0x80))
875   {
876     /* Values between 16384 and 2097151 */
877     a &= (0x7f<<14)|(0x7f);
878     b &= 0x7f;
879     b = b<<7;
880     *v = a | b;
881     return 3;
882   }
883 
884   /* A 32-bit varint is used to store size information in btrees.
885   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
886   ** A 3-byte varint is sufficient, for example, to record the size
887   ** of a 1048569-byte BLOB or string.
888   **
889   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
890   ** rare larger cases can be handled by the slower 64-bit varint
891   ** routine.
892   */
893 #if 1
894   {
895     u64 v64;
896     u8 n;
897 
898     p -= 2;
899     n = sqlite3GetVarint(p, &v64);
900     assert( n>3 && n<=9 );
901     if( (v64 & SQLITE_MAX_U32)!=v64 ){
902       *v = 0xffffffff;
903     }else{
904       *v = (u32)v64;
905     }
906     return n;
907   }
908 
909 #else
910   /* For following code (kept for historical record only) shows an
911   ** unrolling for the 3- and 4-byte varint cases.  This code is
912   ** slightly faster, but it is also larger and much harder to test.
913   */
914   p++;
915   b = b<<14;
916   b |= *p;
917   /* b: p1<<14 | p3 (unmasked) */
918   if (!(b&0x80))
919   {
920     /* Values between 2097152 and 268435455 */
921     b &= (0x7f<<14)|(0x7f);
922     a &= (0x7f<<14)|(0x7f);
923     a = a<<7;
924     *v = a | b;
925     return 4;
926   }
927 
928   p++;
929   a = a<<14;
930   a |= *p;
931   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
932   if (!(a&0x80))
933   {
934     /* Values  between 268435456 and 34359738367 */
935     a &= SLOT_4_2_0;
936     b &= SLOT_4_2_0;
937     b = b<<7;
938     *v = a | b;
939     return 5;
940   }
941 
942   /* We can only reach this point when reading a corrupt database
943   ** file.  In that case we are not in any hurry.  Use the (relatively
944   ** slow) general-purpose sqlite3GetVarint() routine to extract the
945   ** value. */
946   {
947     u64 v64;
948     u8 n;
949 
950     p -= 4;
951     n = sqlite3GetVarint(p, &v64);
952     assert( n>5 && n<=9 );
953     *v = (u32)v64;
954     return n;
955   }
956 #endif
957 }
958 
959 /*
960 ** Return the number of bytes that will be needed to store the given
961 ** 64-bit integer.
962 */
963 int sqlite3VarintLen(u64 v){
964   int i = 0;
965   do{
966     i++;
967     v >>= 7;
968   }while( v!=0 && ALWAYS(i<9) );
969   return i;
970 }
971 
972 
973 /*
974 ** Read or write a four-byte big-endian integer value.
975 */
976 u32 sqlite3Get4byte(const u8 *p){
977   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
978 }
979 void sqlite3Put4byte(unsigned char *p, u32 v){
980   p[0] = (u8)(v>>24);
981   p[1] = (u8)(v>>16);
982   p[2] = (u8)(v>>8);
983   p[3] = (u8)v;
984 }
985 
986 
987 
988 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
989 /*
990 ** Translate a single byte of Hex into an integer.
991 ** This routine only works if h really is a valid hexadecimal
992 ** character:  0..9a..fA..F
993 */
994 static u8 hexToInt(int h){
995   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
996 #ifdef SQLITE_ASCII
997   h += 9*(1&(h>>6));
998 #endif
999 #ifdef SQLITE_EBCDIC
1000   h += 9*(1&~(h>>4));
1001 #endif
1002   return (u8)(h & 0xf);
1003 }
1004 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
1005 
1006 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
1007 /*
1008 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
1009 ** value.  Return a pointer to its binary value.  Space to hold the
1010 ** binary value has been obtained from malloc and must be freed by
1011 ** the calling routine.
1012 */
1013 void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
1014   char *zBlob;
1015   int i;
1016 
1017   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
1018   n--;
1019   if( zBlob ){
1020     for(i=0; i<n; i+=2){
1021       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
1022     }
1023     zBlob[i/2] = 0;
1024   }
1025   return zBlob;
1026 }
1027 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
1028 
1029 /*
1030 ** Log an error that is an API call on a connection pointer that should
1031 ** not have been used.  The "type" of connection pointer is given as the
1032 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
1033 */
1034 static void logBadConnection(const char *zType){
1035   sqlite3_log(SQLITE_MISUSE,
1036      "API call with %s database connection pointer",
1037      zType
1038   );
1039 }
1040 
1041 /*
1042 ** Check to make sure we have a valid db pointer.  This test is not
1043 ** foolproof but it does provide some measure of protection against
1044 ** misuse of the interface such as passing in db pointers that are
1045 ** NULL or which have been previously closed.  If this routine returns
1046 ** 1 it means that the db pointer is valid and 0 if it should not be
1047 ** dereferenced for any reason.  The calling function should invoke
1048 ** SQLITE_MISUSE immediately.
1049 **
1050 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
1051 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
1052 ** open properly and is not fit for general use but which can be
1053 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
1054 */
1055 int sqlite3SafetyCheckOk(sqlite3 *db){
1056   u32 magic;
1057   if( db==0 ){
1058     logBadConnection("NULL");
1059     return 0;
1060   }
1061   magic = db->magic;
1062   if( magic!=SQLITE_MAGIC_OPEN ){
1063     if( sqlite3SafetyCheckSickOrOk(db) ){
1064       testcase( sqlite3GlobalConfig.xLog!=0 );
1065       logBadConnection("unopened");
1066     }
1067     return 0;
1068   }else{
1069     return 1;
1070   }
1071 }
1072 int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
1073   u32 magic;
1074   magic = db->magic;
1075   if( magic!=SQLITE_MAGIC_SICK &&
1076       magic!=SQLITE_MAGIC_OPEN &&
1077       magic!=SQLITE_MAGIC_BUSY ){
1078     testcase( sqlite3GlobalConfig.xLog!=0 );
1079     logBadConnection("invalid");
1080     return 0;
1081   }else{
1082     return 1;
1083   }
1084 }
1085