xref: /sqlite-3.40.0/src/util.c (revision 4249b3f5)
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 ** $Id: util.c,v 1.239 2008/07/22 05:15:53 shane Exp $
18 */
19 #include "sqliteInt.h"
20 #include <stdarg.h>
21 #include <ctype.h>
22 
23 
24 /*
25 ** Return true if the floating point value is Not a Number (NaN).
26 */
27 int sqlite3IsNaN(double x){
28   /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
29   ** On the other hand, the use of -ffast-math comes with the following
30   ** warning:
31   **
32   **      This option [-ffast-math] should never be turned on by any
33   **      -O option since it can result in incorrect output for programs
34   **      which depend on an exact implementation of IEEE or ISO
35   **      rules/specifications for math functions.
36   **
37   ** Under MSVC, this NaN test may fail if compiled with a floating-
38   ** point precision mode other than /fp:precise.  From the MSDN
39   ** documentation:
40   **
41   **      The compiler [with /fp:precise] will properly handle comparisons
42   **      involving NaN. For example, x != x evaluates to true if x is NaN
43   **      ...
44   */
45 #ifdef __FAST_MATH__
46 # error SQLite will not work correctly with the -ffast-math option of GCC.
47 #endif
48   volatile double y = x;
49   volatile double z = y;
50   return y!=z;
51 }
52 
53 /*
54 ** Return the length of a string, except do not allow the string length
55 ** to exceed the SQLITE_LIMIT_LENGTH setting.
56 */
57 int sqlite3Strlen(sqlite3 *db, const char *z){
58   const char *z2 = z;
59   while( *z2 ){ z2++; }
60   if( z2 > &z[db->aLimit[SQLITE_LIMIT_LENGTH]] ){
61     return db->aLimit[SQLITE_LIMIT_LENGTH];
62   }else{
63     return (int)(z2 - z);
64   }
65 }
66 
67 /*
68 ** Set the most recent error code and error string for the sqlite
69 ** handle "db". The error code is set to "err_code".
70 **
71 ** If it is not NULL, string zFormat specifies the format of the
72 ** error string in the style of the printf functions: The following
73 ** format characters are allowed:
74 **
75 **      %s      Insert a string
76 **      %z      A string that should be freed after use
77 **      %d      Insert an integer
78 **      %T      Insert a token
79 **      %S      Insert the first element of a SrcList
80 **
81 ** zFormat and any string tokens that follow it are assumed to be
82 ** encoded in UTF-8.
83 **
84 ** To clear the most recent error for sqlite handle "db", sqlite3Error
85 ** should be called with err_code set to SQLITE_OK and zFormat set
86 ** to NULL.
87 */
88 void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
89   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
90     db->errCode = err_code;
91     if( zFormat ){
92       char *z;
93       va_list ap;
94       va_start(ap, zFormat);
95       z = sqlite3VMPrintf(db, zFormat, ap);
96       va_end(ap);
97       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, sqlite3_free);
98     }else{
99       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
100     }
101   }
102 }
103 
104 /*
105 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
106 ** The following formatting characters are allowed:
107 **
108 **      %s      Insert a string
109 **      %z      A string that should be freed after use
110 **      %d      Insert an integer
111 **      %T      Insert a token
112 **      %S      Insert the first element of a SrcList
113 **
114 ** This function should be used to report any error that occurs whilst
115 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
116 ** last thing the sqlite3_prepare() function does is copy the error
117 ** stored by this function into the database handle using sqlite3Error().
118 ** Function sqlite3Error() should be used during statement execution
119 ** (sqlite3_step() etc.).
120 */
121 void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
122   va_list ap;
123   pParse->nErr++;
124   sqlite3_free(pParse->zErrMsg);
125   va_start(ap, zFormat);
126   pParse->zErrMsg = sqlite3VMPrintf(pParse->db, zFormat, ap);
127   va_end(ap);
128   if( pParse->rc==SQLITE_OK ){
129     pParse->rc = SQLITE_ERROR;
130   }
131 }
132 
133 /*
134 ** Clear the error message in pParse, if any
135 */
136 void sqlite3ErrorClear(Parse *pParse){
137   sqlite3_free(pParse->zErrMsg);
138   pParse->zErrMsg = 0;
139   pParse->nErr = 0;
140 }
141 
142 /*
143 ** Convert an SQL-style quoted string into a normal string by removing
144 ** the quote characters.  The conversion is done in-place.  If the
145 ** input does not begin with a quote character, then this routine
146 ** is a no-op.
147 **
148 ** 2002-Feb-14: This routine is extended to remove MS-Access style
149 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
150 ** "a-b-c".
151 */
152 void sqlite3Dequote(char *z){
153   int quote;
154   int i, j;
155   if( z==0 ) return;
156   quote = z[0];
157   switch( quote ){
158     case '\'':  break;
159     case '"':   break;
160     case '`':   break;                /* For MySQL compatibility */
161     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
162     default:    return;
163   }
164   for(i=1, j=0; z[i]; i++){
165     if( z[i]==quote ){
166       if( z[i+1]==quote ){
167         z[j++] = quote;
168         i++;
169       }else{
170         z[j++] = 0;
171         break;
172       }
173     }else{
174       z[j++] = z[i];
175     }
176   }
177 }
178 
179 /* Convenient short-hand */
180 #define UpperToLower sqlite3UpperToLower
181 
182 /*
183 ** Some systems have stricmp().  Others have strcasecmp().  Because
184 ** there is no consistency, we will define our own.
185 */
186 int sqlite3StrICmp(const char *zLeft, const char *zRight){
187   register unsigned char *a, *b;
188   a = (unsigned char *)zLeft;
189   b = (unsigned char *)zRight;
190   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
191   return UpperToLower[*a] - UpperToLower[*b];
192 }
193 int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
194   register unsigned char *a, *b;
195   a = (unsigned char *)zLeft;
196   b = (unsigned char *)zRight;
197   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
198   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
199 }
200 
201 /*
202 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
203 ** string contains any character which is not part of a number. If
204 ** the string is numeric and contains the '.' character, set *realnum
205 ** to TRUE (otherwise FALSE).
206 **
207 ** An empty string is considered non-numeric.
208 */
209 int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
210   int incr = (enc==SQLITE_UTF8?1:2);
211   if( enc==SQLITE_UTF16BE ) z++;
212   if( *z=='-' || *z=='+' ) z += incr;
213   if( !isdigit(*(u8*)z) ){
214     return 0;
215   }
216   z += incr;
217   if( realnum ) *realnum = 0;
218   while( isdigit(*(u8*)z) ){ z += incr; }
219   if( *z=='.' ){
220     z += incr;
221     if( !isdigit(*(u8*)z) ) return 0;
222     while( isdigit(*(u8*)z) ){ z += incr; }
223     if( realnum ) *realnum = 1;
224   }
225   if( *z=='e' || *z=='E' ){
226     z += incr;
227     if( *z=='+' || *z=='-' ) z += incr;
228     if( !isdigit(*(u8*)z) ) return 0;
229     while( isdigit(*(u8*)z) ){ z += incr; }
230     if( realnum ) *realnum = 1;
231   }
232   return *z==0;
233 }
234 
235 /*
236 ** The string z[] is an ascii representation of a real number.
237 ** Convert this string to a double.
238 **
239 ** This routine assumes that z[] really is a valid number.  If it
240 ** is not, the result is undefined.
241 **
242 ** This routine is used instead of the library atof() function because
243 ** the library atof() might want to use "," as the decimal point instead
244 ** of "." depending on how locale is set.  But that would cause problems
245 ** for SQL.  So this routine always uses "." regardless of locale.
246 */
247 int sqlite3AtoF(const char *z, double *pResult){
248 #ifndef SQLITE_OMIT_FLOATING_POINT
249   int sign = 1;
250   const char *zBegin = z;
251   LONGDOUBLE_TYPE v1 = 0.0;
252   int nSignificant = 0;
253   while( isspace(*(u8*)z) ) z++;
254   if( *z=='-' ){
255     sign = -1;
256     z++;
257   }else if( *z=='+' ){
258     z++;
259   }
260   while( z[0]=='0' ){
261     z++;
262   }
263   while( isdigit(*(u8*)z) ){
264     v1 = v1*10.0 + (*z - '0');
265     z++;
266     nSignificant++;
267   }
268   if( *z=='.' ){
269     LONGDOUBLE_TYPE divisor = 1.0;
270     z++;
271     if( nSignificant==0 ){
272       while( z[0]=='0' ){
273         divisor *= 10.0;
274         z++;
275       }
276     }
277     while( isdigit(*(u8*)z) ){
278       if( nSignificant<18 ){
279         v1 = v1*10.0 + (*z - '0');
280         divisor *= 10.0;
281         nSignificant++;
282       }
283       z++;
284     }
285     v1 /= divisor;
286   }
287   if( *z=='e' || *z=='E' ){
288     int esign = 1;
289     int eval = 0;
290     LONGDOUBLE_TYPE scale = 1.0;
291     z++;
292     if( *z=='-' ){
293       esign = -1;
294       z++;
295     }else if( *z=='+' ){
296       z++;
297     }
298     while( isdigit(*(u8*)z) ){
299       eval = eval*10 + *z - '0';
300       z++;
301     }
302     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
303     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
304     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
305     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
306     if( esign<0 ){
307       v1 /= scale;
308     }else{
309       v1 *= scale;
310     }
311   }
312   *pResult = sign<0 ? -v1 : v1;
313   return z - zBegin;
314 #else
315   return sqlite3Atoi64(z, pResult);
316 #endif /* SQLITE_OMIT_FLOATING_POINT */
317 }
318 
319 /*
320 ** Compare the 19-character string zNum against the text representation
321 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
322 ** if zNum is less than, equal to, or greater than the string.
323 **
324 ** Unlike memcmp() this routine is guaranteed to return the difference
325 ** in the values of the last digit if the only difference is in the
326 ** last digit.  So, for example,
327 **
328 **      compare2pow63("9223372036854775800")
329 **
330 ** will return -8.
331 */
332 static int compare2pow63(const char *zNum){
333   int c;
334   c = memcmp(zNum,"922337203685477580",18);
335   if( c==0 ){
336     c = zNum[18] - '8';
337   }
338   return c;
339 }
340 
341 
342 /*
343 ** Return TRUE if zNum is a 64-bit signed integer and write
344 ** the value of the integer into *pNum.  If zNum is not an integer
345 ** or is an integer that is too large to be expressed with 64 bits,
346 ** then return false.
347 **
348 ** When this routine was originally written it dealt with only
349 ** 32-bit numbers.  At that time, it was much faster than the
350 ** atoi() library routine in RedHat 7.2.
351 */
352 int sqlite3Atoi64(const char *zNum, i64 *pNum){
353   i64 v = 0;
354   int neg;
355   int i, c;
356   const char *zStart;
357   while( isspace(*(u8*)zNum) ) zNum++;
358   if( *zNum=='-' ){
359     neg = 1;
360     zNum++;
361   }else if( *zNum=='+' ){
362     neg = 0;
363     zNum++;
364   }else{
365     neg = 0;
366   }
367   zStart = zNum;
368   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
369   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
370     v = v*10 + c - '0';
371   }
372   *pNum = neg ? -v : v;
373   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
374     /* zNum is empty or contains non-numeric text or is longer
375     ** than 19 digits (thus guaranting that it is too large) */
376     return 0;
377   }else if( i<19 ){
378     /* Less than 19 digits, so we know that it fits in 64 bits */
379     return 1;
380   }else{
381     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
382     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
383     ** is 2^63. */
384     return compare2pow63(zNum)<neg;
385   }
386 }
387 
388 /*
389 ** The string zNum represents an integer.  There might be some other
390 ** information following the integer too, but that part is ignored.
391 ** If the integer that the prefix of zNum represents will fit in a
392 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
393 **
394 ** This routine returns FALSE for the string -9223372036854775808 even that
395 ** that number will, in theory fit in a 64-bit integer.  Positive
396 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
397 ** false.
398 */
399 int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
400   int i, c;
401   int neg = 0;
402   if( *zNum=='-' ){
403     neg = 1;
404     zNum++;
405   }else if( *zNum=='+' ){
406     zNum++;
407   }
408   if( negFlag ) neg = 1-neg;
409   while( *zNum=='0' ){
410     zNum++;   /* Skip leading zeros.  Ticket #2454 */
411   }
412   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
413   if( i<19 ){
414     /* Guaranteed to fit if less than 19 digits */
415     return 1;
416   }else if( i>19 ){
417     /* Guaranteed to be too big if greater than 19 digits */
418     return 0;
419   }else{
420     /* Compare against 2^63. */
421     return compare2pow63(zNum)<neg;
422   }
423 }
424 
425 /*
426 ** If zNum represents an integer that will fit in 32-bits, then set
427 ** *pValue to that integer and return true.  Otherwise return false.
428 **
429 ** Any non-numeric characters that following zNum are ignored.
430 ** This is different from sqlite3Atoi64() which requires the
431 ** input number to be zero-terminated.
432 */
433 int sqlite3GetInt32(const char *zNum, int *pValue){
434   sqlite_int64 v = 0;
435   int i, c;
436   int neg = 0;
437   if( zNum[0]=='-' ){
438     neg = 1;
439     zNum++;
440   }else if( zNum[0]=='+' ){
441     zNum++;
442   }
443   while( zNum[0]=='0' ) zNum++;
444   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
445     v = v*10 + c;
446   }
447 
448   /* The longest decimal representation of a 32 bit integer is 10 digits:
449   **
450   **             1234567890
451   **     2^31 -> 2147483648
452   */
453   if( i>10 ){
454     return 0;
455   }
456   if( v-neg>2147483647 ){
457     return 0;
458   }
459   if( neg ){
460     v = -v;
461   }
462   *pValue = (int)v;
463   return 1;
464 }
465 
466 /*
467 ** The variable-length integer encoding is as follows:
468 **
469 ** KEY:
470 **         A = 0xxxxxxx    7 bits of data and one flag bit
471 **         B = 1xxxxxxx    7 bits of data and one flag bit
472 **         C = xxxxxxxx    8 bits of data
473 **
474 **  7 bits - A
475 ** 14 bits - BA
476 ** 21 bits - BBA
477 ** 28 bits - BBBA
478 ** 35 bits - BBBBA
479 ** 42 bits - BBBBBA
480 ** 49 bits - BBBBBBA
481 ** 56 bits - BBBBBBBA
482 ** 64 bits - BBBBBBBBC
483 */
484 
485 /*
486 ** Write a 64-bit variable-length integer to memory starting at p[0].
487 ** The length of data write will be between 1 and 9 bytes.  The number
488 ** of bytes written is returned.
489 **
490 ** A variable-length integer consists of the lower 7 bits of each byte
491 ** for all bytes that have the 8th bit set and one byte with the 8th
492 ** bit clear.  Except, if we get to the 9th byte, it stores the full
493 ** 8 bits and is the last byte.
494 */
495 int sqlite3PutVarint(unsigned char *p, u64 v){
496   int i, j, n;
497   u8 buf[10];
498   if( v & (((u64)0xff000000)<<32) ){
499     p[8] = v;
500     v >>= 8;
501     for(i=7; i>=0; i--){
502       p[i] = (v & 0x7f) | 0x80;
503       v >>= 7;
504     }
505     return 9;
506   }
507   n = 0;
508   do{
509     buf[n++] = (v & 0x7f) | 0x80;
510     v >>= 7;
511   }while( v!=0 );
512   buf[0] &= 0x7f;
513   assert( n<=9 );
514   for(i=0, j=n-1; j>=0; j--, i++){
515     p[i] = buf[j];
516   }
517   return n;
518 }
519 
520 /*
521 ** This routine is a faster version of sqlite3PutVarint() that only
522 ** works for 32-bit positive integers and which is optimized for
523 ** the common case of small integers.  A MACRO version, putVarint32,
524 ** is provided which inlines the single-byte case.  All code should use
525 ** the MACRO version as this function assumes the single-byte case has
526 ** already been handled.
527 */
528 int sqlite3PutVarint32(unsigned char *p, u32 v){
529 #ifndef putVarint32
530   if( (v & ~0x7f)==0 ){
531     p[0] = v;
532     return 1;
533   }
534 #endif
535   if( (v & ~0x3fff)==0 ){
536     p[0] = (v>>7) | 0x80;
537     p[1] = v & 0x7f;
538     return 2;
539   }
540   return sqlite3PutVarint(p, v);
541 }
542 
543 /*
544 ** Read a 64-bit variable-length integer from memory starting at p[0].
545 ** Return the number of bytes read.  The value is stored in *v.
546 */
547 int sqlite3GetVarint(const unsigned char *p, u64 *v){
548   u32 a,b,s;
549 
550   a = *p;
551   /* a: p0 (unmasked) */
552   if (!(a&0x80))
553   {
554     *v = a;
555     return 1;
556   }
557 
558   p++;
559   b = *p;
560   /* b: p1 (unmasked) */
561   if (!(b&0x80))
562   {
563     a &= 0x7f;
564     a = a<<7;
565     a |= b;
566     *v = a;
567     return 2;
568   }
569 
570   p++;
571   a = a<<14;
572   a |= *p;
573   /* a: p0<<14 | p2 (unmasked) */
574   if (!(a&0x80))
575   {
576     a &= (0x7f<<14)|(0x7f);
577     b &= 0x7f;
578     b = b<<7;
579     a |= b;
580     *v = a;
581     return 3;
582   }
583 
584   /* CSE1 from below */
585   a &= (0x7f<<14)|(0x7f);
586   p++;
587   b = b<<14;
588   b |= *p;
589   /* b: p1<<14 | p3 (unmasked) */
590   if (!(b&0x80))
591   {
592     b &= (0x7f<<14)|(0x7f);
593     /* moved CSE1 up */
594     /* a &= (0x7f<<14)|(0x7f); */
595     a = a<<7;
596     a |= b;
597     *v = a;
598     return 4;
599   }
600 
601   /* a: p0<<14 | p2 (masked) */
602   /* b: p1<<14 | p3 (unmasked) */
603   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
604   /* moved CSE1 up */
605   /* a &= (0x7f<<14)|(0x7f); */
606   b &= (0x7f<<14)|(0x7f);
607   s = a;
608   /* s: p0<<14 | p2 (masked) */
609 
610   p++;
611   a = a<<14;
612   a |= *p;
613   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
614   if (!(a&0x80))
615   {
616     /* we can skip these cause they were (effectively) done above in calc'ing s */
617     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
618     /* b &= (0x7f<<14)|(0x7f); */
619     b = b<<7;
620     a |= b;
621     s = s>>18;
622     *v = ((u64)s)<<32 | a;
623     return 5;
624   }
625 
626   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
627   s = s<<7;
628   s |= b;
629   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
630 
631   p++;
632   b = b<<14;
633   b |= *p;
634   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
635   if (!(b&0x80))
636   {
637     /* we can skip this cause it was (effectively) done above in calc'ing s */
638     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
639     a &= (0x7f<<14)|(0x7f);
640     a = a<<7;
641     a |= b;
642     s = s>>18;
643     *v = ((u64)s)<<32 | a;
644     return 6;
645   }
646 
647   p++;
648   a = a<<14;
649   a |= *p;
650   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
651   if (!(a&0x80))
652   {
653     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
654     b &= (0x7f<<14)|(0x7f);
655     b = b<<7;
656     a |= b;
657     s = s>>11;
658     *v = ((u64)s)<<32 | a;
659     return 7;
660   }
661 
662   /* CSE2 from below */
663   a &= (0x7f<<14)|(0x7f);
664   p++;
665   b = b<<14;
666   b |= *p;
667   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
668   if (!(b&0x80))
669   {
670     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
671     /* moved CSE2 up */
672     /* a &= (0x7f<<14)|(0x7f); */
673     a = a<<7;
674     a |= b;
675     s = s>>4;
676     *v = ((u64)s)<<32 | a;
677     return 8;
678   }
679 
680   p++;
681   a = a<<15;
682   a |= *p;
683   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
684 
685   /* moved CSE2 up */
686   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
687   b &= (0x7f<<14)|(0x7f);
688   b = b<<8;
689   a |= b;
690 
691   s = s<<4;
692   b = p[-4];
693   b &= 0x7f;
694   b = b>>3;
695   s |= b;
696 
697   *v = ((u64)s)<<32 | a;
698 
699   return 9;
700 }
701 
702 /*
703 ** Read a 32-bit variable-length integer from memory starting at p[0].
704 ** Return the number of bytes read.  The value is stored in *v.
705 ** A MACRO version, getVarint32, is provided which inlines the
706 ** single-byte case.  All code should use the MACRO version as
707 ** this function assumes the single-byte case has already been handled.
708 */
709 int sqlite3GetVarint32(const unsigned char *p, u32 *v){
710   u32 a,b;
711 
712   a = *p;
713   /* a: p0 (unmasked) */
714 #ifndef getVarint32
715   if (!(a&0x80))
716   {
717     *v = a;
718     return 1;
719   }
720 #endif
721 
722   p++;
723   b = *p;
724   /* b: p1 (unmasked) */
725   if (!(b&0x80))
726   {
727     a &= 0x7f;
728     a = a<<7;
729     *v = a | b;
730     return 2;
731   }
732 
733   p++;
734   a = a<<14;
735   a |= *p;
736   /* a: p0<<14 | p2 (unmasked) */
737   if (!(a&0x80))
738   {
739     a &= (0x7f<<14)|(0x7f);
740     b &= 0x7f;
741     b = b<<7;
742     *v = a | b;
743     return 3;
744   }
745 
746   p++;
747   b = b<<14;
748   b |= *p;
749   /* b: p1<<14 | p3 (unmasked) */
750   if (!(b&0x80))
751   {
752     b &= (0x7f<<14)|(0x7f);
753     a &= (0x7f<<14)|(0x7f);
754     a = a<<7;
755     *v = a | b;
756     return 4;
757   }
758 
759   p++;
760   a = a<<14;
761   a |= *p;
762   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
763   if (!(a&0x80))
764   {
765     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
766     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
767     b = b<<7;
768     *v = a | b;
769     return 5;
770   }
771 
772   /* We can only reach this point when reading a corrupt database
773   ** file.  In that case we are not in any hurry.  Use the (relatively
774   ** slow) general-purpose sqlite3GetVarint() routine to extract the
775   ** value. */
776   {
777     u64 v64;
778     int n;
779 
780     p -= 4;
781     n = sqlite3GetVarint(p, &v64);
782     assert( n>5 && n<=9 );
783     *v = (u32)v64;
784     return n;
785   }
786 }
787 
788 /*
789 ** Return the number of bytes that will be needed to store the given
790 ** 64-bit integer.
791 */
792 int sqlite3VarintLen(u64 v){
793   int i = 0;
794   do{
795     i++;
796     v >>= 7;
797   }while( v!=0 && i<9 );
798   return i;
799 }
800 
801 
802 /*
803 ** Read or write a four-byte big-endian integer value.
804 */
805 u32 sqlite3Get4byte(const u8 *p){
806   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
807 }
808 void sqlite3Put4byte(unsigned char *p, u32 v){
809   p[0] = v>>24;
810   p[1] = v>>16;
811   p[2] = v>>8;
812   p[3] = v;
813 }
814 
815 
816 
817 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
818 /*
819 ** Translate a single byte of Hex into an integer.
820 ** This routinen only works if h really is a valid hexadecimal
821 ** character:  0..9a..fA..F
822 */
823 static int hexToInt(int h){
824   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
825 #ifdef SQLITE_ASCII
826   h += 9*(1&(h>>6));
827 #endif
828 #ifdef SQLITE_EBCDIC
829   h += 9*(1&~(h>>4));
830 #endif
831   return h & 0xf;
832 }
833 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
834 
835 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
836 /*
837 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
838 ** value.  Return a pointer to its binary value.  Space to hold the
839 ** binary value has been obtained from malloc and must be freed by
840 ** the calling routine.
841 */
842 void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
843   char *zBlob;
844   int i;
845 
846   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
847   n--;
848   if( zBlob ){
849     for(i=0; i<n; i+=2){
850       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
851     }
852     zBlob[i/2] = 0;
853   }
854   return zBlob;
855 }
856 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
857 
858 
859 /*
860 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
861 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
862 ** when this routine is called.
863 **
864 ** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
865 ** value indicates that the database connection passed into the API is
866 ** open and is not being used by another thread.  By changing the value
867 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
868 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
869 ** when the API exits.
870 **
871 ** This routine is a attempt to detect if two threads use the
872 ** same sqlite* pointer at the same time.  There is a race
873 ** condition so it is possible that the error is not detected.
874 ** But usually the problem will be seen.  The result will be an
875 ** error which can be used to debug the application that is
876 ** using SQLite incorrectly.
877 **
878 ** Ticket #202:  If db->magic is not a valid open value, take care not
879 ** to modify the db structure at all.  It could be that db is a stale
880 ** pointer.  In other words, it could be that there has been a prior
881 ** call to sqlite3_close(db) and db has been deallocated.  And we do
882 ** not want to write into deallocated memory.
883 */
884 #ifdef SQLITE_DEBUG
885 int sqlite3SafetyOn(sqlite3 *db){
886   if( db->magic==SQLITE_MAGIC_OPEN ){
887     db->magic = SQLITE_MAGIC_BUSY;
888     assert( sqlite3_mutex_held(db->mutex) );
889     return 0;
890   }else if( db->magic==SQLITE_MAGIC_BUSY ){
891     db->magic = SQLITE_MAGIC_ERROR;
892     db->u1.isInterrupted = 1;
893   }
894   return 1;
895 }
896 #endif
897 
898 /*
899 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
900 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
901 ** when this routine is called.
902 */
903 #ifdef SQLITE_DEBUG
904 int sqlite3SafetyOff(sqlite3 *db){
905   if( db->magic==SQLITE_MAGIC_BUSY ){
906     db->magic = SQLITE_MAGIC_OPEN;
907     assert( sqlite3_mutex_held(db->mutex) );
908     return 0;
909   }else{
910     db->magic = SQLITE_MAGIC_ERROR;
911     db->u1.isInterrupted = 1;
912     return 1;
913   }
914 }
915 #endif
916 
917 /*
918 ** Check to make sure we have a valid db pointer.  This test is not
919 ** foolproof but it does provide some measure of protection against
920 ** misuse of the interface such as passing in db pointers that are
921 ** NULL or which have been previously closed.  If this routine returns
922 ** 1 it means that the db pointer is valid and 0 if it should not be
923 ** dereferenced for any reason.  The calling function should invoke
924 ** SQLITE_MISUSE immediately.
925 **
926 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
927 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
928 ** open properly and is not fit for general use but which can be
929 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
930 */
931 int sqlite3SafetyCheckOk(sqlite3 *db){
932   int magic;
933   if( db==0 ) return 0;
934   magic = db->magic;
935   if( magic!=SQLITE_MAGIC_OPEN &&
936       magic!=SQLITE_MAGIC_BUSY ) return 0;
937   return 1;
938 }
939 int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
940   int magic;
941   if( db==0 ) return 0;
942   magic = db->magic;
943   if( magic!=SQLITE_MAGIC_SICK &&
944       magic!=SQLITE_MAGIC_OPEN &&
945       magic!=SQLITE_MAGIC_BUSY ) return 0;
946   return 1;
947 }
948