blob: d12e55516f14efb33ba2229f45e5422cedd27511 [file] [log] [blame]
drhc81c11f2009-11-10 01:30:52 +00001/*
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>
drh0ede9eb2015-01-10 16:49:23 +000020#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
drhc81c11f2009-11-10 01:30:52 +000021# include <math.h>
22#endif
23
24/*
25** Routine needed to support the testcase() macro.
26*/
27#ifdef SQLITE_COVERAGE_TEST
28void sqlite3Coverage(int x){
drh68bf0672011-04-11 15:35:24 +000029 static unsigned dummy = 0;
30 dummy += (unsigned)x;
drhc81c11f2009-11-10 01:30:52 +000031}
32#endif
33
drhc007f612014-05-16 14:17:01 +000034/*
drhce059e52019-04-05 17:22:50 +000035** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
36** or to bypass normal error detection during testing in order to let
37** execute proceed futher downstream.
drhc007f612014-05-16 14:17:01 +000038**
drhce059e52019-04-05 17:22:50 +000039** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0). The
40** sqlite3FaultSim() function only returns non-zero during testing.
drhc007f612014-05-16 14:17:01 +000041**
drhce059e52019-04-05 17:22:50 +000042** During testing, if the test harness has set a fault-sim callback using
43** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
44** each call to sqlite3FaultSim() is relayed to that application-supplied
45** callback and the integer return value form the application-supplied
46** callback is returned by sqlite3FaultSim().
47**
48** The integer argument to sqlite3FaultSim() is a code to identify which
49** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
50** should have a unique code. To prevent legacy testing applications from
51** breaking, the codes should not be changed or reused.
drhc007f612014-05-16 14:17:01 +000052*/
drhd12602a2016-12-07 15:49:02 +000053#ifndef SQLITE_UNTESTABLE
drhc007f612014-05-16 14:17:01 +000054int sqlite3FaultSim(int iTest){
55 int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
56 return xCallback ? xCallback(iTest) : SQLITE_OK;
57}
58#endif
59
drh85c8f292010-01-13 17:39:53 +000060#ifndef SQLITE_OMIT_FLOATING_POINT
drhc81c11f2009-11-10 01:30:52 +000061/*
62** Return true if the floating point value is Not a Number (NaN).
63**
64** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
65** Otherwise, we have our own implementation that works on most systems.
66*/
67int sqlite3IsNaN(double x){
68 int rc; /* The value return */
drh0ede9eb2015-01-10 16:49:23 +000069#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
drhc81c11f2009-11-10 01:30:52 +000070 /*
71 ** Systems that support the isnan() library function should probably
72 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
73 ** found that many systems do not have a working isnan() function so
74 ** this implementation is provided as an alternative.
75 **
76 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
77 ** On the other hand, the use of -ffast-math comes with the following
78 ** warning:
79 **
80 ** This option [-ffast-math] should never be turned on by any
81 ** -O option since it can result in incorrect output for programs
82 ** which depend on an exact implementation of IEEE or ISO
83 ** rules/specifications for math functions.
84 **
85 ** Under MSVC, this NaN test may fail if compiled with a floating-
86 ** point precision mode other than /fp:precise. From the MSDN
87 ** documentation:
88 **
89 ** The compiler [with /fp:precise] will properly handle comparisons
90 ** involving NaN. For example, x != x evaluates to true if x is NaN
91 ** ...
92 */
93#ifdef __FAST_MATH__
94# error SQLite will not work correctly with the -ffast-math option of GCC.
95#endif
96 volatile double y = x;
97 volatile double z = y;
98 rc = (y!=z);
drh0ede9eb2015-01-10 16:49:23 +000099#else /* if HAVE_ISNAN */
drhc81c11f2009-11-10 01:30:52 +0000100 rc = isnan(x);
drh0ede9eb2015-01-10 16:49:23 +0000101#endif /* HAVE_ISNAN */
drhc81c11f2009-11-10 01:30:52 +0000102 testcase( rc );
103 return rc;
104}
drh85c8f292010-01-13 17:39:53 +0000105#endif /* SQLITE_OMIT_FLOATING_POINT */
drhc81c11f2009-11-10 01:30:52 +0000106
107/*
108** Compute a string length that is limited to what can be stored in
109** lower 30 bits of a 32-bit signed integer.
110**
111** The value returned will never be negative. Nor will it ever be greater
112** than the actual length of the string. For very long strings (greater
113** than 1GiB) the value returned might be less than the true string length.
114*/
115int sqlite3Strlen30(const char *z){
drhc81c11f2009-11-10 01:30:52 +0000116 if( z==0 ) return 0;
drh1116bf12015-06-30 03:18:33 +0000117 return 0x3fffffff & (int)strlen(z);
drhc81c11f2009-11-10 01:30:52 +0000118}
119
120/*
drhd7564862016-03-22 20:05:09 +0000121** Return the declared type of a column. Or return zDflt if the column
122** has no declared type.
123**
124** The column type is an extra string stored after the zero-terminator on
125** the column name if and only if the COLFLAG_HASTYPE flag is set.
drh94eaafa2016-02-29 15:53:11 +0000126*/
drhd7564862016-03-22 20:05:09 +0000127char *sqlite3ColumnType(Column *pCol, char *zDflt){
128 if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
129 return pCol->zName + strlen(pCol->zName) + 1;
drh94eaafa2016-02-29 15:53:11 +0000130}
131
132/*
drh80fbee02016-03-21 11:57:13 +0000133** Helper function for sqlite3Error() - called rarely. Broken out into
134** a separate routine to avoid unnecessary register saves on entry to
135** sqlite3Error().
drh13f40da2014-08-22 18:00:11 +0000136*/
drh8d2f41c2016-03-21 11:38:01 +0000137static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
138 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
139 sqlite3SystemError(db, err_code);
140}
drh80fbee02016-03-21 11:57:13 +0000141
142/*
143** Set the current error code to err_code and clear any prior error message.
144** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
145** that would be appropriate.
146*/
drh13f40da2014-08-22 18:00:11 +0000147void sqlite3Error(sqlite3 *db, int err_code){
148 assert( db!=0 );
149 db->errCode = err_code;
drh8d2f41c2016-03-21 11:38:01 +0000150 if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
drh13f40da2014-08-22 18:00:11 +0000151}
152
153/*
drh1b9f2142016-03-17 16:01:23 +0000154** Load the sqlite3.iSysErrno field if that is an appropriate thing
155** to do based on the SQLite error code in rc.
156*/
157void sqlite3SystemError(sqlite3 *db, int rc){
158 if( rc==SQLITE_IOERR_NOMEM ) return;
159 rc &= 0xff;
160 if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
161 db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
162 }
163}
164
165/*
drhc81c11f2009-11-10 01:30:52 +0000166** Set the most recent error code and error string for the sqlite
167** handle "db". The error code is set to "err_code".
168**
169** If it is not NULL, string zFormat specifies the format of the
170** error string in the style of the printf functions: The following
171** format characters are allowed:
172**
173** %s Insert a string
174** %z A string that should be freed after use
175** %d Insert an integer
176** %T Insert a token
177** %S Insert the first element of a SrcList
178**
179** zFormat and any string tokens that follow it are assumed to be
180** encoded in UTF-8.
181**
182** To clear the most recent error for sqlite handle "db", sqlite3Error
183** should be called with err_code set to SQLITE_OK and zFormat set
184** to NULL.
185*/
drh13f40da2014-08-22 18:00:11 +0000186void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
drha3cc0072013-12-13 16:23:55 +0000187 assert( db!=0 );
188 db->errCode = err_code;
drh8d2f41c2016-03-21 11:38:01 +0000189 sqlite3SystemError(db, err_code);
drh13f40da2014-08-22 18:00:11 +0000190 if( zFormat==0 ){
191 sqlite3Error(db, err_code);
192 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
drha3cc0072013-12-13 16:23:55 +0000193 char *z;
194 va_list ap;
195 va_start(ap, zFormat);
196 z = sqlite3VMPrintf(db, zFormat, ap);
197 va_end(ap);
198 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
drhc81c11f2009-11-10 01:30:52 +0000199 }
200}
201
202/*
203** Add an error message to pParse->zErrMsg and increment pParse->nErr.
204** The following formatting characters are allowed:
205**
206** %s Insert a string
207** %z A string that should be freed after use
208** %d Insert an integer
209** %T Insert a token
210** %S Insert the first element of a SrcList
211**
drh13f40da2014-08-22 18:00:11 +0000212** This function should be used to report any error that occurs while
drhc81c11f2009-11-10 01:30:52 +0000213** compiling an SQL statement (i.e. within sqlite3_prepare()). The
214** last thing the sqlite3_prepare() function does is copy the error
215** stored by this function into the database handle using sqlite3Error().
drh13f40da2014-08-22 18:00:11 +0000216** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
217** during statement execution (sqlite3_step() etc.).
drhc81c11f2009-11-10 01:30:52 +0000218*/
219void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
drha7564662010-02-22 19:32:31 +0000220 char *zMsg;
drhc81c11f2009-11-10 01:30:52 +0000221 va_list ap;
222 sqlite3 *db = pParse->db;
drhc81c11f2009-11-10 01:30:52 +0000223 va_start(ap, zFormat);
drha7564662010-02-22 19:32:31 +0000224 zMsg = sqlite3VMPrintf(db, zFormat, ap);
drhc81c11f2009-11-10 01:30:52 +0000225 va_end(ap);
drha7564662010-02-22 19:32:31 +0000226 if( db->suppressErr ){
227 sqlite3DbFree(db, zMsg);
228 }else{
229 pParse->nErr++;
230 sqlite3DbFree(db, pParse->zErrMsg);
231 pParse->zErrMsg = zMsg;
232 pParse->rc = SQLITE_ERROR;
drha7564662010-02-22 19:32:31 +0000233 }
drhc81c11f2009-11-10 01:30:52 +0000234}
235
236/*
drhc3dcdba2019-04-09 21:32:46 +0000237** If database connection db is currently parsing SQL, then transfer
238** error code errCode to that parser if the parser has not already
239** encountered some other kind of error.
240*/
241int sqlite3ErrorToParser(sqlite3 *db, int errCode){
242 Parse *pParse;
243 if( db==0 || (pParse = db->pParse)==0 ) return errCode;
244 pParse->rc = errCode;
245 pParse->nErr++;
246 return errCode;
247}
248
249/*
drhc81c11f2009-11-10 01:30:52 +0000250** Convert an SQL-style quoted string into a normal string by removing
251** the quote characters. The conversion is done in-place. If the
252** input does not begin with a quote character, then this routine
253** is a no-op.
254**
255** The input string must be zero-terminated. A new zero-terminator
256** is added to the dequoted string.
257**
258** The return value is -1 if no dequoting occurs or the length of the
259** dequoted string, exclusive of the zero terminator, if dequoting does
260** occur.
261**
drh51d35b02019-01-11 13:32:23 +0000262** 2002-02-14: This routine is extended to remove MS-Access style
peter.d.reid60ec9142014-09-06 16:39:46 +0000263** brackets from around identifiers. For example: "[a-b-c]" becomes
drhc81c11f2009-11-10 01:30:52 +0000264** "a-b-c".
265*/
drh244b9d62016-04-11 19:01:08 +0000266void sqlite3Dequote(char *z){
drhc81c11f2009-11-10 01:30:52 +0000267 char quote;
268 int i, j;
drh244b9d62016-04-11 19:01:08 +0000269 if( z==0 ) return;
drhc81c11f2009-11-10 01:30:52 +0000270 quote = z[0];
drh244b9d62016-04-11 19:01:08 +0000271 if( !sqlite3Isquote(quote) ) return;
272 if( quote=='[' ) quote = ']';
drh9ccd8652013-09-13 16:36:46 +0000273 for(i=1, j=0;; i++){
274 assert( z[i] );
drhc81c11f2009-11-10 01:30:52 +0000275 if( z[i]==quote ){
276 if( z[i+1]==quote ){
277 z[j++] = quote;
278 i++;
279 }else{
280 break;
281 }
282 }else{
283 z[j++] = z[i];
284 }
285 }
286 z[j] = 0;
drhc81c11f2009-11-10 01:30:52 +0000287}
drh51d35b02019-01-11 13:32:23 +0000288void sqlite3DequoteExpr(Expr *p){
289 assert( sqlite3Isquote(p->u.zToken[0]) );
290 p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
291 sqlite3Dequote(p->u.zToken);
292}
drhc81c11f2009-11-10 01:30:52 +0000293
drh40aced52016-01-22 17:48:09 +0000294/*
295** Generate a Token object from a string
296*/
297void sqlite3TokenInit(Token *p, char *z){
298 p->z = z;
299 p->n = sqlite3Strlen30(z);
300}
301
drhc81c11f2009-11-10 01:30:52 +0000302/* Convenient short-hand */
303#define UpperToLower sqlite3UpperToLower
304
305/*
306** Some systems have stricmp(). Others have strcasecmp(). Because
307** there is no consistency, we will define our own.
drh9f129f42010-08-31 15:27:32 +0000308**
drh0299b402012-03-19 17:42:46 +0000309** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
310** sqlite3_strnicmp() APIs allow applications and extensions to compare
311** the contents of two buffers containing UTF-8 strings in a
312** case-independent fashion, using the same definition of "case
313** independence" that SQLite uses internally when comparing identifiers.
drhc81c11f2009-11-10 01:30:52 +0000314*/
drh3fa97302012-02-22 16:58:36 +0000315int sqlite3_stricmp(const char *zLeft, const char *zRight){
drh9ca95732014-10-24 00:35:58 +0000316 if( zLeft==0 ){
317 return zRight ? -1 : 0;
318 }else if( zRight==0 ){
319 return 1;
320 }
drh80738d92016-02-15 00:34:16 +0000321 return sqlite3StrICmp(zLeft, zRight);
322}
323int sqlite3StrICmp(const char *zLeft, const char *zRight){
324 unsigned char *a, *b;
drh7e427332019-04-17 11:34:44 +0000325 int c, x;
drhc81c11f2009-11-10 01:30:52 +0000326 a = (unsigned char *)zLeft;
327 b = (unsigned char *)zRight;
drh80738d92016-02-15 00:34:16 +0000328 for(;;){
drh7e427332019-04-17 11:34:44 +0000329 c = *a;
330 x = *b;
331 if( c==x ){
332 if( c==0 ) break;
333 }else{
334 c = (int)UpperToLower[c] - (int)UpperToLower[x];
335 if( c ) break;
336 }
drh80738d92016-02-15 00:34:16 +0000337 a++;
338 b++;
339 }
340 return c;
drhc81c11f2009-11-10 01:30:52 +0000341}
342int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
343 register unsigned char *a, *b;
drh9ca95732014-10-24 00:35:58 +0000344 if( zLeft==0 ){
345 return zRight ? -1 : 0;
346 }else if( zRight==0 ){
347 return 1;
348 }
drhc81c11f2009-11-10 01:30:52 +0000349 a = (unsigned char *)zLeft;
350 b = (unsigned char *)zRight;
351 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
352 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
353}
354
355/*
drh02a43f62017-12-26 14:46:20 +0000356** Compute 10 to the E-th power. Examples: E==1 results in 10.
357** E==2 results in 100. E==50 results in 1.0e50.
358**
359** This routine only works for values of E between 1 and 341.
360*/
361static LONGDOUBLE_TYPE sqlite3Pow10(int E){
drh3dc97272018-01-17 21:14:17 +0000362#if defined(_MSC_VER)
363 static const LONGDOUBLE_TYPE x[] = {
364 1.0e+001,
365 1.0e+002,
366 1.0e+004,
367 1.0e+008,
368 1.0e+016,
369 1.0e+032,
370 1.0e+064,
371 1.0e+128,
372 1.0e+256
373 };
374 LONGDOUBLE_TYPE r = 1.0;
375 int i;
376 assert( E>=0 && E<=307 );
377 for(i=0; E!=0; i++, E >>=1){
378 if( E & 1 ) r *= x[i];
379 }
380 return r;
381#else
drh02a43f62017-12-26 14:46:20 +0000382 LONGDOUBLE_TYPE x = 10.0;
383 LONGDOUBLE_TYPE r = 1.0;
384 while(1){
385 if( E & 1 ) r *= x;
386 E >>= 1;
387 if( E==0 ) break;
388 x *= x;
389 }
390 return r;
drh3dc97272018-01-17 21:14:17 +0000391#endif
drh02a43f62017-12-26 14:46:20 +0000392}
393
394/*
drh9339da12010-09-30 00:50:49 +0000395** The string z[] is an text representation of a real number.
drh025586a2010-09-30 17:33:11 +0000396** Convert this string to a double and write it into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000397**
drh9339da12010-09-30 00:50:49 +0000398** The string z[] is length bytes in length (bytes, not characters) and
399** uses the encoding enc. The string is not necessarily zero-terminated.
drhc81c11f2009-11-10 01:30:52 +0000400**
drh9339da12010-09-30 00:50:49 +0000401** Return TRUE if the result is a valid real number (or integer) and FALSE
drh025586a2010-09-30 17:33:11 +0000402** if the string is empty or contains extraneous text. Valid numbers
403** are in one of these formats:
404**
405** [+-]digits[E[+-]digits]
406** [+-]digits.[digits][E[+-]digits]
407** [+-].digits[E[+-]digits]
408**
409** Leading and trailing whitespace is ignored for the purpose of determining
410** validity.
411**
412** If some prefix of the input string is a valid number, this routine
413** returns FALSE but it still converts the prefix and writes the result
414** into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000415*/
drh9339da12010-09-30 00:50:49 +0000416int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
drhc81c11f2009-11-10 01:30:52 +0000417#ifndef SQLITE_OMIT_FLOATING_POINT
drh0e5fba72013-03-20 12:04:29 +0000418 int incr;
drh9339da12010-09-30 00:50:49 +0000419 const char *zEnd = z + length;
drhc81c11f2009-11-10 01:30:52 +0000420 /* sign * significand * (10 ^ (esign * exponent)) */
drh025586a2010-09-30 17:33:11 +0000421 int sign = 1; /* sign of significand */
422 i64 s = 0; /* significand */
423 int d = 0; /* adjust exponent for shifting decimal point */
424 int esign = 1; /* sign of exponent */
425 int e = 0; /* exponent */
426 int eValid = 1; /* True exponent is either not used or is well-formed */
drhc81c11f2009-11-10 01:30:52 +0000427 double result;
428 int nDigits = 0;
drhad975d52016-04-27 15:24:13 +0000429 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
drhc81c11f2009-11-10 01:30:52 +0000430
drh0e5fba72013-03-20 12:04:29 +0000431 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
drh025586a2010-09-30 17:33:11 +0000432 *pResult = 0.0; /* Default return value, in case of an error */
433
drh0e5fba72013-03-20 12:04:29 +0000434 if( enc==SQLITE_UTF8 ){
435 incr = 1;
436 }else{
437 int i;
438 incr = 2;
439 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
440 for(i=3-enc; i<length && z[i]==0; i+=2){}
441 nonNum = i<length;
drhad975d52016-04-27 15:24:13 +0000442 zEnd = &z[i^1];
drh0e5fba72013-03-20 12:04:29 +0000443 z += (enc&1);
444 }
drh9339da12010-09-30 00:50:49 +0000445
drhc81c11f2009-11-10 01:30:52 +0000446 /* skip leading spaces */
drh9339da12010-09-30 00:50:49 +0000447 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
drh025586a2010-09-30 17:33:11 +0000448 if( z>=zEnd ) return 0;
drh9339da12010-09-30 00:50:49 +0000449
drhc81c11f2009-11-10 01:30:52 +0000450 /* get sign of significand */
451 if( *z=='-' ){
452 sign = -1;
drh9339da12010-09-30 00:50:49 +0000453 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000454 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000455 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000456 }
drh9339da12010-09-30 00:50:49 +0000457
drhc81c11f2009-11-10 01:30:52 +0000458 /* copy max significant digits to significand */
drh9339da12010-09-30 00:50:49 +0000459 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
drhc81c11f2009-11-10 01:30:52 +0000460 s = s*10 + (*z - '0');
drh12f84e52017-11-06 09:34:45 +0000461 z+=incr; nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000462 }
drh9339da12010-09-30 00:50:49 +0000463
drhc81c11f2009-11-10 01:30:52 +0000464 /* skip non-significant significand digits
465 ** (increase exponent by d to shift decimal left) */
drh12f84e52017-11-06 09:34:45 +0000466 while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; nDigits++; d++; }
drh9339da12010-09-30 00:50:49 +0000467 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000468
469 /* if decimal point is present */
470 if( *z=='.' ){
drh9339da12010-09-30 00:50:49 +0000471 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000472 /* copy digits from after decimal to significand
473 ** (decrease exponent by d to shift decimal right) */
drh15af62a2016-04-26 23:14:45 +0000474 while( z<zEnd && sqlite3Isdigit(*z) ){
475 if( s<((LARGEST_INT64-9)/10) ){
476 s = s*10 + (*z - '0');
477 d--;
478 }
drh12f84e52017-11-06 09:34:45 +0000479 z+=incr; nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000480 }
drhc81c11f2009-11-10 01:30:52 +0000481 }
drh9339da12010-09-30 00:50:49 +0000482 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000483
484 /* if exponent is present */
485 if( *z=='e' || *z=='E' ){
drh9339da12010-09-30 00:50:49 +0000486 z+=incr;
drh025586a2010-09-30 17:33:11 +0000487 eValid = 0;
drhad975d52016-04-27 15:24:13 +0000488
489 /* This branch is needed to avoid a (harmless) buffer overread. The
490 ** special comment alerts the mutation tester that the correct answer
491 ** is obtained even if the branch is omitted */
492 if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
493
drhc81c11f2009-11-10 01:30:52 +0000494 /* get sign of exponent */
495 if( *z=='-' ){
496 esign = -1;
drh9339da12010-09-30 00:50:49 +0000497 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000498 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000499 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000500 }
501 /* copy digits to exponent */
drh9339da12010-09-30 00:50:49 +0000502 while( z<zEnd && sqlite3Isdigit(*z) ){
drh57db4a72011-10-17 20:41:46 +0000503 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
drh9339da12010-09-30 00:50:49 +0000504 z+=incr;
drh025586a2010-09-30 17:33:11 +0000505 eValid = 1;
drhc81c11f2009-11-10 01:30:52 +0000506 }
507 }
508
drh025586a2010-09-30 17:33:11 +0000509 /* skip trailing spaces */
drhc6daa012016-04-27 02:35:03 +0000510 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
drh025586a2010-09-30 17:33:11 +0000511
drh9339da12010-09-30 00:50:49 +0000512do_atof_calc:
drhc81c11f2009-11-10 01:30:52 +0000513 /* adjust exponent by d, and update sign */
514 e = (e*esign) + d;
515 if( e<0 ) {
516 esign = -1;
517 e *= -1;
518 } else {
519 esign = 1;
520 }
521
drhad975d52016-04-27 15:24:13 +0000522 if( s==0 ) {
523 /* In the IEEE 754 standard, zero is signed. */
drhc6daa012016-04-27 02:35:03 +0000524 result = sign<0 ? -(double)0 : (double)0;
drhc81c11f2009-11-10 01:30:52 +0000525 } else {
drhad975d52016-04-27 15:24:13 +0000526 /* Attempt to reduce exponent.
527 **
528 ** Branches that are not required for the correct answer but which only
529 ** help to obtain the correct answer faster are marked with special
530 ** comments, as a hint to the mutation tester.
531 */
532 while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
533 if( esign>0 ){
534 if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
535 s *= 10;
536 }else{
537 if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
538 s /= 10;
539 }
540 e--;
drhc81c11f2009-11-10 01:30:52 +0000541 }
542
543 /* adjust the sign of significand */
544 s = sign<0 ? -s : s;
545
drhad975d52016-04-27 15:24:13 +0000546 if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
547 result = (double)s;
548 }else{
drhc81c11f2009-11-10 01:30:52 +0000549 /* attempt to handle extremely small/large numbers better */
drhad975d52016-04-27 15:24:13 +0000550 if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
551 if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
drh02a43f62017-12-26 14:46:20 +0000552 LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
drhad975d52016-04-27 15:24:13 +0000553 if( esign<0 ){
554 result = s / scale;
555 result /= 1.0e+308;
556 }else{
557 result = s * scale;
558 result *= 1.0e+308;
559 }
560 }else{ assert( e>=342 );
561 if( esign<0 ){
562 result = 0.0*s;
563 }else{
drhb9772e72017-09-12 13:27:43 +0000564#ifdef INFINITY
drh3ba18ad2017-09-12 15:05:34 +0000565 result = INFINITY*s;
drhb9772e72017-09-12 13:27:43 +0000566#else
drhad975d52016-04-27 15:24:13 +0000567 result = 1e308*1e308*s; /* Infinity */
drhb9772e72017-09-12 13:27:43 +0000568#endif
drhad975d52016-04-27 15:24:13 +0000569 }
drh2458a2e2011-10-17 12:14:26 +0000570 }
drhc81c11f2009-11-10 01:30:52 +0000571 }else{
drh02a43f62017-12-26 14:46:20 +0000572 LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
drhc81c11f2009-11-10 01:30:52 +0000573 if( esign<0 ){
574 result = s / scale;
575 }else{
576 result = s * scale;
577 }
578 }
drhc81c11f2009-11-10 01:30:52 +0000579 }
580 }
581
582 /* store the result */
583 *pResult = result;
584
drh025586a2010-09-30 17:33:11 +0000585 /* return true if number and no extra non-whitespace chracters after */
drhad975d52016-04-27 15:24:13 +0000586 return z==zEnd && nDigits>0 && eValid && nonNum==0;
drhc81c11f2009-11-10 01:30:52 +0000587#else
shaneh5f1d6b62010-09-30 16:51:25 +0000588 return !sqlite3Atoi64(z, pResult, length, enc);
drhc81c11f2009-11-10 01:30:52 +0000589#endif /* SQLITE_OMIT_FLOATING_POINT */
590}
591
592/*
593** Compare the 19-character string zNum against the text representation
594** value 2^63: 9223372036854775808. Return negative, zero, or positive
595** if zNum is less than, equal to, or greater than the string.
shaneh5f1d6b62010-09-30 16:51:25 +0000596** Note that zNum must contain exactly 19 characters.
drhc81c11f2009-11-10 01:30:52 +0000597**
598** Unlike memcmp() this routine is guaranteed to return the difference
599** in the values of the last digit if the only difference is in the
600** last digit. So, for example,
601**
drh9339da12010-09-30 00:50:49 +0000602** compare2pow63("9223372036854775800", 1)
drhc81c11f2009-11-10 01:30:52 +0000603**
604** will return -8.
605*/
drh9339da12010-09-30 00:50:49 +0000606static int compare2pow63(const char *zNum, int incr){
607 int c = 0;
608 int i;
609 /* 012345678901234567 */
610 const char *pow63 = "922337203685477580";
611 for(i=0; c==0 && i<18; i++){
612 c = (zNum[i*incr]-pow63[i])*10;
613 }
drhc81c11f2009-11-10 01:30:52 +0000614 if( c==0 ){
drh9339da12010-09-30 00:50:49 +0000615 c = zNum[18*incr] - '8';
drh44dbca82010-01-13 04:22:20 +0000616 testcase( c==(-1) );
617 testcase( c==0 );
618 testcase( c==(+1) );
drhc81c11f2009-11-10 01:30:52 +0000619 }
620 return c;
621}
622
drhc81c11f2009-11-10 01:30:52 +0000623/*
drh9296c182014-07-23 13:40:49 +0000624** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
625** routine does *not* accept hexadecimal notation.
drh158b9cb2011-03-05 20:59:46 +0000626**
drh84d4f1a2017-09-20 10:47:10 +0000627** Returns:
drh158b9cb2011-03-05 20:59:46 +0000628**
drh84d4f1a2017-09-20 10:47:10 +0000629** 0 Successful transformation. Fits in a 64-bit signed integer.
drh4eb57ce2018-01-26 18:37:34 +0000630** 1 Excess non-space text after the integer value
drh84d4f1a2017-09-20 10:47:10 +0000631** 2 Integer too large for a 64-bit signed integer or is malformed
632** 3 Special case of 9223372036854775808
drhc81c11f2009-11-10 01:30:52 +0000633**
drh9339da12010-09-30 00:50:49 +0000634** length is the number of bytes in the string (bytes, not characters).
635** The string is not necessarily zero-terminated. The encoding is
636** given by enc.
drhc81c11f2009-11-10 01:30:52 +0000637*/
drh9339da12010-09-30 00:50:49 +0000638int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
drh0e5fba72013-03-20 12:04:29 +0000639 int incr;
drh158b9cb2011-03-05 20:59:46 +0000640 u64 u = 0;
shaneh5f1d6b62010-09-30 16:51:25 +0000641 int neg = 0; /* assume positive */
drh9339da12010-09-30 00:50:49 +0000642 int i;
643 int c = 0;
drh609d5842016-04-28 00:32:16 +0000644 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
drh84d4f1a2017-09-20 10:47:10 +0000645 int rc; /* Baseline return code */
drhc81c11f2009-11-10 01:30:52 +0000646 const char *zStart;
drh9339da12010-09-30 00:50:49 +0000647 const char *zEnd = zNum + length;
drh0e5fba72013-03-20 12:04:29 +0000648 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
649 if( enc==SQLITE_UTF8 ){
650 incr = 1;
651 }else{
652 incr = 2;
653 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
654 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
655 nonNum = i<length;
drh609d5842016-04-28 00:32:16 +0000656 zEnd = &zNum[i^1];
drh0e5fba72013-03-20 12:04:29 +0000657 zNum += (enc&1);
658 }
drh9339da12010-09-30 00:50:49 +0000659 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
drh158b9cb2011-03-05 20:59:46 +0000660 if( zNum<zEnd ){
661 if( *zNum=='-' ){
662 neg = 1;
663 zNum+=incr;
664 }else if( *zNum=='+' ){
665 zNum+=incr;
666 }
drhc81c11f2009-11-10 01:30:52 +0000667 }
668 zStart = zNum;
drh9339da12010-09-30 00:50:49 +0000669 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
670 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
drh158b9cb2011-03-05 20:59:46 +0000671 u = u*10 + c - '0';
drhc81c11f2009-11-10 01:30:52 +0000672 }
drh4eb57ce2018-01-26 18:37:34 +0000673 testcase( i==18*incr );
674 testcase( i==19*incr );
675 testcase( i==20*incr );
drh1822ebf2018-01-27 14:25:27 +0000676 if( u>LARGEST_INT64 ){
677 /* This test and assignment is needed only to suppress UB warnings
678 ** from clang and -fsanitize=undefined. This test and assignment make
679 ** the code a little larger and slower, and no harm comes from omitting
680 ** them, but we must appaise the undefined-behavior pharisees. */
681 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
682 }else if( neg ){
drh158b9cb2011-03-05 20:59:46 +0000683 *pNum = -(i64)u;
684 }else{
685 *pNum = (i64)u;
686 }
drh4eb57ce2018-01-26 18:37:34 +0000687 rc = 0;
688 if( (i==0 && zStart==zNum) /* No digits */
drh609d5842016-04-28 00:32:16 +0000689 || nonNum /* UTF16 with high-order bytes non-zero */
690 ){
drh84d4f1a2017-09-20 10:47:10 +0000691 rc = 1;
drh4eb57ce2018-01-26 18:37:34 +0000692 }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */
693 int jj = i;
694 do{
695 if( !sqlite3Isspace(zNum[jj]) ){
696 rc = 1; /* Extra non-space text after the integer */
697 break;
698 }
699 jj += incr;
700 }while( &zNum[jj]<zEnd );
drh84d4f1a2017-09-20 10:47:10 +0000701 }
drh4eb57ce2018-01-26 18:37:34 +0000702 if( i<19*incr ){
drhc81c11f2009-11-10 01:30:52 +0000703 /* Less than 19 digits, so we know that it fits in 64 bits */
drh158b9cb2011-03-05 20:59:46 +0000704 assert( u<=LARGEST_INT64 );
drh84d4f1a2017-09-20 10:47:10 +0000705 return rc;
drhc81c11f2009-11-10 01:30:52 +0000706 }else{
drh158b9cb2011-03-05 20:59:46 +0000707 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
drh4eb57ce2018-01-26 18:37:34 +0000708 c = i>19*incr ? 1 : compare2pow63(zNum, incr);
drh158b9cb2011-03-05 20:59:46 +0000709 if( c<0 ){
710 /* zNum is less than 9223372036854775808 so it fits */
711 assert( u<=LARGEST_INT64 );
drh84d4f1a2017-09-20 10:47:10 +0000712 return rc;
drh158b9cb2011-03-05 20:59:46 +0000713 }else{
drh4eb57ce2018-01-26 18:37:34 +0000714 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
715 if( c>0 ){
716 /* zNum is greater than 9223372036854775808 so it overflows */
717 return 2;
718 }else{
719 /* zNum is exactly 9223372036854775808. Fits if negative. The
720 ** special case 2 overflow if positive */
721 assert( u-1==LARGEST_INT64 );
722 return neg ? rc : 3;
723 }
drh158b9cb2011-03-05 20:59:46 +0000724 }
drhc81c11f2009-11-10 01:30:52 +0000725 }
726}
727
728/*
drh9296c182014-07-23 13:40:49 +0000729** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
730** into a 64-bit signed integer. This routine accepts hexadecimal literals,
731** whereas sqlite3Atoi64() does not.
732**
733** Returns:
734**
735** 0 Successful transformation. Fits in a 64-bit signed integer.
drh84d4f1a2017-09-20 10:47:10 +0000736** 1 Excess text after the integer value
737** 2 Integer too large for a 64-bit signed integer or is malformed
738** 3 Special case of 9223372036854775808
drh9296c182014-07-23 13:40:49 +0000739*/
740int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
741#ifndef SQLITE_OMIT_HEX_INTEGER
742 if( z[0]=='0'
743 && (z[1]=='x' || z[1]=='X')
drh9296c182014-07-23 13:40:49 +0000744 ){
745 u64 u = 0;
746 int i, k;
747 for(i=2; z[i]=='0'; i++){}
748 for(k=i; sqlite3Isxdigit(z[k]); k++){
749 u = u*16 + sqlite3HexToInt(z[k]);
750 }
751 memcpy(pOut, &u, 8);
drh84d4f1a2017-09-20 10:47:10 +0000752 return (z[k]==0 && k-i<=16) ? 0 : 2;
drh9296c182014-07-23 13:40:49 +0000753 }else
754#endif /* SQLITE_OMIT_HEX_INTEGER */
755 {
756 return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
757 }
758}
759
760/*
drhc81c11f2009-11-10 01:30:52 +0000761** If zNum represents an integer that will fit in 32-bits, then set
762** *pValue to that integer and return true. Otherwise return false.
763**
drh9296c182014-07-23 13:40:49 +0000764** This routine accepts both decimal and hexadecimal notation for integers.
765**
drhc81c11f2009-11-10 01:30:52 +0000766** Any non-numeric characters that following zNum are ignored.
767** This is different from sqlite3Atoi64() which requires the
768** input number to be zero-terminated.
769*/
770int sqlite3GetInt32(const char *zNum, int *pValue){
771 sqlite_int64 v = 0;
772 int i, c;
773 int neg = 0;
774 if( zNum[0]=='-' ){
775 neg = 1;
776 zNum++;
777 }else if( zNum[0]=='+' ){
778 zNum++;
779 }
drh28e048c2014-07-23 01:26:51 +0000780#ifndef SQLITE_OMIT_HEX_INTEGER
781 else if( zNum[0]=='0'
782 && (zNum[1]=='x' || zNum[1]=='X')
783 && sqlite3Isxdigit(zNum[2])
784 ){
785 u32 u = 0;
786 zNum += 2;
787 while( zNum[0]=='0' ) zNum++;
788 for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
789 u = u*16 + sqlite3HexToInt(zNum[i]);
790 }
791 if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
792 memcpy(pValue, &u, 4);
793 return 1;
794 }else{
795 return 0;
796 }
797 }
798#endif
drh313e6fd2017-05-03 17:44:28 +0000799 if( !sqlite3Isdigit(zNum[0]) ) return 0;
drh935f2e72015-04-18 04:45:00 +0000800 while( zNum[0]=='0' ) zNum++;
drhc81c11f2009-11-10 01:30:52 +0000801 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
802 v = v*10 + c;
803 }
804
805 /* The longest decimal representation of a 32 bit integer is 10 digits:
806 **
807 ** 1234567890
808 ** 2^31 -> 2147483648
809 */
drh44dbca82010-01-13 04:22:20 +0000810 testcase( i==10 );
drhc81c11f2009-11-10 01:30:52 +0000811 if( i>10 ){
812 return 0;
813 }
drh44dbca82010-01-13 04:22:20 +0000814 testcase( v-neg==2147483647 );
drhc81c11f2009-11-10 01:30:52 +0000815 if( v-neg>2147483647 ){
816 return 0;
817 }
818 if( neg ){
819 v = -v;
820 }
821 *pValue = (int)v;
822 return 1;
823}
824
825/*
drh60ac3f42010-11-23 18:59:27 +0000826** Return a 32-bit integer value extracted from a string. If the
827** string is not an integer, just return 0.
828*/
829int sqlite3Atoi(const char *z){
830 int x = 0;
831 if( z ) sqlite3GetInt32(z, &x);
832 return x;
833}
834
835/*
drhc81c11f2009-11-10 01:30:52 +0000836** The variable-length integer encoding is as follows:
837**
838** KEY:
839** A = 0xxxxxxx 7 bits of data and one flag bit
840** B = 1xxxxxxx 7 bits of data and one flag bit
841** C = xxxxxxxx 8 bits of data
842**
843** 7 bits - A
844** 14 bits - BA
845** 21 bits - BBA
846** 28 bits - BBBA
847** 35 bits - BBBBA
848** 42 bits - BBBBBA
849** 49 bits - BBBBBBA
850** 56 bits - BBBBBBBA
851** 64 bits - BBBBBBBBC
852*/
853
854/*
855** Write a 64-bit variable-length integer to memory starting at p[0].
856** The length of data write will be between 1 and 9 bytes. The number
857** of bytes written is returned.
858**
859** A variable-length integer consists of the lower 7 bits of each byte
860** for all bytes that have the 8th bit set and one byte with the 8th
861** bit clear. Except, if we get to the 9th byte, it stores the full
862** 8 bits and is the last byte.
863*/
drh2f2b2b82014-08-22 18:48:25 +0000864static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
drhc81c11f2009-11-10 01:30:52 +0000865 int i, j, n;
866 u8 buf[10];
867 if( v & (((u64)0xff000000)<<32) ){
868 p[8] = (u8)v;
869 v >>= 8;
870 for(i=7; i>=0; i--){
871 p[i] = (u8)((v & 0x7f) | 0x80);
872 v >>= 7;
873 }
874 return 9;
875 }
876 n = 0;
877 do{
878 buf[n++] = (u8)((v & 0x7f) | 0x80);
879 v >>= 7;
880 }while( v!=0 );
881 buf[0] &= 0x7f;
882 assert( n<=9 );
883 for(i=0, j=n-1; j>=0; j--, i++){
884 p[i] = buf[j];
885 }
886 return n;
887}
drh2f2b2b82014-08-22 18:48:25 +0000888int sqlite3PutVarint(unsigned char *p, u64 v){
889 if( v<=0x7f ){
890 p[0] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000891 return 1;
892 }
drh2f2b2b82014-08-22 18:48:25 +0000893 if( v<=0x3fff ){
894 p[0] = ((v>>7)&0x7f)|0x80;
895 p[1] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000896 return 2;
897 }
drh2f2b2b82014-08-22 18:48:25 +0000898 return putVarint64(p,v);
drhc81c11f2009-11-10 01:30:52 +0000899}
900
901/*
drh0b2864c2010-03-03 15:18:38 +0000902** Bitmasks used by sqlite3GetVarint(). These precomputed constants
903** are defined here rather than simply putting the constant expressions
904** inline in order to work around bugs in the RVT compiler.
905**
906** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
907**
908** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
909*/
910#define SLOT_2_0 0x001fc07f
911#define SLOT_4_2_0 0xf01fc07f
912
913
914/*
drhc81c11f2009-11-10 01:30:52 +0000915** Read a 64-bit variable-length integer from memory starting at p[0].
916** Return the number of bytes read. The value is stored in *v.
917*/
918u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
919 u32 a,b,s;
920
drh698c86f2019-04-17 12:07:08 +0000921 if( ((signed char*)p)[0]>=0 ){
922 *v = *p;
drhc81c11f2009-11-10 01:30:52 +0000923 return 1;
924 }
drh698c86f2019-04-17 12:07:08 +0000925 if( ((signed char*)p)[1]>=0 ){
926 *v = ((u32)(p[0]&0x7f)<<7) | p[1];
drhc81c11f2009-11-10 01:30:52 +0000927 return 2;
928 }
929
drh0b2864c2010-03-03 15:18:38 +0000930 /* Verify that constants are precomputed correctly */
931 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
shaneh1da207e2010-03-09 14:41:12 +0000932 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
drh0b2864c2010-03-03 15:18:38 +0000933
drh698c86f2019-04-17 12:07:08 +0000934 a = ((u32)p[0])<<14;
935 b = p[1];
936 p += 2;
drhc81c11f2009-11-10 01:30:52 +0000937 a |= *p;
938 /* a: p0<<14 | p2 (unmasked) */
939 if (!(a&0x80))
940 {
drh0b2864c2010-03-03 15:18:38 +0000941 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000942 b &= 0x7f;
943 b = b<<7;
944 a |= b;
945 *v = a;
946 return 3;
947 }
948
949 /* CSE1 from below */
drh0b2864c2010-03-03 15:18:38 +0000950 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000951 p++;
952 b = b<<14;
953 b |= *p;
954 /* b: p1<<14 | p3 (unmasked) */
955 if (!(b&0x80))
956 {
drh0b2864c2010-03-03 15:18:38 +0000957 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000958 /* moved CSE1 up */
959 /* a &= (0x7f<<14)|(0x7f); */
960 a = a<<7;
961 a |= b;
962 *v = a;
963 return 4;
964 }
965
966 /* a: p0<<14 | p2 (masked) */
967 /* b: p1<<14 | p3 (unmasked) */
968 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
969 /* moved CSE1 up */
970 /* a &= (0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +0000971 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000972 s = a;
973 /* s: p0<<14 | p2 (masked) */
974
975 p++;
976 a = a<<14;
977 a |= *p;
978 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
979 if (!(a&0x80))
980 {
drh62aaa6c2015-11-21 17:27:42 +0000981 /* we can skip these cause they were (effectively) done above
982 ** while calculating s */
drhc81c11f2009-11-10 01:30:52 +0000983 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
984 /* b &= (0x7f<<14)|(0x7f); */
985 b = b<<7;
986 a |= b;
987 s = s>>18;
988 *v = ((u64)s)<<32 | a;
989 return 5;
990 }
991
992 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
993 s = s<<7;
994 s |= b;
995 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
996
997 p++;
998 b = b<<14;
999 b |= *p;
1000 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
1001 if (!(b&0x80))
1002 {
1003 /* we can skip this cause it was (effectively) done above in calc'ing s */
1004 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +00001005 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +00001006 a = a<<7;
1007 a |= b;
1008 s = s>>18;
1009 *v = ((u64)s)<<32 | a;
1010 return 6;
1011 }
1012
1013 p++;
1014 a = a<<14;
1015 a |= *p;
1016 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
1017 if (!(a&0x80))
1018 {
drh0b2864c2010-03-03 15:18:38 +00001019 a &= SLOT_4_2_0;
1020 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +00001021 b = b<<7;
1022 a |= b;
1023 s = s>>11;
1024 *v = ((u64)s)<<32 | a;
1025 return 7;
1026 }
1027
1028 /* CSE2 from below */
drh0b2864c2010-03-03 15:18:38 +00001029 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +00001030 p++;
1031 b = b<<14;
1032 b |= *p;
1033 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
1034 if (!(b&0x80))
1035 {
drh0b2864c2010-03-03 15:18:38 +00001036 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +00001037 /* moved CSE2 up */
1038 /* a &= (0x7f<<14)|(0x7f); */
1039 a = a<<7;
1040 a |= b;
1041 s = s>>4;
1042 *v = ((u64)s)<<32 | a;
1043 return 8;
1044 }
1045
1046 p++;
1047 a = a<<15;
1048 a |= *p;
1049 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
1050
1051 /* moved CSE2 up */
1052 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
drh0b2864c2010-03-03 15:18:38 +00001053 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +00001054 b = b<<8;
1055 a |= b;
1056
1057 s = s<<4;
1058 b = p[-4];
1059 b &= 0x7f;
1060 b = b>>3;
1061 s |= b;
1062
1063 *v = ((u64)s)<<32 | a;
1064
1065 return 9;
1066}
1067
1068/*
1069** Read a 32-bit variable-length integer from memory starting at p[0].
1070** Return the number of bytes read. The value is stored in *v.
1071**
1072** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
1073** integer, then set *v to 0xffffffff.
1074**
1075** A MACRO version, getVarint32, is provided which inlines the
1076** single-byte case. All code should use the MACRO version as
1077** this function assumes the single-byte case has already been handled.
1078*/
1079u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
1080 u32 a,b;
1081
1082 /* The 1-byte case. Overwhelmingly the most common. Handled inline
1083 ** by the getVarin32() macro */
1084 a = *p;
1085 /* a: p0 (unmasked) */
1086#ifndef getVarint32
1087 if (!(a&0x80))
1088 {
1089 /* Values between 0 and 127 */
1090 *v = a;
1091 return 1;
1092 }
1093#endif
1094
1095 /* The 2-byte case */
1096 p++;
1097 b = *p;
1098 /* b: p1 (unmasked) */
1099 if (!(b&0x80))
1100 {
1101 /* Values between 128 and 16383 */
1102 a &= 0x7f;
1103 a = a<<7;
1104 *v = a | b;
1105 return 2;
1106 }
1107
1108 /* The 3-byte case */
1109 p++;
1110 a = a<<14;
1111 a |= *p;
1112 /* a: p0<<14 | p2 (unmasked) */
1113 if (!(a&0x80))
1114 {
1115 /* Values between 16384 and 2097151 */
1116 a &= (0x7f<<14)|(0x7f);
1117 b &= 0x7f;
1118 b = b<<7;
1119 *v = a | b;
1120 return 3;
1121 }
1122
1123 /* A 32-bit varint is used to store size information in btrees.
1124 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
1125 ** A 3-byte varint is sufficient, for example, to record the size
1126 ** of a 1048569-byte BLOB or string.
1127 **
1128 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
1129 ** rare larger cases can be handled by the slower 64-bit varint
1130 ** routine.
1131 */
1132#if 1
1133 {
1134 u64 v64;
1135 u8 n;
1136
1137 p -= 2;
1138 n = sqlite3GetVarint(p, &v64);
1139 assert( n>3 && n<=9 );
1140 if( (v64 & SQLITE_MAX_U32)!=v64 ){
1141 *v = 0xffffffff;
1142 }else{
1143 *v = (u32)v64;
1144 }
1145 return n;
1146 }
1147
1148#else
1149 /* For following code (kept for historical record only) shows an
1150 ** unrolling for the 3- and 4-byte varint cases. This code is
1151 ** slightly faster, but it is also larger and much harder to test.
1152 */
1153 p++;
1154 b = b<<14;
1155 b |= *p;
1156 /* b: p1<<14 | p3 (unmasked) */
1157 if (!(b&0x80))
1158 {
1159 /* Values between 2097152 and 268435455 */
1160 b &= (0x7f<<14)|(0x7f);
1161 a &= (0x7f<<14)|(0x7f);
1162 a = a<<7;
1163 *v = a | b;
1164 return 4;
1165 }
1166
1167 p++;
1168 a = a<<14;
1169 a |= *p;
1170 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1171 if (!(a&0x80))
1172 {
dan3bbe7612010-03-03 16:02:05 +00001173 /* Values between 268435456 and 34359738367 */
1174 a &= SLOT_4_2_0;
1175 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +00001176 b = b<<7;
1177 *v = a | b;
1178 return 5;
1179 }
1180
1181 /* We can only reach this point when reading a corrupt database
1182 ** file. In that case we are not in any hurry. Use the (relatively
1183 ** slow) general-purpose sqlite3GetVarint() routine to extract the
1184 ** value. */
1185 {
1186 u64 v64;
1187 u8 n;
1188
1189 p -= 4;
1190 n = sqlite3GetVarint(p, &v64);
1191 assert( n>5 && n<=9 );
1192 *v = (u32)v64;
1193 return n;
1194 }
1195#endif
1196}
1197
1198/*
1199** Return the number of bytes that will be needed to store the given
1200** 64-bit integer.
1201*/
1202int sqlite3VarintLen(u64 v){
drh59a53642015-09-01 22:29:07 +00001203 int i;
drh6f17c092016-03-04 21:18:09 +00001204 for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
drhc81c11f2009-11-10 01:30:52 +00001205 return i;
1206}
1207
1208
1209/*
1210** Read or write a four-byte big-endian integer value.
1211*/
1212u32 sqlite3Get4byte(const u8 *p){
drh5372e4d2015-06-30 12:47:09 +00001213#if SQLITE_BYTEORDER==4321
1214 u32 x;
1215 memcpy(&x,p,4);
1216 return x;
drhdc5ece82017-02-15 15:09:09 +00001217#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:09 +00001218 u32 x;
1219 memcpy(&x,p,4);
1220 return __builtin_bswap32(x);
drha39284b2017-02-09 17:12:22 +00001221#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
mistachkin647ca462015-06-30 17:28:40 +00001222 u32 x;
1223 memcpy(&x,p,4);
1224 return _byteswap_ulong(x);
drh5372e4d2015-06-30 12:47:09 +00001225#else
drh693e6712014-01-24 22:58:00 +00001226 testcase( p[0]&0x80 );
1227 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
drh5372e4d2015-06-30 12:47:09 +00001228#endif
drhc81c11f2009-11-10 01:30:52 +00001229}
1230void sqlite3Put4byte(unsigned char *p, u32 v){
drh5372e4d2015-06-30 12:47:09 +00001231#if SQLITE_BYTEORDER==4321
1232 memcpy(p,&v,4);
drhdc5ece82017-02-15 15:09:09 +00001233#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:09 +00001234 u32 x = __builtin_bswap32(v);
1235 memcpy(p,&x,4);
drha39284b2017-02-09 17:12:22 +00001236#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
mistachkin647ca462015-06-30 17:28:40 +00001237 u32 x = _byteswap_ulong(v);
1238 memcpy(p,&x,4);
drh5372e4d2015-06-30 12:47:09 +00001239#else
drhc81c11f2009-11-10 01:30:52 +00001240 p[0] = (u8)(v>>24);
1241 p[1] = (u8)(v>>16);
1242 p[2] = (u8)(v>>8);
1243 p[3] = (u8)v;
drh5372e4d2015-06-30 12:47:09 +00001244#endif
drhc81c11f2009-11-10 01:30:52 +00001245}
1246
drh9296c182014-07-23 13:40:49 +00001247
1248
1249/*
1250** Translate a single byte of Hex into an integer.
1251** This routine only works if h really is a valid hexadecimal
1252** character: 0..9a..fA..F
1253*/
1254u8 sqlite3HexToInt(int h){
1255 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
1256#ifdef SQLITE_ASCII
1257 h += 9*(1&(h>>6));
1258#endif
1259#ifdef SQLITE_EBCDIC
1260 h += 9*(1&~(h>>4));
1261#endif
1262 return (u8)(h & 0xf);
1263}
1264
drhc81c11f2009-11-10 01:30:52 +00001265#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
1266/*
1267** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
1268** value. Return a pointer to its binary value. Space to hold the
1269** binary value has been obtained from malloc and must be freed by
1270** the calling routine.
1271*/
1272void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
1273 char *zBlob;
1274 int i;
1275
drh575fad62016-02-05 13:38:36 +00001276 zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
drhc81c11f2009-11-10 01:30:52 +00001277 n--;
1278 if( zBlob ){
1279 for(i=0; i<n; i+=2){
dancd74b612011-04-22 19:37:32 +00001280 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
drhc81c11f2009-11-10 01:30:52 +00001281 }
1282 zBlob[i/2] = 0;
1283 }
1284 return zBlob;
1285}
1286#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
1287
drh413c3d32010-02-23 20:11:56 +00001288/*
1289** Log an error that is an API call on a connection pointer that should
1290** not have been used. The "type" of connection pointer is given as the
1291** argument. The zType is a word like "NULL" or "closed" or "invalid".
1292*/
1293static void logBadConnection(const char *zType){
1294 sqlite3_log(SQLITE_MISUSE,
1295 "API call with %s database connection pointer",
1296 zType
1297 );
1298}
drhc81c11f2009-11-10 01:30:52 +00001299
1300/*
drhc81c11f2009-11-10 01:30:52 +00001301** Check to make sure we have a valid db pointer. This test is not
1302** foolproof but it does provide some measure of protection against
1303** misuse of the interface such as passing in db pointers that are
1304** NULL or which have been previously closed. If this routine returns
1305** 1 it means that the db pointer is valid and 0 if it should not be
1306** dereferenced for any reason. The calling function should invoke
1307** SQLITE_MISUSE immediately.
1308**
1309** sqlite3SafetyCheckOk() requires that the db pointer be valid for
1310** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
1311** open properly and is not fit for general use but which can be
1312** used as an argument to sqlite3_errmsg() or sqlite3_close().
1313*/
1314int sqlite3SafetyCheckOk(sqlite3 *db){
1315 u32 magic;
drh413c3d32010-02-23 20:11:56 +00001316 if( db==0 ){
1317 logBadConnection("NULL");
1318 return 0;
1319 }
drhc81c11f2009-11-10 01:30:52 +00001320 magic = db->magic;
drh9978c972010-02-23 17:36:32 +00001321 if( magic!=SQLITE_MAGIC_OPEN ){
drhe294da02010-02-25 23:44:15 +00001322 if( sqlite3SafetyCheckSickOrOk(db) ){
1323 testcase( sqlite3GlobalConfig.xLog!=0 );
drh413c3d32010-02-23 20:11:56 +00001324 logBadConnection("unopened");
1325 }
drhc81c11f2009-11-10 01:30:52 +00001326 return 0;
1327 }else{
1328 return 1;
1329 }
1330}
1331int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
1332 u32 magic;
1333 magic = db->magic;
1334 if( magic!=SQLITE_MAGIC_SICK &&
1335 magic!=SQLITE_MAGIC_OPEN &&
drh413c3d32010-02-23 20:11:56 +00001336 magic!=SQLITE_MAGIC_BUSY ){
drhe294da02010-02-25 23:44:15 +00001337 testcase( sqlite3GlobalConfig.xLog!=0 );
drhaf46dc12010-02-24 21:44:07 +00001338 logBadConnection("invalid");
drh413c3d32010-02-23 20:11:56 +00001339 return 0;
1340 }else{
1341 return 1;
1342 }
drhc81c11f2009-11-10 01:30:52 +00001343}
drh158b9cb2011-03-05 20:59:46 +00001344
1345/*
1346** Attempt to add, substract, or multiply the 64-bit signed value iB against
1347** the other 64-bit signed integer at *pA and store the result in *pA.
1348** Return 0 on success. Or if the operation would have resulted in an
1349** overflow, leave *pA unchanged and return 1.
1350*/
1351int sqlite3AddInt64(i64 *pA, i64 iB){
drhb9772e72017-09-12 13:27:43 +00001352#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
drh4a477612017-01-03 17:33:43 +00001353 return __builtin_add_overflow(*pA, iB, pA);
1354#else
drh158b9cb2011-03-05 20:59:46 +00001355 i64 iA = *pA;
1356 testcase( iA==0 ); testcase( iA==1 );
1357 testcase( iB==-1 ); testcase( iB==0 );
1358 if( iB>=0 ){
1359 testcase( iA>0 && LARGEST_INT64 - iA == iB );
1360 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
1361 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001362 }else{
1363 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
1364 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
1365 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001366 }
drh53a6eb32014-02-10 12:59:15 +00001367 *pA += iB;
drh158b9cb2011-03-05 20:59:46 +00001368 return 0;
drh4a477612017-01-03 17:33:43 +00001369#endif
drh158b9cb2011-03-05 20:59:46 +00001370}
1371int sqlite3SubInt64(i64 *pA, i64 iB){
drhb9772e72017-09-12 13:27:43 +00001372#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
drh4a477612017-01-03 17:33:43 +00001373 return __builtin_sub_overflow(*pA, iB, pA);
1374#else
drh158b9cb2011-03-05 20:59:46 +00001375 testcase( iB==SMALLEST_INT64+1 );
1376 if( iB==SMALLEST_INT64 ){
1377 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
1378 if( (*pA)>=0 ) return 1;
1379 *pA -= iB;
1380 return 0;
1381 }else{
1382 return sqlite3AddInt64(pA, -iB);
1383 }
drh4a477612017-01-03 17:33:43 +00001384#endif
drh158b9cb2011-03-05 20:59:46 +00001385}
drh158b9cb2011-03-05 20:59:46 +00001386int sqlite3MulInt64(i64 *pA, i64 iB){
drhb9772e72017-09-12 13:27:43 +00001387#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
drh4a477612017-01-03 17:33:43 +00001388 return __builtin_mul_overflow(*pA, iB, pA);
1389#else
drh158b9cb2011-03-05 20:59:46 +00001390 i64 iA = *pA;
drh09952c62016-09-20 22:04:05 +00001391 if( iB>0 ){
1392 if( iA>LARGEST_INT64/iB ) return 1;
1393 if( iA<SMALLEST_INT64/iB ) return 1;
1394 }else if( iB<0 ){
1395 if( iA>0 ){
1396 if( iB<SMALLEST_INT64/iA ) return 1;
1397 }else if( iA<0 ){
1398 if( iB==SMALLEST_INT64 ) return 1;
1399 if( iA==SMALLEST_INT64 ) return 1;
1400 if( -iA>LARGEST_INT64/-iB ) return 1;
drh53a6eb32014-02-10 12:59:15 +00001401 }
drh53a6eb32014-02-10 12:59:15 +00001402 }
drh09952c62016-09-20 22:04:05 +00001403 *pA = iA*iB;
drh158b9cb2011-03-05 20:59:46 +00001404 return 0;
drh4a477612017-01-03 17:33:43 +00001405#endif
drh158b9cb2011-03-05 20:59:46 +00001406}
drhd50ffc42011-03-08 02:38:28 +00001407
1408/*
1409** Compute the absolute value of a 32-bit signed integer, of possible. Or
1410** if the integer has a value of -2147483648, return +2147483647
1411*/
1412int sqlite3AbsInt32(int x){
1413 if( x>=0 ) return x;
drh87e79ae2011-03-08 13:06:41 +00001414 if( x==(int)0x80000000 ) return 0x7fffffff;
drhd50ffc42011-03-08 02:38:28 +00001415 return -x;
1416}
drh81cc5162011-05-17 20:36:21 +00001417
1418#ifdef SQLITE_ENABLE_8_3_NAMES
1419/*
drhb51bf432011-07-21 21:29:35 +00001420** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
drh81cc5162011-05-17 20:36:21 +00001421** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
1422** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
1423** three characters, then shorten the suffix on z[] to be the last three
1424** characters of the original suffix.
1425**
drhb51bf432011-07-21 21:29:35 +00001426** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
1427** do the suffix shortening regardless of URI parameter.
1428**
drh81cc5162011-05-17 20:36:21 +00001429** Examples:
1430**
1431** test.db-journal => test.nal
1432** test.db-wal => test.wal
1433** test.db-shm => test.shm
drhf5808602011-12-16 00:33:04 +00001434** test.db-mj7f3319fa => test.9fa
drh81cc5162011-05-17 20:36:21 +00001435*/
1436void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
drhb51bf432011-07-21 21:29:35 +00001437#if SQLITE_ENABLE_8_3_NAMES<2
drh7d39e172012-01-02 12:41:53 +00001438 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
drhb51bf432011-07-21 21:29:35 +00001439#endif
1440 {
drh81cc5162011-05-17 20:36:21 +00001441 int i, sz;
1442 sz = sqlite3Strlen30(z);
drhc83f2d42011-05-18 02:41:10 +00001443 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
drhc02a43a2012-01-10 23:18:38 +00001444 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
drh81cc5162011-05-17 20:36:21 +00001445 }
1446}
1447#endif
drhbf539c42013-10-05 18:16:02 +00001448
1449/*
1450** Find (an approximate) sum of two LogEst values. This computation is
1451** not a simple "+" operator because LogEst is stored as a logarithmic
1452** value.
1453**
1454*/
1455LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
1456 static const unsigned char x[] = {
1457 10, 10, /* 0,1 */
1458 9, 9, /* 2,3 */
1459 8, 8, /* 4,5 */
1460 7, 7, 7, /* 6,7,8 */
1461 6, 6, 6, /* 9,10,11 */
1462 5, 5, 5, /* 12-14 */
1463 4, 4, 4, 4, /* 15-18 */
1464 3, 3, 3, 3, 3, 3, /* 19-24 */
1465 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
1466 };
1467 if( a>=b ){
1468 if( a>b+49 ) return a;
1469 if( a>b+31 ) return a+1;
1470 return a+x[a-b];
1471 }else{
1472 if( b>a+49 ) return b;
1473 if( b>a+31 ) return b+1;
1474 return b+x[b-a];
1475 }
1476}
1477
1478/*
drh224155d2014-04-30 13:19:09 +00001479** Convert an integer into a LogEst. In other words, compute an
1480** approximation for 10*log2(x).
drhbf539c42013-10-05 18:16:02 +00001481*/
1482LogEst sqlite3LogEst(u64 x){
1483 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1484 LogEst y = 40;
1485 if( x<8 ){
1486 if( x<2 ) return 0;
1487 while( x<8 ){ y -= 10; x <<= 1; }
1488 }else{
drhceb4b1d2017-08-17 20:53:07 +00001489#if GCC_VERSION>=5004000
1490 int i = 60 - __builtin_clzll(x);
1491 y += i*10;
1492 x >>= i;
1493#else
drh75ab50c2016-04-28 14:15:12 +00001494 while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
drhbf539c42013-10-05 18:16:02 +00001495 while( x>15 ){ y += 10; x >>= 1; }
drhceb4b1d2017-08-17 20:53:07 +00001496#endif
drhbf539c42013-10-05 18:16:02 +00001497 }
1498 return a[x&7] + y - 10;
1499}
1500
1501#ifndef SQLITE_OMIT_VIRTUALTABLE
1502/*
1503** Convert a double into a LogEst
1504** In other words, compute an approximation for 10*log2(x).
1505*/
1506LogEst sqlite3LogEstFromDouble(double x){
1507 u64 a;
1508 LogEst e;
1509 assert( sizeof(x)==8 && sizeof(a)==8 );
1510 if( x<=1 ) return 0;
1511 if( x<=2000000000 ) return sqlite3LogEst((u64)x);
1512 memcpy(&a, &x, 8);
1513 e = (a>>52) - 1022;
1514 return e*10;
1515}
1516#endif /* SQLITE_OMIT_VIRTUALTABLE */
1517
drh14bfd992016-03-05 14:00:09 +00001518#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
drhd566c952016-02-25 21:19:03 +00001519 defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
1520 defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
drhbf539c42013-10-05 18:16:02 +00001521/*
1522** Convert a LogEst into an integer.
drhd566c952016-02-25 21:19:03 +00001523**
1524** Note that this routine is only used when one or more of various
1525** non-standard compile-time options is enabled.
drhbf539c42013-10-05 18:16:02 +00001526*/
1527u64 sqlite3LogEstToInt(LogEst x){
1528 u64 n;
drhbf539c42013-10-05 18:16:02 +00001529 n = x%10;
1530 x /= 10;
1531 if( n>=5 ) n -= 2;
1532 else if( n>=1 ) n -= 1;
drhecdf20d2016-03-10 14:28:24 +00001533#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
1534 defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
1535 if( x>60 ) return (u64)LARGEST_INT64;
1536#else
1537 /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
1538 ** possible to this routine is 310, resulting in a maximum x of 31 */
1539 assert( x<=60 );
1540#endif
1541 return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
drhbf539c42013-10-05 18:16:02 +00001542}
drhd566c952016-02-25 21:19:03 +00001543#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
drh9bf755c2016-12-23 03:59:31 +00001544
1545/*
1546** Add a new name/number pair to a VList. This might require that the
1547** VList object be reallocated, so return the new VList. If an OOM
drhce1bbe52016-12-23 13:52:45 +00001548** error occurs, the original VList returned and the
drh9bf755c2016-12-23 03:59:31 +00001549** db->mallocFailed flag is set.
1550**
1551** A VList is really just an array of integers. To destroy a VList,
1552** simply pass it to sqlite3DbFree().
1553**
1554** The first integer is the number of integers allocated for the whole
1555** VList. The second integer is the number of integers actually used.
1556** Each name/number pair is encoded by subsequent groups of 3 or more
1557** integers.
1558**
drhce1bbe52016-12-23 13:52:45 +00001559** Each name/number pair starts with two integers which are the numeric
drh9bf755c2016-12-23 03:59:31 +00001560** value for the pair and the size of the name/number pair, respectively.
1561** The text name overlays one or more following integers. The text name
1562** is always zero-terminated.
drhce1bbe52016-12-23 13:52:45 +00001563**
1564** Conceptually:
1565**
1566** struct VList {
1567** int nAlloc; // Number of allocated slots
1568** int nUsed; // Number of used slots
1569** struct VListEntry {
1570** int iValue; // Value for this entry
1571** int nSlot; // Slots used by this entry
1572** // ... variable name goes here
1573** } a[0];
1574** }
1575**
1576** During code generation, pointers to the variable names within the
1577** VList are taken. When that happens, nAlloc is set to zero as an
1578** indication that the VList may never again be enlarged, since the
1579** accompanying realloc() would invalidate the pointers.
drh9bf755c2016-12-23 03:59:31 +00001580*/
1581VList *sqlite3VListAdd(
1582 sqlite3 *db, /* The database connection used for malloc() */
1583 VList *pIn, /* The input VList. Might be NULL */
1584 const char *zName, /* Name of symbol to add */
1585 int nName, /* Bytes of text in zName */
1586 int iVal /* Value to associate with zName */
1587){
1588 int nInt; /* number of sizeof(int) objects needed for zName */
drhce1bbe52016-12-23 13:52:45 +00001589 char *z; /* Pointer to where zName will be stored */
1590 int i; /* Index in pIn[] where zName is stored */
drh9bf755c2016-12-23 03:59:31 +00001591
1592 nInt = nName/4 + 3;
drhce1bbe52016-12-23 13:52:45 +00001593 assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
drh9bf755c2016-12-23 03:59:31 +00001594 if( pIn==0 || pIn[1]+nInt > pIn[0] ){
1595 /* Enlarge the allocation */
drh0aa32312019-04-13 04:01:12 +00001596 sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
drh9bf755c2016-12-23 03:59:31 +00001597 VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
drhce1bbe52016-12-23 13:52:45 +00001598 if( pOut==0 ) return pIn;
drh9bf755c2016-12-23 03:59:31 +00001599 if( pIn==0 ) pOut[1] = 2;
1600 pIn = pOut;
1601 pIn[0] = nAlloc;
1602 }
1603 i = pIn[1];
1604 pIn[i] = iVal;
1605 pIn[i+1] = nInt;
1606 z = (char*)&pIn[i+2];
1607 pIn[1] = i+nInt;
1608 assert( pIn[1]<=pIn[0] );
1609 memcpy(z, zName, nName);
1610 z[nName] = 0;
1611 return pIn;
1612}
1613
1614/*
1615** Return a pointer to the name of a variable in the given VList that
1616** has the value iVal. Or return a NULL if there is no such variable in
1617** the list
1618*/
1619const char *sqlite3VListNumToName(VList *pIn, int iVal){
1620 int i, mx;
1621 if( pIn==0 ) return 0;
1622 mx = pIn[1];
1623 i = 2;
1624 do{
1625 if( pIn[i]==iVal ) return (char*)&pIn[i+2];
1626 i += pIn[i+1];
1627 }while( i<mx );
1628 return 0;
1629}
1630
1631/*
1632** Return the number of the variable named zName, if it is in VList.
1633** or return 0 if there is no such variable.
1634*/
1635int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
1636 int i, mx;
1637 if( pIn==0 ) return 0;
1638 mx = pIn[1];
1639 i = 2;
1640 do{
1641 const char *z = (const char*)&pIn[i+2];
1642 if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
1643 i += pIn[i+1];
1644 }while( i<mx );
1645 return 0;
1646}