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