util.c 33 KB

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