blob: 81d3bf36bc09bc0a9c028fac41818964ab6046cb [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;
325 int c;
drhc81c11f2009-11-10 01:30:52 +0000326 a = (unsigned char *)zLeft;
327 b = (unsigned char *)zRight;
drh80738d92016-02-15 00:34:16 +0000328 for(;;){
329 c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
330 if( c || *a==0 ) break;
331 a++;
332 b++;
333 }
334 return c;
drhc81c11f2009-11-10 01:30:52 +0000335}
336int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
337 register unsigned char *a, *b;
drh9ca95732014-10-24 00:35:58 +0000338 if( zLeft==0 ){
339 return zRight ? -1 : 0;
340 }else if( zRight==0 ){
341 return 1;
342 }
drhc81c11f2009-11-10 01:30:52 +0000343 a = (unsigned char *)zLeft;
344 b = (unsigned char *)zRight;
345 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
346 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
347}
348
349/*
drh02a43f62017-12-26 14:46:20 +0000350** Compute 10 to the E-th power. Examples: E==1 results in 10.
351** E==2 results in 100. E==50 results in 1.0e50.
352**
353** This routine only works for values of E between 1 and 341.
354*/
355static LONGDOUBLE_TYPE sqlite3Pow10(int E){
drh3dc97272018-01-17 21:14:17 +0000356#if defined(_MSC_VER)
357 static const LONGDOUBLE_TYPE x[] = {
358 1.0e+001,
359 1.0e+002,
360 1.0e+004,
361 1.0e+008,
362 1.0e+016,
363 1.0e+032,
364 1.0e+064,
365 1.0e+128,
366 1.0e+256
367 };
368 LONGDOUBLE_TYPE r = 1.0;
369 int i;
370 assert( E>=0 && E<=307 );
371 for(i=0; E!=0; i++, E >>=1){
372 if( E & 1 ) r *= x[i];
373 }
374 return r;
375#else
drh02a43f62017-12-26 14:46:20 +0000376 LONGDOUBLE_TYPE x = 10.0;
377 LONGDOUBLE_TYPE r = 1.0;
378 while(1){
379 if( E & 1 ) r *= x;
380 E >>= 1;
381 if( E==0 ) break;
382 x *= x;
383 }
384 return r;
drh3dc97272018-01-17 21:14:17 +0000385#endif
drh02a43f62017-12-26 14:46:20 +0000386}
387
388/*
drh9339da12010-09-30 00:50:49 +0000389** The string z[] is an text representation of a real number.
drh025586a2010-09-30 17:33:11 +0000390** Convert this string to a double and write it into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000391**
drh9339da12010-09-30 00:50:49 +0000392** The string z[] is length bytes in length (bytes, not characters) and
393** uses the encoding enc. The string is not necessarily zero-terminated.
drhc81c11f2009-11-10 01:30:52 +0000394**
drh9339da12010-09-30 00:50:49 +0000395** Return TRUE if the result is a valid real number (or integer) and FALSE
drh025586a2010-09-30 17:33:11 +0000396** if the string is empty or contains extraneous text. Valid numbers
397** are in one of these formats:
398**
399** [+-]digits[E[+-]digits]
400** [+-]digits.[digits][E[+-]digits]
401** [+-].digits[E[+-]digits]
402**
403** Leading and trailing whitespace is ignored for the purpose of determining
404** validity.
405**
406** If some prefix of the input string is a valid number, this routine
407** returns FALSE but it still converts the prefix and writes the result
408** into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000409*/
drh9339da12010-09-30 00:50:49 +0000410int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
drhc81c11f2009-11-10 01:30:52 +0000411#ifndef SQLITE_OMIT_FLOATING_POINT
drh0e5fba72013-03-20 12:04:29 +0000412 int incr;
drh9339da12010-09-30 00:50:49 +0000413 const char *zEnd = z + length;
drhc81c11f2009-11-10 01:30:52 +0000414 /* sign * significand * (10 ^ (esign * exponent)) */
drh025586a2010-09-30 17:33:11 +0000415 int sign = 1; /* sign of significand */
416 i64 s = 0; /* significand */
417 int d = 0; /* adjust exponent for shifting decimal point */
418 int esign = 1; /* sign of exponent */
419 int e = 0; /* exponent */
420 int eValid = 1; /* True exponent is either not used or is well-formed */
drhc81c11f2009-11-10 01:30:52 +0000421 double result;
422 int nDigits = 0;
drhad975d52016-04-27 15:24:13 +0000423 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
drhc81c11f2009-11-10 01:30:52 +0000424
drh0e5fba72013-03-20 12:04:29 +0000425 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
drh025586a2010-09-30 17:33:11 +0000426 *pResult = 0.0; /* Default return value, in case of an error */
427
drh0e5fba72013-03-20 12:04:29 +0000428 if( enc==SQLITE_UTF8 ){
429 incr = 1;
430 }else{
431 int i;
432 incr = 2;
433 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
434 for(i=3-enc; i<length && z[i]==0; i+=2){}
435 nonNum = i<length;
drhad975d52016-04-27 15:24:13 +0000436 zEnd = &z[i^1];
drh0e5fba72013-03-20 12:04:29 +0000437 z += (enc&1);
438 }
drh9339da12010-09-30 00:50:49 +0000439
drhc81c11f2009-11-10 01:30:52 +0000440 /* skip leading spaces */
drh9339da12010-09-30 00:50:49 +0000441 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
drh025586a2010-09-30 17:33:11 +0000442 if( z>=zEnd ) return 0;
drh9339da12010-09-30 00:50:49 +0000443
drhc81c11f2009-11-10 01:30:52 +0000444 /* get sign of significand */
445 if( *z=='-' ){
446 sign = -1;
drh9339da12010-09-30 00:50:49 +0000447 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000448 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000449 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000450 }
drh9339da12010-09-30 00:50:49 +0000451
drhc81c11f2009-11-10 01:30:52 +0000452 /* copy max significant digits to significand */
drh9339da12010-09-30 00:50:49 +0000453 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
drhc81c11f2009-11-10 01:30:52 +0000454 s = s*10 + (*z - '0');
drh12f84e52017-11-06 09:34:45 +0000455 z+=incr; nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000456 }
drh9339da12010-09-30 00:50:49 +0000457
drhc81c11f2009-11-10 01:30:52 +0000458 /* skip non-significant significand digits
459 ** (increase exponent by d to shift decimal left) */
drh12f84e52017-11-06 09:34:45 +0000460 while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; nDigits++; d++; }
drh9339da12010-09-30 00:50:49 +0000461 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000462
463 /* if decimal point is present */
464 if( *z=='.' ){
drh9339da12010-09-30 00:50:49 +0000465 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000466 /* copy digits from after decimal to significand
467 ** (decrease exponent by d to shift decimal right) */
drh15af62a2016-04-26 23:14:45 +0000468 while( z<zEnd && sqlite3Isdigit(*z) ){
469 if( s<((LARGEST_INT64-9)/10) ){
470 s = s*10 + (*z - '0');
471 d--;
472 }
drh12f84e52017-11-06 09:34:45 +0000473 z+=incr; nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000474 }
drhc81c11f2009-11-10 01:30:52 +0000475 }
drh9339da12010-09-30 00:50:49 +0000476 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000477
478 /* if exponent is present */
479 if( *z=='e' || *z=='E' ){
drh9339da12010-09-30 00:50:49 +0000480 z+=incr;
drh025586a2010-09-30 17:33:11 +0000481 eValid = 0;
drhad975d52016-04-27 15:24:13 +0000482
483 /* This branch is needed to avoid a (harmless) buffer overread. The
484 ** special comment alerts the mutation tester that the correct answer
485 ** is obtained even if the branch is omitted */
486 if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
487
drhc81c11f2009-11-10 01:30:52 +0000488 /* get sign of exponent */
489 if( *z=='-' ){
490 esign = -1;
drh9339da12010-09-30 00:50:49 +0000491 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000492 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000493 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000494 }
495 /* copy digits to exponent */
drh9339da12010-09-30 00:50:49 +0000496 while( z<zEnd && sqlite3Isdigit(*z) ){
drh57db4a72011-10-17 20:41:46 +0000497 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
drh9339da12010-09-30 00:50:49 +0000498 z+=incr;
drh025586a2010-09-30 17:33:11 +0000499 eValid = 1;
drhc81c11f2009-11-10 01:30:52 +0000500 }
501 }
502
drh025586a2010-09-30 17:33:11 +0000503 /* skip trailing spaces */
drhc6daa012016-04-27 02:35:03 +0000504 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
drh025586a2010-09-30 17:33:11 +0000505
drh9339da12010-09-30 00:50:49 +0000506do_atof_calc:
drhc81c11f2009-11-10 01:30:52 +0000507 /* adjust exponent by d, and update sign */
508 e = (e*esign) + d;
509 if( e<0 ) {
510 esign = -1;
511 e *= -1;
512 } else {
513 esign = 1;
514 }
515
drhad975d52016-04-27 15:24:13 +0000516 if( s==0 ) {
517 /* In the IEEE 754 standard, zero is signed. */
drhc6daa012016-04-27 02:35:03 +0000518 result = sign<0 ? -(double)0 : (double)0;
drhc81c11f2009-11-10 01:30:52 +0000519 } else {
drhad975d52016-04-27 15:24:13 +0000520 /* Attempt to reduce exponent.
521 **
522 ** Branches that are not required for the correct answer but which only
523 ** help to obtain the correct answer faster are marked with special
524 ** comments, as a hint to the mutation tester.
525 */
526 while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
527 if( esign>0 ){
528 if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
529 s *= 10;
530 }else{
531 if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
532 s /= 10;
533 }
534 e--;
drhc81c11f2009-11-10 01:30:52 +0000535 }
536
537 /* adjust the sign of significand */
538 s = sign<0 ? -s : s;
539
drhad975d52016-04-27 15:24:13 +0000540 if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
541 result = (double)s;
542 }else{
drhc81c11f2009-11-10 01:30:52 +0000543 /* attempt to handle extremely small/large numbers better */
drhad975d52016-04-27 15:24:13 +0000544 if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
545 if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
drh02a43f62017-12-26 14:46:20 +0000546 LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
drhad975d52016-04-27 15:24:13 +0000547 if( esign<0 ){
548 result = s / scale;
549 result /= 1.0e+308;
550 }else{
551 result = s * scale;
552 result *= 1.0e+308;
553 }
554 }else{ assert( e>=342 );
555 if( esign<0 ){
556 result = 0.0*s;
557 }else{
drhb9772e72017-09-12 13:27:43 +0000558#ifdef INFINITY
drh3ba18ad2017-09-12 15:05:34 +0000559 result = INFINITY*s;
drhb9772e72017-09-12 13:27:43 +0000560#else
drhad975d52016-04-27 15:24:13 +0000561 result = 1e308*1e308*s; /* Infinity */
drhb9772e72017-09-12 13:27:43 +0000562#endif
drhad975d52016-04-27 15:24:13 +0000563 }
drh2458a2e2011-10-17 12:14:26 +0000564 }
drhc81c11f2009-11-10 01:30:52 +0000565 }else{
drh02a43f62017-12-26 14:46:20 +0000566 LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
drhc81c11f2009-11-10 01:30:52 +0000567 if( esign<0 ){
568 result = s / scale;
569 }else{
570 result = s * scale;
571 }
572 }
drhc81c11f2009-11-10 01:30:52 +0000573 }
574 }
575
576 /* store the result */
577 *pResult = result;
578
drh025586a2010-09-30 17:33:11 +0000579 /* return true if number and no extra non-whitespace chracters after */
drhad975d52016-04-27 15:24:13 +0000580 return z==zEnd && nDigits>0 && eValid && nonNum==0;
drhc81c11f2009-11-10 01:30:52 +0000581#else
shaneh5f1d6b62010-09-30 16:51:25 +0000582 return !sqlite3Atoi64(z, pResult, length, enc);
drhc81c11f2009-11-10 01:30:52 +0000583#endif /* SQLITE_OMIT_FLOATING_POINT */
584}
585
586/*
587** Compare the 19-character string zNum against the text representation
588** value 2^63: 9223372036854775808. Return negative, zero, or positive
589** if zNum is less than, equal to, or greater than the string.
shaneh5f1d6b62010-09-30 16:51:25 +0000590** Note that zNum must contain exactly 19 characters.
drhc81c11f2009-11-10 01:30:52 +0000591**
592** Unlike memcmp() this routine is guaranteed to return the difference
593** in the values of the last digit if the only difference is in the
594** last digit. So, for example,
595**
drh9339da12010-09-30 00:50:49 +0000596** compare2pow63("9223372036854775800", 1)
drhc81c11f2009-11-10 01:30:52 +0000597**
598** will return -8.
599*/
drh9339da12010-09-30 00:50:49 +0000600static int compare2pow63(const char *zNum, int incr){
601 int c = 0;
602 int i;
603 /* 012345678901234567 */
604 const char *pow63 = "922337203685477580";
605 for(i=0; c==0 && i<18; i++){
606 c = (zNum[i*incr]-pow63[i])*10;
607 }
drhc81c11f2009-11-10 01:30:52 +0000608 if( c==0 ){
drh9339da12010-09-30 00:50:49 +0000609 c = zNum[18*incr] - '8';
drh44dbca82010-01-13 04:22:20 +0000610 testcase( c==(-1) );
611 testcase( c==0 );
612 testcase( c==(+1) );
drhc81c11f2009-11-10 01:30:52 +0000613 }
614 return c;
615}
616
drhc81c11f2009-11-10 01:30:52 +0000617/*
drh9296c182014-07-23 13:40:49 +0000618** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
619** routine does *not* accept hexadecimal notation.
drh158b9cb2011-03-05 20:59:46 +0000620**
drh84d4f1a2017-09-20 10:47:10 +0000621** Returns:
drh158b9cb2011-03-05 20:59:46 +0000622**
drh84d4f1a2017-09-20 10:47:10 +0000623** 0 Successful transformation. Fits in a 64-bit signed integer.
drh4eb57ce2018-01-26 18:37:34 +0000624** 1 Excess non-space text after the integer value
drh84d4f1a2017-09-20 10:47:10 +0000625** 2 Integer too large for a 64-bit signed integer or is malformed
626** 3 Special case of 9223372036854775808
drhc81c11f2009-11-10 01:30:52 +0000627**
drh9339da12010-09-30 00:50:49 +0000628** length is the number of bytes in the string (bytes, not characters).
629** The string is not necessarily zero-terminated. The encoding is
630** given by enc.
drhc81c11f2009-11-10 01:30:52 +0000631*/
drh9339da12010-09-30 00:50:49 +0000632int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
drh0e5fba72013-03-20 12:04:29 +0000633 int incr;
drh158b9cb2011-03-05 20:59:46 +0000634 u64 u = 0;
shaneh5f1d6b62010-09-30 16:51:25 +0000635 int neg = 0; /* assume positive */
drh9339da12010-09-30 00:50:49 +0000636 int i;
637 int c = 0;
drh609d5842016-04-28 00:32:16 +0000638 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
drh84d4f1a2017-09-20 10:47:10 +0000639 int rc; /* Baseline return code */
drhc81c11f2009-11-10 01:30:52 +0000640 const char *zStart;
drh9339da12010-09-30 00:50:49 +0000641 const char *zEnd = zNum + length;
drh0e5fba72013-03-20 12:04:29 +0000642 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
643 if( enc==SQLITE_UTF8 ){
644 incr = 1;
645 }else{
646 incr = 2;
647 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
648 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
649 nonNum = i<length;
drh609d5842016-04-28 00:32:16 +0000650 zEnd = &zNum[i^1];
drh0e5fba72013-03-20 12:04:29 +0000651 zNum += (enc&1);
652 }
drh9339da12010-09-30 00:50:49 +0000653 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
drh158b9cb2011-03-05 20:59:46 +0000654 if( zNum<zEnd ){
655 if( *zNum=='-' ){
656 neg = 1;
657 zNum+=incr;
658 }else if( *zNum=='+' ){
659 zNum+=incr;
660 }
drhc81c11f2009-11-10 01:30:52 +0000661 }
662 zStart = zNum;
drh9339da12010-09-30 00:50:49 +0000663 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
664 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
drh158b9cb2011-03-05 20:59:46 +0000665 u = u*10 + c - '0';
drhc81c11f2009-11-10 01:30:52 +0000666 }
drh4eb57ce2018-01-26 18:37:34 +0000667 testcase( i==18*incr );
668 testcase( i==19*incr );
669 testcase( i==20*incr );
drh1822ebf2018-01-27 14:25:27 +0000670 if( u>LARGEST_INT64 ){
671 /* This test and assignment is needed only to suppress UB warnings
672 ** from clang and -fsanitize=undefined. This test and assignment make
673 ** the code a little larger and slower, and no harm comes from omitting
674 ** them, but we must appaise the undefined-behavior pharisees. */
675 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
676 }else if( neg ){
drh158b9cb2011-03-05 20:59:46 +0000677 *pNum = -(i64)u;
678 }else{
679 *pNum = (i64)u;
680 }
drh4eb57ce2018-01-26 18:37:34 +0000681 rc = 0;
682 if( (i==0 && zStart==zNum) /* No digits */
drh609d5842016-04-28 00:32:16 +0000683 || nonNum /* UTF16 with high-order bytes non-zero */
684 ){
drh84d4f1a2017-09-20 10:47:10 +0000685 rc = 1;
drh4eb57ce2018-01-26 18:37:34 +0000686 }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */
687 int jj = i;
688 do{
689 if( !sqlite3Isspace(zNum[jj]) ){
690 rc = 1; /* Extra non-space text after the integer */
691 break;
692 }
693 jj += incr;
694 }while( &zNum[jj]<zEnd );
drh84d4f1a2017-09-20 10:47:10 +0000695 }
drh4eb57ce2018-01-26 18:37:34 +0000696 if( i<19*incr ){
drhc81c11f2009-11-10 01:30:52 +0000697 /* Less than 19 digits, so we know that it fits in 64 bits */
drh158b9cb2011-03-05 20:59:46 +0000698 assert( u<=LARGEST_INT64 );
drh84d4f1a2017-09-20 10:47:10 +0000699 return rc;
drhc81c11f2009-11-10 01:30:52 +0000700 }else{
drh158b9cb2011-03-05 20:59:46 +0000701 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
drh4eb57ce2018-01-26 18:37:34 +0000702 c = i>19*incr ? 1 : compare2pow63(zNum, incr);
drh158b9cb2011-03-05 20:59:46 +0000703 if( c<0 ){
704 /* zNum is less than 9223372036854775808 so it fits */
705 assert( u<=LARGEST_INT64 );
drh84d4f1a2017-09-20 10:47:10 +0000706 return rc;
drh158b9cb2011-03-05 20:59:46 +0000707 }else{
drh4eb57ce2018-01-26 18:37:34 +0000708 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
709 if( c>0 ){
710 /* zNum is greater than 9223372036854775808 so it overflows */
711 return 2;
712 }else{
713 /* zNum is exactly 9223372036854775808. Fits if negative. The
714 ** special case 2 overflow if positive */
715 assert( u-1==LARGEST_INT64 );
716 return neg ? rc : 3;
717 }
drh158b9cb2011-03-05 20:59:46 +0000718 }
drhc81c11f2009-11-10 01:30:52 +0000719 }
720}
721
722/*
drh9296c182014-07-23 13:40:49 +0000723** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
724** into a 64-bit signed integer. This routine accepts hexadecimal literals,
725** whereas sqlite3Atoi64() does not.
726**
727** Returns:
728**
729** 0 Successful transformation. Fits in a 64-bit signed integer.
drh84d4f1a2017-09-20 10:47:10 +0000730** 1 Excess text after the integer value
731** 2 Integer too large for a 64-bit signed integer or is malformed
732** 3 Special case of 9223372036854775808
drh9296c182014-07-23 13:40:49 +0000733*/
734int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
735#ifndef SQLITE_OMIT_HEX_INTEGER
736 if( z[0]=='0'
737 && (z[1]=='x' || z[1]=='X')
drh9296c182014-07-23 13:40:49 +0000738 ){
739 u64 u = 0;
740 int i, k;
741 for(i=2; z[i]=='0'; i++){}
742 for(k=i; sqlite3Isxdigit(z[k]); k++){
743 u = u*16 + sqlite3HexToInt(z[k]);
744 }
745 memcpy(pOut, &u, 8);
drh84d4f1a2017-09-20 10:47:10 +0000746 return (z[k]==0 && k-i<=16) ? 0 : 2;
drh9296c182014-07-23 13:40:49 +0000747 }else
748#endif /* SQLITE_OMIT_HEX_INTEGER */
749 {
750 return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
751 }
752}
753
754/*
drhc81c11f2009-11-10 01:30:52 +0000755** If zNum represents an integer that will fit in 32-bits, then set
756** *pValue to that integer and return true. Otherwise return false.
757**
drh9296c182014-07-23 13:40:49 +0000758** This routine accepts both decimal and hexadecimal notation for integers.
759**
drhc81c11f2009-11-10 01:30:52 +0000760** Any non-numeric characters that following zNum are ignored.
761** This is different from sqlite3Atoi64() which requires the
762** input number to be zero-terminated.
763*/
764int sqlite3GetInt32(const char *zNum, int *pValue){
765 sqlite_int64 v = 0;
766 int i, c;
767 int neg = 0;
768 if( zNum[0]=='-' ){
769 neg = 1;
770 zNum++;
771 }else if( zNum[0]=='+' ){
772 zNum++;
773 }
drh28e048c2014-07-23 01:26:51 +0000774#ifndef SQLITE_OMIT_HEX_INTEGER
775 else if( zNum[0]=='0'
776 && (zNum[1]=='x' || zNum[1]=='X')
777 && sqlite3Isxdigit(zNum[2])
778 ){
779 u32 u = 0;
780 zNum += 2;
781 while( zNum[0]=='0' ) zNum++;
782 for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
783 u = u*16 + sqlite3HexToInt(zNum[i]);
784 }
785 if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
786 memcpy(pValue, &u, 4);
787 return 1;
788 }else{
789 return 0;
790 }
791 }
792#endif
drh313e6fd2017-05-03 17:44:28 +0000793 if( !sqlite3Isdigit(zNum[0]) ) return 0;
drh935f2e72015-04-18 04:45:00 +0000794 while( zNum[0]=='0' ) zNum++;
drhc81c11f2009-11-10 01:30:52 +0000795 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
796 v = v*10 + c;
797 }
798
799 /* The longest decimal representation of a 32 bit integer is 10 digits:
800 **
801 ** 1234567890
802 ** 2^31 -> 2147483648
803 */
drh44dbca82010-01-13 04:22:20 +0000804 testcase( i==10 );
drhc81c11f2009-11-10 01:30:52 +0000805 if( i>10 ){
806 return 0;
807 }
drh44dbca82010-01-13 04:22:20 +0000808 testcase( v-neg==2147483647 );
drhc81c11f2009-11-10 01:30:52 +0000809 if( v-neg>2147483647 ){
810 return 0;
811 }
812 if( neg ){
813 v = -v;
814 }
815 *pValue = (int)v;
816 return 1;
817}
818
819/*
drh60ac3f42010-11-23 18:59:27 +0000820** Return a 32-bit integer value extracted from a string. If the
821** string is not an integer, just return 0.
822*/
823int sqlite3Atoi(const char *z){
824 int x = 0;
825 if( z ) sqlite3GetInt32(z, &x);
826 return x;
827}
828
829/*
drhc81c11f2009-11-10 01:30:52 +0000830** The variable-length integer encoding is as follows:
831**
832** KEY:
833** A = 0xxxxxxx 7 bits of data and one flag bit
834** B = 1xxxxxxx 7 bits of data and one flag bit
835** C = xxxxxxxx 8 bits of data
836**
837** 7 bits - A
838** 14 bits - BA
839** 21 bits - BBA
840** 28 bits - BBBA
841** 35 bits - BBBBA
842** 42 bits - BBBBBA
843** 49 bits - BBBBBBA
844** 56 bits - BBBBBBBA
845** 64 bits - BBBBBBBBC
846*/
847
848/*
849** Write a 64-bit variable-length integer to memory starting at p[0].
850** The length of data write will be between 1 and 9 bytes. The number
851** of bytes written is returned.
852**
853** A variable-length integer consists of the lower 7 bits of each byte
854** for all bytes that have the 8th bit set and one byte with the 8th
855** bit clear. Except, if we get to the 9th byte, it stores the full
856** 8 bits and is the last byte.
857*/
drh2f2b2b82014-08-22 18:48:25 +0000858static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
drhc81c11f2009-11-10 01:30:52 +0000859 int i, j, n;
860 u8 buf[10];
861 if( v & (((u64)0xff000000)<<32) ){
862 p[8] = (u8)v;
863 v >>= 8;
864 for(i=7; i>=0; i--){
865 p[i] = (u8)((v & 0x7f) | 0x80);
866 v >>= 7;
867 }
868 return 9;
869 }
870 n = 0;
871 do{
872 buf[n++] = (u8)((v & 0x7f) | 0x80);
873 v >>= 7;
874 }while( v!=0 );
875 buf[0] &= 0x7f;
876 assert( n<=9 );
877 for(i=0, j=n-1; j>=0; j--, i++){
878 p[i] = buf[j];
879 }
880 return n;
881}
drh2f2b2b82014-08-22 18:48:25 +0000882int sqlite3PutVarint(unsigned char *p, u64 v){
883 if( v<=0x7f ){
884 p[0] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000885 return 1;
886 }
drh2f2b2b82014-08-22 18:48:25 +0000887 if( v<=0x3fff ){
888 p[0] = ((v>>7)&0x7f)|0x80;
889 p[1] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000890 return 2;
891 }
drh2f2b2b82014-08-22 18:48:25 +0000892 return putVarint64(p,v);
drhc81c11f2009-11-10 01:30:52 +0000893}
894
895/*
drh0b2864c2010-03-03 15:18:38 +0000896** Bitmasks used by sqlite3GetVarint(). These precomputed constants
897** are defined here rather than simply putting the constant expressions
898** inline in order to work around bugs in the RVT compiler.
899**
900** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
901**
902** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
903*/
904#define SLOT_2_0 0x001fc07f
905#define SLOT_4_2_0 0xf01fc07f
906
907
908/*
drhc81c11f2009-11-10 01:30:52 +0000909** Read a 64-bit variable-length integer from memory starting at p[0].
910** Return the number of bytes read. The value is stored in *v.
911*/
912u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
913 u32 a,b,s;
914
915 a = *p;
916 /* a: p0 (unmasked) */
917 if (!(a&0x80))
918 {
919 *v = a;
920 return 1;
921 }
922
923 p++;
924 b = *p;
925 /* b: p1 (unmasked) */
926 if (!(b&0x80))
927 {
928 a &= 0x7f;
929 a = a<<7;
930 a |= b;
931 *v = a;
932 return 2;
933 }
934
drh0b2864c2010-03-03 15:18:38 +0000935 /* Verify that constants are precomputed correctly */
936 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
shaneh1da207e2010-03-09 14:41:12 +0000937 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
drh0b2864c2010-03-03 15:18:38 +0000938
drhc81c11f2009-11-10 01:30:52 +0000939 p++;
940 a = a<<14;
941 a |= *p;
942 /* a: p0<<14 | p2 (unmasked) */
943 if (!(a&0x80))
944 {
drh0b2864c2010-03-03 15:18:38 +0000945 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000946 b &= 0x7f;
947 b = b<<7;
948 a |= b;
949 *v = a;
950 return 3;
951 }
952
953 /* CSE1 from below */
drh0b2864c2010-03-03 15:18:38 +0000954 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000955 p++;
956 b = b<<14;
957 b |= *p;
958 /* b: p1<<14 | p3 (unmasked) */
959 if (!(b&0x80))
960 {
drh0b2864c2010-03-03 15:18:38 +0000961 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000962 /* moved CSE1 up */
963 /* a &= (0x7f<<14)|(0x7f); */
964 a = a<<7;
965 a |= b;
966 *v = a;
967 return 4;
968 }
969
970 /* a: p0<<14 | p2 (masked) */
971 /* b: p1<<14 | p3 (unmasked) */
972 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
973 /* moved CSE1 up */
974 /* a &= (0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +0000975 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000976 s = a;
977 /* s: p0<<14 | p2 (masked) */
978
979 p++;
980 a = a<<14;
981 a |= *p;
982 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
983 if (!(a&0x80))
984 {
drh62aaa6c2015-11-21 17:27:42 +0000985 /* we can skip these cause they were (effectively) done above
986 ** while calculating s */
drhc81c11f2009-11-10 01:30:52 +0000987 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
988 /* b &= (0x7f<<14)|(0x7f); */
989 b = b<<7;
990 a |= b;
991 s = s>>18;
992 *v = ((u64)s)<<32 | a;
993 return 5;
994 }
995
996 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
997 s = s<<7;
998 s |= b;
999 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
1000
1001 p++;
1002 b = b<<14;
1003 b |= *p;
1004 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
1005 if (!(b&0x80))
1006 {
1007 /* we can skip this cause it was (effectively) done above in calc'ing s */
1008 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +00001009 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +00001010 a = a<<7;
1011 a |= b;
1012 s = s>>18;
1013 *v = ((u64)s)<<32 | a;
1014 return 6;
1015 }
1016
1017 p++;
1018 a = a<<14;
1019 a |= *p;
1020 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
1021 if (!(a&0x80))
1022 {
drh0b2864c2010-03-03 15:18:38 +00001023 a &= SLOT_4_2_0;
1024 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +00001025 b = b<<7;
1026 a |= b;
1027 s = s>>11;
1028 *v = ((u64)s)<<32 | a;
1029 return 7;
1030 }
1031
1032 /* CSE2 from below */
drh0b2864c2010-03-03 15:18:38 +00001033 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +00001034 p++;
1035 b = b<<14;
1036 b |= *p;
1037 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
1038 if (!(b&0x80))
1039 {
drh0b2864c2010-03-03 15:18:38 +00001040 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +00001041 /* moved CSE2 up */
1042 /* a &= (0x7f<<14)|(0x7f); */
1043 a = a<<7;
1044 a |= b;
1045 s = s>>4;
1046 *v = ((u64)s)<<32 | a;
1047 return 8;
1048 }
1049
1050 p++;
1051 a = a<<15;
1052 a |= *p;
1053 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
1054
1055 /* moved CSE2 up */
1056 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
drh0b2864c2010-03-03 15:18:38 +00001057 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +00001058 b = b<<8;
1059 a |= b;
1060
1061 s = s<<4;
1062 b = p[-4];
1063 b &= 0x7f;
1064 b = b>>3;
1065 s |= b;
1066
1067 *v = ((u64)s)<<32 | a;
1068
1069 return 9;
1070}
1071
1072/*
1073** Read a 32-bit variable-length integer from memory starting at p[0].
1074** Return the number of bytes read. The value is stored in *v.
1075**
1076** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
1077** integer, then set *v to 0xffffffff.
1078**
1079** A MACRO version, getVarint32, is provided which inlines the
1080** single-byte case. All code should use the MACRO version as
1081** this function assumes the single-byte case has already been handled.
1082*/
1083u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
1084 u32 a,b;
1085
1086 /* The 1-byte case. Overwhelmingly the most common. Handled inline
1087 ** by the getVarin32() macro */
1088 a = *p;
1089 /* a: p0 (unmasked) */
1090#ifndef getVarint32
1091 if (!(a&0x80))
1092 {
1093 /* Values between 0 and 127 */
1094 *v = a;
1095 return 1;
1096 }
1097#endif
1098
1099 /* The 2-byte case */
1100 p++;
1101 b = *p;
1102 /* b: p1 (unmasked) */
1103 if (!(b&0x80))
1104 {
1105 /* Values between 128 and 16383 */
1106 a &= 0x7f;
1107 a = a<<7;
1108 *v = a | b;
1109 return 2;
1110 }
1111
1112 /* The 3-byte case */
1113 p++;
1114 a = a<<14;
1115 a |= *p;
1116 /* a: p0<<14 | p2 (unmasked) */
1117 if (!(a&0x80))
1118 {
1119 /* Values between 16384 and 2097151 */
1120 a &= (0x7f<<14)|(0x7f);
1121 b &= 0x7f;
1122 b = b<<7;
1123 *v = a | b;
1124 return 3;
1125 }
1126
1127 /* A 32-bit varint is used to store size information in btrees.
1128 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
1129 ** A 3-byte varint is sufficient, for example, to record the size
1130 ** of a 1048569-byte BLOB or string.
1131 **
1132 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
1133 ** rare larger cases can be handled by the slower 64-bit varint
1134 ** routine.
1135 */
1136#if 1
1137 {
1138 u64 v64;
1139 u8 n;
1140
1141 p -= 2;
1142 n = sqlite3GetVarint(p, &v64);
1143 assert( n>3 && n<=9 );
1144 if( (v64 & SQLITE_MAX_U32)!=v64 ){
1145 *v = 0xffffffff;
1146 }else{
1147 *v = (u32)v64;
1148 }
1149 return n;
1150 }
1151
1152#else
1153 /* For following code (kept for historical record only) shows an
1154 ** unrolling for the 3- and 4-byte varint cases. This code is
1155 ** slightly faster, but it is also larger and much harder to test.
1156 */
1157 p++;
1158 b = b<<14;
1159 b |= *p;
1160 /* b: p1<<14 | p3 (unmasked) */
1161 if (!(b&0x80))
1162 {
1163 /* Values between 2097152 and 268435455 */
1164 b &= (0x7f<<14)|(0x7f);
1165 a &= (0x7f<<14)|(0x7f);
1166 a = a<<7;
1167 *v = a | b;
1168 return 4;
1169 }
1170
1171 p++;
1172 a = a<<14;
1173 a |= *p;
1174 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1175 if (!(a&0x80))
1176 {
dan3bbe7612010-03-03 16:02:05 +00001177 /* Values between 268435456 and 34359738367 */
1178 a &= SLOT_4_2_0;
1179 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +00001180 b = b<<7;
1181 *v = a | b;
1182 return 5;
1183 }
1184
1185 /* We can only reach this point when reading a corrupt database
1186 ** file. In that case we are not in any hurry. Use the (relatively
1187 ** slow) general-purpose sqlite3GetVarint() routine to extract the
1188 ** value. */
1189 {
1190 u64 v64;
1191 u8 n;
1192
1193 p -= 4;
1194 n = sqlite3GetVarint(p, &v64);
1195 assert( n>5 && n<=9 );
1196 *v = (u32)v64;
1197 return n;
1198 }
1199#endif
1200}
1201
1202/*
1203** Return the number of bytes that will be needed to store the given
1204** 64-bit integer.
1205*/
1206int sqlite3VarintLen(u64 v){
drh59a53642015-09-01 22:29:07 +00001207 int i;
drh6f17c092016-03-04 21:18:09 +00001208 for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
drhc81c11f2009-11-10 01:30:52 +00001209 return i;
1210}
1211
1212
1213/*
1214** Read or write a four-byte big-endian integer value.
1215*/
1216u32 sqlite3Get4byte(const u8 *p){
drh5372e4d2015-06-30 12:47:09 +00001217#if SQLITE_BYTEORDER==4321
1218 u32 x;
1219 memcpy(&x,p,4);
1220 return x;
drhdc5ece82017-02-15 15:09:09 +00001221#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:09 +00001222 u32 x;
1223 memcpy(&x,p,4);
1224 return __builtin_bswap32(x);
drha39284b2017-02-09 17:12:22 +00001225#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
mistachkin647ca462015-06-30 17:28:40 +00001226 u32 x;
1227 memcpy(&x,p,4);
1228 return _byteswap_ulong(x);
drh5372e4d2015-06-30 12:47:09 +00001229#else
drh693e6712014-01-24 22:58:00 +00001230 testcase( p[0]&0x80 );
1231 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
drh5372e4d2015-06-30 12:47:09 +00001232#endif
drhc81c11f2009-11-10 01:30:52 +00001233}
1234void sqlite3Put4byte(unsigned char *p, u32 v){
drh5372e4d2015-06-30 12:47:09 +00001235#if SQLITE_BYTEORDER==4321
1236 memcpy(p,&v,4);
drhdc5ece82017-02-15 15:09:09 +00001237#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:09 +00001238 u32 x = __builtin_bswap32(v);
1239 memcpy(p,&x,4);
drha39284b2017-02-09 17:12:22 +00001240#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
mistachkin647ca462015-06-30 17:28:40 +00001241 u32 x = _byteswap_ulong(v);
1242 memcpy(p,&x,4);
drh5372e4d2015-06-30 12:47:09 +00001243#else
drhc81c11f2009-11-10 01:30:52 +00001244 p[0] = (u8)(v>>24);
1245 p[1] = (u8)(v>>16);
1246 p[2] = (u8)(v>>8);
1247 p[3] = (u8)v;
drh5372e4d2015-06-30 12:47:09 +00001248#endif
drhc81c11f2009-11-10 01:30:52 +00001249}
1250
drh9296c182014-07-23 13:40:49 +00001251
1252
1253/*
1254** Translate a single byte of Hex into an integer.
1255** This routine only works if h really is a valid hexadecimal
1256** character: 0..9a..fA..F
1257*/
1258u8 sqlite3HexToInt(int h){
1259 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
1260#ifdef SQLITE_ASCII
1261 h += 9*(1&(h>>6));
1262#endif
1263#ifdef SQLITE_EBCDIC
1264 h += 9*(1&~(h>>4));
1265#endif
1266 return (u8)(h & 0xf);
1267}
1268
drhc81c11f2009-11-10 01:30:52 +00001269#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
1270/*
1271** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
1272** value. Return a pointer to its binary value. Space to hold the
1273** binary value has been obtained from malloc and must be freed by
1274** the calling routine.
1275*/
1276void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
1277 char *zBlob;
1278 int i;
1279
drh575fad62016-02-05 13:38:36 +00001280 zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
drhc81c11f2009-11-10 01:30:52 +00001281 n--;
1282 if( zBlob ){
1283 for(i=0; i<n; i+=2){
dancd74b612011-04-22 19:37:32 +00001284 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
drhc81c11f2009-11-10 01:30:52 +00001285 }
1286 zBlob[i/2] = 0;
1287 }
1288 return zBlob;
1289}
1290#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
1291
drh413c3d32010-02-23 20:11:56 +00001292/*
1293** Log an error that is an API call on a connection pointer that should
1294** not have been used. The "type" of connection pointer is given as the
1295** argument. The zType is a word like "NULL" or "closed" or "invalid".
1296*/
1297static void logBadConnection(const char *zType){
1298 sqlite3_log(SQLITE_MISUSE,
1299 "API call with %s database connection pointer",
1300 zType
1301 );
1302}
drhc81c11f2009-11-10 01:30:52 +00001303
1304/*
drhc81c11f2009-11-10 01:30:52 +00001305** Check to make sure we have a valid db pointer. This test is not
1306** foolproof but it does provide some measure of protection against
1307** misuse of the interface such as passing in db pointers that are
1308** NULL or which have been previously closed. If this routine returns
1309** 1 it means that the db pointer is valid and 0 if it should not be
1310** dereferenced for any reason. The calling function should invoke
1311** SQLITE_MISUSE immediately.
1312**
1313** sqlite3SafetyCheckOk() requires that the db pointer be valid for
1314** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
1315** open properly and is not fit for general use but which can be
1316** used as an argument to sqlite3_errmsg() or sqlite3_close().
1317*/
1318int sqlite3SafetyCheckOk(sqlite3 *db){
1319 u32 magic;
drh413c3d32010-02-23 20:11:56 +00001320 if( db==0 ){
1321 logBadConnection("NULL");
1322 return 0;
1323 }
drhc81c11f2009-11-10 01:30:52 +00001324 magic = db->magic;
drh9978c972010-02-23 17:36:32 +00001325 if( magic!=SQLITE_MAGIC_OPEN ){
drhe294da02010-02-25 23:44:15 +00001326 if( sqlite3SafetyCheckSickOrOk(db) ){
1327 testcase( sqlite3GlobalConfig.xLog!=0 );
drh413c3d32010-02-23 20:11:56 +00001328 logBadConnection("unopened");
1329 }
drhc81c11f2009-11-10 01:30:52 +00001330 return 0;
1331 }else{
1332 return 1;
1333 }
1334}
1335int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
1336 u32 magic;
1337 magic = db->magic;
1338 if( magic!=SQLITE_MAGIC_SICK &&
1339 magic!=SQLITE_MAGIC_OPEN &&
drh413c3d32010-02-23 20:11:56 +00001340 magic!=SQLITE_MAGIC_BUSY ){
drhe294da02010-02-25 23:44:15 +00001341 testcase( sqlite3GlobalConfig.xLog!=0 );
drhaf46dc12010-02-24 21:44:07 +00001342 logBadConnection("invalid");
drh413c3d32010-02-23 20:11:56 +00001343 return 0;
1344 }else{
1345 return 1;
1346 }
drhc81c11f2009-11-10 01:30:52 +00001347}
drh158b9cb2011-03-05 20:59:46 +00001348
1349/*
1350** Attempt to add, substract, or multiply the 64-bit signed value iB against
1351** the other 64-bit signed integer at *pA and store the result in *pA.
1352** Return 0 on success. Or if the operation would have resulted in an
1353** overflow, leave *pA unchanged and return 1.
1354*/
1355int sqlite3AddInt64(i64 *pA, i64 iB){
drhb9772e72017-09-12 13:27:43 +00001356#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
drh4a477612017-01-03 17:33:43 +00001357 return __builtin_add_overflow(*pA, iB, pA);
1358#else
drh158b9cb2011-03-05 20:59:46 +00001359 i64 iA = *pA;
1360 testcase( iA==0 ); testcase( iA==1 );
1361 testcase( iB==-1 ); testcase( iB==0 );
1362 if( iB>=0 ){
1363 testcase( iA>0 && LARGEST_INT64 - iA == iB );
1364 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
1365 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001366 }else{
1367 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
1368 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
1369 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001370 }
drh53a6eb32014-02-10 12:59:15 +00001371 *pA += iB;
drh158b9cb2011-03-05 20:59:46 +00001372 return 0;
drh4a477612017-01-03 17:33:43 +00001373#endif
drh158b9cb2011-03-05 20:59:46 +00001374}
1375int sqlite3SubInt64(i64 *pA, i64 iB){
drhb9772e72017-09-12 13:27:43 +00001376#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
drh4a477612017-01-03 17:33:43 +00001377 return __builtin_sub_overflow(*pA, iB, pA);
1378#else
drh158b9cb2011-03-05 20:59:46 +00001379 testcase( iB==SMALLEST_INT64+1 );
1380 if( iB==SMALLEST_INT64 ){
1381 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
1382 if( (*pA)>=0 ) return 1;
1383 *pA -= iB;
1384 return 0;
1385 }else{
1386 return sqlite3AddInt64(pA, -iB);
1387 }
drh4a477612017-01-03 17:33:43 +00001388#endif
drh158b9cb2011-03-05 20:59:46 +00001389}
drh158b9cb2011-03-05 20:59:46 +00001390int sqlite3MulInt64(i64 *pA, i64 iB){
drhb9772e72017-09-12 13:27:43 +00001391#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
drh4a477612017-01-03 17:33:43 +00001392 return __builtin_mul_overflow(*pA, iB, pA);
1393#else
drh158b9cb2011-03-05 20:59:46 +00001394 i64 iA = *pA;
drh09952c62016-09-20 22:04:05 +00001395 if( iB>0 ){
1396 if( iA>LARGEST_INT64/iB ) return 1;
1397 if( iA<SMALLEST_INT64/iB ) return 1;
1398 }else if( iB<0 ){
1399 if( iA>0 ){
1400 if( iB<SMALLEST_INT64/iA ) return 1;
1401 }else if( iA<0 ){
1402 if( iB==SMALLEST_INT64 ) return 1;
1403 if( iA==SMALLEST_INT64 ) return 1;
1404 if( -iA>LARGEST_INT64/-iB ) return 1;
drh53a6eb32014-02-10 12:59:15 +00001405 }
drh53a6eb32014-02-10 12:59:15 +00001406 }
drh09952c62016-09-20 22:04:05 +00001407 *pA = iA*iB;
drh158b9cb2011-03-05 20:59:46 +00001408 return 0;
drh4a477612017-01-03 17:33:43 +00001409#endif
drh158b9cb2011-03-05 20:59:46 +00001410}
drhd50ffc42011-03-08 02:38:28 +00001411
1412/*
1413** Compute the absolute value of a 32-bit signed integer, of possible. Or
1414** if the integer has a value of -2147483648, return +2147483647
1415*/
1416int sqlite3AbsInt32(int x){
1417 if( x>=0 ) return x;
drh87e79ae2011-03-08 13:06:41 +00001418 if( x==(int)0x80000000 ) return 0x7fffffff;
drhd50ffc42011-03-08 02:38:28 +00001419 return -x;
1420}
drh81cc5162011-05-17 20:36:21 +00001421
1422#ifdef SQLITE_ENABLE_8_3_NAMES
1423/*
drhb51bf432011-07-21 21:29:35 +00001424** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
drh81cc5162011-05-17 20:36:21 +00001425** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
1426** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
1427** three characters, then shorten the suffix on z[] to be the last three
1428** characters of the original suffix.
1429**
drhb51bf432011-07-21 21:29:35 +00001430** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
1431** do the suffix shortening regardless of URI parameter.
1432**
drh81cc5162011-05-17 20:36:21 +00001433** Examples:
1434**
1435** test.db-journal => test.nal
1436** test.db-wal => test.wal
1437** test.db-shm => test.shm
drhf5808602011-12-16 00:33:04 +00001438** test.db-mj7f3319fa => test.9fa
drh81cc5162011-05-17 20:36:21 +00001439*/
1440void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
drhb51bf432011-07-21 21:29:35 +00001441#if SQLITE_ENABLE_8_3_NAMES<2
drh7d39e172012-01-02 12:41:53 +00001442 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
drhb51bf432011-07-21 21:29:35 +00001443#endif
1444 {
drh81cc5162011-05-17 20:36:21 +00001445 int i, sz;
1446 sz = sqlite3Strlen30(z);
drhc83f2d42011-05-18 02:41:10 +00001447 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
drhc02a43a2012-01-10 23:18:38 +00001448 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
drh81cc5162011-05-17 20:36:21 +00001449 }
1450}
1451#endif
drhbf539c42013-10-05 18:16:02 +00001452
1453/*
1454** Find (an approximate) sum of two LogEst values. This computation is
1455** not a simple "+" operator because LogEst is stored as a logarithmic
1456** value.
1457**
1458*/
1459LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
1460 static const unsigned char x[] = {
1461 10, 10, /* 0,1 */
1462 9, 9, /* 2,3 */
1463 8, 8, /* 4,5 */
1464 7, 7, 7, /* 6,7,8 */
1465 6, 6, 6, /* 9,10,11 */
1466 5, 5, 5, /* 12-14 */
1467 4, 4, 4, 4, /* 15-18 */
1468 3, 3, 3, 3, 3, 3, /* 19-24 */
1469 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
1470 };
1471 if( a>=b ){
1472 if( a>b+49 ) return a;
1473 if( a>b+31 ) return a+1;
1474 return a+x[a-b];
1475 }else{
1476 if( b>a+49 ) return b;
1477 if( b>a+31 ) return b+1;
1478 return b+x[b-a];
1479 }
1480}
1481
1482/*
drh224155d2014-04-30 13:19:09 +00001483** Convert an integer into a LogEst. In other words, compute an
1484** approximation for 10*log2(x).
drhbf539c42013-10-05 18:16:02 +00001485*/
1486LogEst sqlite3LogEst(u64 x){
1487 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1488 LogEst y = 40;
1489 if( x<8 ){
1490 if( x<2 ) return 0;
1491 while( x<8 ){ y -= 10; x <<= 1; }
1492 }else{
drhceb4b1d2017-08-17 20:53:07 +00001493#if GCC_VERSION>=5004000
1494 int i = 60 - __builtin_clzll(x);
1495 y += i*10;
1496 x >>= i;
1497#else
drh75ab50c2016-04-28 14:15:12 +00001498 while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
drhbf539c42013-10-05 18:16:02 +00001499 while( x>15 ){ y += 10; x >>= 1; }
drhceb4b1d2017-08-17 20:53:07 +00001500#endif
drhbf539c42013-10-05 18:16:02 +00001501 }
1502 return a[x&7] + y - 10;
1503}
1504
1505#ifndef SQLITE_OMIT_VIRTUALTABLE
1506/*
1507** Convert a double into a LogEst
1508** In other words, compute an approximation for 10*log2(x).
1509*/
1510LogEst sqlite3LogEstFromDouble(double x){
1511 u64 a;
1512 LogEst e;
1513 assert( sizeof(x)==8 && sizeof(a)==8 );
1514 if( x<=1 ) return 0;
1515 if( x<=2000000000 ) return sqlite3LogEst((u64)x);
1516 memcpy(&a, &x, 8);
1517 e = (a>>52) - 1022;
1518 return e*10;
1519}
1520#endif /* SQLITE_OMIT_VIRTUALTABLE */
1521
drh14bfd992016-03-05 14:00:09 +00001522#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
drhd566c952016-02-25 21:19:03 +00001523 defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
1524 defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
drhbf539c42013-10-05 18:16:02 +00001525/*
1526** Convert a LogEst into an integer.
drhd566c952016-02-25 21:19:03 +00001527**
1528** Note that this routine is only used when one or more of various
1529** non-standard compile-time options is enabled.
drhbf539c42013-10-05 18:16:02 +00001530*/
1531u64 sqlite3LogEstToInt(LogEst x){
1532 u64 n;
drhbf539c42013-10-05 18:16:02 +00001533 n = x%10;
1534 x /= 10;
1535 if( n>=5 ) n -= 2;
1536 else if( n>=1 ) n -= 1;
drhecdf20d2016-03-10 14:28:24 +00001537#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
1538 defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
1539 if( x>60 ) return (u64)LARGEST_INT64;
1540#else
1541 /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
1542 ** possible to this routine is 310, resulting in a maximum x of 31 */
1543 assert( x<=60 );
1544#endif
1545 return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
drhbf539c42013-10-05 18:16:02 +00001546}
drhd566c952016-02-25 21:19:03 +00001547#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
drh9bf755c2016-12-23 03:59:31 +00001548
1549/*
1550** Add a new name/number pair to a VList. This might require that the
1551** VList object be reallocated, so return the new VList. If an OOM
drhce1bbe52016-12-23 13:52:45 +00001552** error occurs, the original VList returned and the
drh9bf755c2016-12-23 03:59:31 +00001553** db->mallocFailed flag is set.
1554**
1555** A VList is really just an array of integers. To destroy a VList,
1556** simply pass it to sqlite3DbFree().
1557**
1558** The first integer is the number of integers allocated for the whole
1559** VList. The second integer is the number of integers actually used.
1560** Each name/number pair is encoded by subsequent groups of 3 or more
1561** integers.
1562**
drhce1bbe52016-12-23 13:52:45 +00001563** Each name/number pair starts with two integers which are the numeric
drh9bf755c2016-12-23 03:59:31 +00001564** value for the pair and the size of the name/number pair, respectively.
1565** The text name overlays one or more following integers. The text name
1566** is always zero-terminated.
drhce1bbe52016-12-23 13:52:45 +00001567**
1568** Conceptually:
1569**
1570** struct VList {
1571** int nAlloc; // Number of allocated slots
1572** int nUsed; // Number of used slots
1573** struct VListEntry {
1574** int iValue; // Value for this entry
1575** int nSlot; // Slots used by this entry
1576** // ... variable name goes here
1577** } a[0];
1578** }
1579**
1580** During code generation, pointers to the variable names within the
1581** VList are taken. When that happens, nAlloc is set to zero as an
1582** indication that the VList may never again be enlarged, since the
1583** accompanying realloc() would invalidate the pointers.
drh9bf755c2016-12-23 03:59:31 +00001584*/
1585VList *sqlite3VListAdd(
1586 sqlite3 *db, /* The database connection used for malloc() */
1587 VList *pIn, /* The input VList. Might be NULL */
1588 const char *zName, /* Name of symbol to add */
1589 int nName, /* Bytes of text in zName */
1590 int iVal /* Value to associate with zName */
1591){
1592 int nInt; /* number of sizeof(int) objects needed for zName */
drhce1bbe52016-12-23 13:52:45 +00001593 char *z; /* Pointer to where zName will be stored */
1594 int i; /* Index in pIn[] where zName is stored */
drh9bf755c2016-12-23 03:59:31 +00001595
1596 nInt = nName/4 + 3;
drhce1bbe52016-12-23 13:52:45 +00001597 assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
drh9bf755c2016-12-23 03:59:31 +00001598 if( pIn==0 || pIn[1]+nInt > pIn[0] ){
1599 /* Enlarge the allocation */
1600 int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
1601 VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
drhce1bbe52016-12-23 13:52:45 +00001602 if( pOut==0 ) return pIn;
drh9bf755c2016-12-23 03:59:31 +00001603 if( pIn==0 ) pOut[1] = 2;
1604 pIn = pOut;
1605 pIn[0] = nAlloc;
1606 }
1607 i = pIn[1];
1608 pIn[i] = iVal;
1609 pIn[i+1] = nInt;
1610 z = (char*)&pIn[i+2];
1611 pIn[1] = i+nInt;
1612 assert( pIn[1]<=pIn[0] );
1613 memcpy(z, zName, nName);
1614 z[nName] = 0;
1615 return pIn;
1616}
1617
1618/*
1619** Return a pointer to the name of a variable in the given VList that
1620** has the value iVal. Or return a NULL if there is no such variable in
1621** the list
1622*/
1623const char *sqlite3VListNumToName(VList *pIn, int iVal){
1624 int i, mx;
1625 if( pIn==0 ) return 0;
1626 mx = pIn[1];
1627 i = 2;
1628 do{
1629 if( pIn[i]==iVal ) return (char*)&pIn[i+2];
1630 i += pIn[i+1];
1631 }while( i<mx );
1632 return 0;
1633}
1634
1635/*
1636** Return the number of the variable named zName, if it is in VList.
1637** or return 0 if there is no such variable.
1638*/
1639int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
1640 int i, mx;
1641 if( pIn==0 ) return 0;
1642 mx = pIn[1];
1643 i = 2;
1644 do{
1645 const char *z = (const char*)&pIn[i+2];
1646 if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
1647 i += pIn[i+1];
1648 }while( i<mx );
1649 return 0;
1650}