blob: 6aead47faa3d808d02725ae5aa1bfbecbbc1173e [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/*
35** Give a callback to the test harness that can be used to simulate faults
36** in places where it is difficult or expensive to do so purely by means
37** of inputs.
38**
39** The intent of the integer argument is to let the fault simulator know
40** which of multiple sqlite3FaultSim() calls has been hit.
41**
42** Return whatever integer value the test callback returns, or return
43** SQLITE_OK if no test callback is installed.
44*/
45#ifndef SQLITE_OMIT_BUILTIN_TEST
46int sqlite3FaultSim(int iTest){
47 int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
48 return xCallback ? xCallback(iTest) : SQLITE_OK;
49}
50#endif
51
drh85c8f292010-01-13 17:39:53 +000052#ifndef SQLITE_OMIT_FLOATING_POINT
drhc81c11f2009-11-10 01:30:52 +000053/*
54** Return true if the floating point value is Not a Number (NaN).
55**
56** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
57** Otherwise, we have our own implementation that works on most systems.
58*/
59int sqlite3IsNaN(double x){
60 int rc; /* The value return */
drh0ede9eb2015-01-10 16:49:23 +000061#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
drhc81c11f2009-11-10 01:30:52 +000062 /*
63 ** Systems that support the isnan() library function should probably
64 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
65 ** found that many systems do not have a working isnan() function so
66 ** this implementation is provided as an alternative.
67 **
68 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
69 ** On the other hand, the use of -ffast-math comes with the following
70 ** warning:
71 **
72 ** This option [-ffast-math] should never be turned on by any
73 ** -O option since it can result in incorrect output for programs
74 ** which depend on an exact implementation of IEEE or ISO
75 ** rules/specifications for math functions.
76 **
77 ** Under MSVC, this NaN test may fail if compiled with a floating-
78 ** point precision mode other than /fp:precise. From the MSDN
79 ** documentation:
80 **
81 ** The compiler [with /fp:precise] will properly handle comparisons
82 ** involving NaN. For example, x != x evaluates to true if x is NaN
83 ** ...
84 */
85#ifdef __FAST_MATH__
86# error SQLite will not work correctly with the -ffast-math option of GCC.
87#endif
88 volatile double y = x;
89 volatile double z = y;
90 rc = (y!=z);
drh0ede9eb2015-01-10 16:49:23 +000091#else /* if HAVE_ISNAN */
drhc81c11f2009-11-10 01:30:52 +000092 rc = isnan(x);
drh0ede9eb2015-01-10 16:49:23 +000093#endif /* HAVE_ISNAN */
drhc81c11f2009-11-10 01:30:52 +000094 testcase( rc );
95 return rc;
96}
drh85c8f292010-01-13 17:39:53 +000097#endif /* SQLITE_OMIT_FLOATING_POINT */
drhc81c11f2009-11-10 01:30:52 +000098
99/*
100** Compute a string length that is limited to what can be stored in
101** lower 30 bits of a 32-bit signed integer.
102**
103** The value returned will never be negative. Nor will it ever be greater
104** than the actual length of the string. For very long strings (greater
105** than 1GiB) the value returned might be less than the true string length.
106*/
107int sqlite3Strlen30(const char *z){
drhc81c11f2009-11-10 01:30:52 +0000108 if( z==0 ) return 0;
drh1116bf12015-06-30 03:18:33 +0000109 return 0x3fffffff & (int)strlen(z);
drhc81c11f2009-11-10 01:30:52 +0000110}
111
112/*
drh94eaafa2016-02-29 15:53:11 +0000113** The string z[] is followed immediately by another string. Return
114** a poiner to that other string.
115*/
116const char *sqlite3StrNext(const char *z){
117 return z + strlen(z) + 1;
118}
119
120/*
drh13f40da2014-08-22 18:00:11 +0000121** Set the current error code to err_code and clear any prior error message.
122*/
123void sqlite3Error(sqlite3 *db, int err_code){
124 assert( db!=0 );
125 db->errCode = err_code;
126 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
127}
128
129/*
drhc81c11f2009-11-10 01:30:52 +0000130** Set the most recent error code and error string for the sqlite
131** handle "db". The error code is set to "err_code".
132**
133** If it is not NULL, string zFormat specifies the format of the
134** error string in the style of the printf functions: The following
135** format characters are allowed:
136**
137** %s Insert a string
138** %z A string that should be freed after use
139** %d Insert an integer
140** %T Insert a token
141** %S Insert the first element of a SrcList
142**
143** zFormat and any string tokens that follow it are assumed to be
144** encoded in UTF-8.
145**
146** To clear the most recent error for sqlite handle "db", sqlite3Error
147** should be called with err_code set to SQLITE_OK and zFormat set
148** to NULL.
149*/
drh13f40da2014-08-22 18:00:11 +0000150void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
drha3cc0072013-12-13 16:23:55 +0000151 assert( db!=0 );
152 db->errCode = err_code;
drh13f40da2014-08-22 18:00:11 +0000153 if( zFormat==0 ){
154 sqlite3Error(db, err_code);
155 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
drha3cc0072013-12-13 16:23:55 +0000156 char *z;
157 va_list ap;
158 va_start(ap, zFormat);
159 z = sqlite3VMPrintf(db, zFormat, ap);
160 va_end(ap);
161 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
drhc81c11f2009-11-10 01:30:52 +0000162 }
163}
164
165/*
166** Add an error message to pParse->zErrMsg and increment pParse->nErr.
167** The following formatting characters are allowed:
168**
169** %s Insert a string
170** %z A string that should be freed after use
171** %d Insert an integer
172** %T Insert a token
173** %S Insert the first element of a SrcList
174**
drh13f40da2014-08-22 18:00:11 +0000175** This function should be used to report any error that occurs while
drhc81c11f2009-11-10 01:30:52 +0000176** compiling an SQL statement (i.e. within sqlite3_prepare()). The
177** last thing the sqlite3_prepare() function does is copy the error
178** stored by this function into the database handle using sqlite3Error().
drh13f40da2014-08-22 18:00:11 +0000179** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
180** during statement execution (sqlite3_step() etc.).
drhc81c11f2009-11-10 01:30:52 +0000181*/
182void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
drha7564662010-02-22 19:32:31 +0000183 char *zMsg;
drhc81c11f2009-11-10 01:30:52 +0000184 va_list ap;
185 sqlite3 *db = pParse->db;
drhc81c11f2009-11-10 01:30:52 +0000186 va_start(ap, zFormat);
drha7564662010-02-22 19:32:31 +0000187 zMsg = sqlite3VMPrintf(db, zFormat, ap);
drhc81c11f2009-11-10 01:30:52 +0000188 va_end(ap);
drha7564662010-02-22 19:32:31 +0000189 if( db->suppressErr ){
190 sqlite3DbFree(db, zMsg);
191 }else{
192 pParse->nErr++;
193 sqlite3DbFree(db, pParse->zErrMsg);
194 pParse->zErrMsg = zMsg;
195 pParse->rc = SQLITE_ERROR;
drha7564662010-02-22 19:32:31 +0000196 }
drhc81c11f2009-11-10 01:30:52 +0000197}
198
199/*
200** Convert an SQL-style quoted string into a normal string by removing
201** the quote characters. The conversion is done in-place. If the
202** input does not begin with a quote character, then this routine
203** is a no-op.
204**
205** The input string must be zero-terminated. A new zero-terminator
206** is added to the dequoted string.
207**
208** The return value is -1 if no dequoting occurs or the length of the
209** dequoted string, exclusive of the zero terminator, if dequoting does
210** occur.
211**
212** 2002-Feb-14: This routine is extended to remove MS-Access style
peter.d.reid60ec9142014-09-06 16:39:46 +0000213** brackets from around identifiers. For example: "[a-b-c]" becomes
drhc81c11f2009-11-10 01:30:52 +0000214** "a-b-c".
215*/
216int sqlite3Dequote(char *z){
217 char quote;
218 int i, j;
219 if( z==0 ) return -1;
220 quote = z[0];
221 switch( quote ){
222 case '\'': break;
223 case '"': break;
224 case '`': break; /* For MySQL compatibility */
225 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
226 default: return -1;
227 }
drh9ccd8652013-09-13 16:36:46 +0000228 for(i=1, j=0;; i++){
229 assert( z[i] );
drhc81c11f2009-11-10 01:30:52 +0000230 if( z[i]==quote ){
231 if( z[i+1]==quote ){
232 z[j++] = quote;
233 i++;
234 }else{
235 break;
236 }
237 }else{
238 z[j++] = z[i];
239 }
240 }
241 z[j] = 0;
242 return j;
243}
244
drh40aced52016-01-22 17:48:09 +0000245/*
246** Generate a Token object from a string
247*/
248void sqlite3TokenInit(Token *p, char *z){
249 p->z = z;
250 p->n = sqlite3Strlen30(z);
251}
252
drhc81c11f2009-11-10 01:30:52 +0000253/* Convenient short-hand */
254#define UpperToLower sqlite3UpperToLower
255
256/*
257** Some systems have stricmp(). Others have strcasecmp(). Because
258** there is no consistency, we will define our own.
drh9f129f42010-08-31 15:27:32 +0000259**
drh0299b402012-03-19 17:42:46 +0000260** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
261** sqlite3_strnicmp() APIs allow applications and extensions to compare
262** the contents of two buffers containing UTF-8 strings in a
263** case-independent fashion, using the same definition of "case
264** independence" that SQLite uses internally when comparing identifiers.
drhc81c11f2009-11-10 01:30:52 +0000265*/
drh3fa97302012-02-22 16:58:36 +0000266int sqlite3_stricmp(const char *zLeft, const char *zRight){
drh9ca95732014-10-24 00:35:58 +0000267 if( zLeft==0 ){
268 return zRight ? -1 : 0;
269 }else if( zRight==0 ){
270 return 1;
271 }
drh80738d92016-02-15 00:34:16 +0000272 return sqlite3StrICmp(zLeft, zRight);
273}
274int sqlite3StrICmp(const char *zLeft, const char *zRight){
275 unsigned char *a, *b;
276 int c;
drhc81c11f2009-11-10 01:30:52 +0000277 a = (unsigned char *)zLeft;
278 b = (unsigned char *)zRight;
drh80738d92016-02-15 00:34:16 +0000279 for(;;){
280 c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
281 if( c || *a==0 ) break;
282 a++;
283 b++;
284 }
285 return c;
drhc81c11f2009-11-10 01:30:52 +0000286}
287int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
288 register unsigned char *a, *b;
drh9ca95732014-10-24 00:35:58 +0000289 if( zLeft==0 ){
290 return zRight ? -1 : 0;
291 }else if( zRight==0 ){
292 return 1;
293 }
drhc81c11f2009-11-10 01:30:52 +0000294 a = (unsigned char *)zLeft;
295 b = (unsigned char *)zRight;
296 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
297 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
298}
299
300/*
drh9339da12010-09-30 00:50:49 +0000301** The string z[] is an text representation of a real number.
drh025586a2010-09-30 17:33:11 +0000302** Convert this string to a double and write it into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000303**
drh9339da12010-09-30 00:50:49 +0000304** The string z[] is length bytes in length (bytes, not characters) and
305** uses the encoding enc. The string is not necessarily zero-terminated.
drhc81c11f2009-11-10 01:30:52 +0000306**
drh9339da12010-09-30 00:50:49 +0000307** Return TRUE if the result is a valid real number (or integer) and FALSE
drh025586a2010-09-30 17:33:11 +0000308** if the string is empty or contains extraneous text. Valid numbers
309** are in one of these formats:
310**
311** [+-]digits[E[+-]digits]
312** [+-]digits.[digits][E[+-]digits]
313** [+-].digits[E[+-]digits]
314**
315** Leading and trailing whitespace is ignored for the purpose of determining
316** validity.
317**
318** If some prefix of the input string is a valid number, this routine
319** returns FALSE but it still converts the prefix and writes the result
320** into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000321*/
drh9339da12010-09-30 00:50:49 +0000322int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
drhc81c11f2009-11-10 01:30:52 +0000323#ifndef SQLITE_OMIT_FLOATING_POINT
drh0e5fba72013-03-20 12:04:29 +0000324 int incr;
drh9339da12010-09-30 00:50:49 +0000325 const char *zEnd = z + length;
drhc81c11f2009-11-10 01:30:52 +0000326 /* sign * significand * (10 ^ (esign * exponent)) */
drh025586a2010-09-30 17:33:11 +0000327 int sign = 1; /* sign of significand */
328 i64 s = 0; /* significand */
329 int d = 0; /* adjust exponent for shifting decimal point */
330 int esign = 1; /* sign of exponent */
331 int e = 0; /* exponent */
332 int eValid = 1; /* True exponent is either not used or is well-formed */
drhc81c11f2009-11-10 01:30:52 +0000333 double result;
334 int nDigits = 0;
drh0e5fba72013-03-20 12:04:29 +0000335 int nonNum = 0;
drhc81c11f2009-11-10 01:30:52 +0000336
drh0e5fba72013-03-20 12:04:29 +0000337 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
drh025586a2010-09-30 17:33:11 +0000338 *pResult = 0.0; /* Default return value, in case of an error */
339
drh0e5fba72013-03-20 12:04:29 +0000340 if( enc==SQLITE_UTF8 ){
341 incr = 1;
342 }else{
343 int i;
344 incr = 2;
345 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
346 for(i=3-enc; i<length && z[i]==0; i+=2){}
347 nonNum = i<length;
348 zEnd = z+i+enc-3;
349 z += (enc&1);
350 }
drh9339da12010-09-30 00:50:49 +0000351
drhc81c11f2009-11-10 01:30:52 +0000352 /* skip leading spaces */
drh9339da12010-09-30 00:50:49 +0000353 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
drh025586a2010-09-30 17:33:11 +0000354 if( z>=zEnd ) return 0;
drh9339da12010-09-30 00:50:49 +0000355
drhc81c11f2009-11-10 01:30:52 +0000356 /* get sign of significand */
357 if( *z=='-' ){
358 sign = -1;
drh9339da12010-09-30 00:50:49 +0000359 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000360 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000361 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000362 }
drh9339da12010-09-30 00:50:49 +0000363
drhc81c11f2009-11-10 01:30:52 +0000364 /* skip leading zeroes */
drh9339da12010-09-30 00:50:49 +0000365 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000366
367 /* copy max significant digits to significand */
drh9339da12010-09-30 00:50:49 +0000368 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
drhc81c11f2009-11-10 01:30:52 +0000369 s = s*10 + (*z - '0');
drh9339da12010-09-30 00:50:49 +0000370 z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000371 }
drh9339da12010-09-30 00:50:49 +0000372
drhc81c11f2009-11-10 01:30:52 +0000373 /* skip non-significant significand digits
374 ** (increase exponent by d to shift decimal left) */
drh9339da12010-09-30 00:50:49 +0000375 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
376 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000377
378 /* if decimal point is present */
379 if( *z=='.' ){
drh9339da12010-09-30 00:50:49 +0000380 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000381 /* copy digits from after decimal to significand
382 ** (decrease exponent by d to shift decimal right) */
drh9339da12010-09-30 00:50:49 +0000383 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
drhc81c11f2009-11-10 01:30:52 +0000384 s = s*10 + (*z - '0');
drh9339da12010-09-30 00:50:49 +0000385 z+=incr, nDigits++, d--;
drhc81c11f2009-11-10 01:30:52 +0000386 }
387 /* skip non-significant digits */
drh9339da12010-09-30 00:50:49 +0000388 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000389 }
drh9339da12010-09-30 00:50:49 +0000390 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000391
392 /* if exponent is present */
393 if( *z=='e' || *z=='E' ){
drh9339da12010-09-30 00:50:49 +0000394 z+=incr;
drh025586a2010-09-30 17:33:11 +0000395 eValid = 0;
drh9339da12010-09-30 00:50:49 +0000396 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000397 /* get sign of exponent */
398 if( *z=='-' ){
399 esign = -1;
drh9339da12010-09-30 00:50:49 +0000400 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000401 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000402 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000403 }
404 /* copy digits to exponent */
drh9339da12010-09-30 00:50:49 +0000405 while( z<zEnd && sqlite3Isdigit(*z) ){
drh57db4a72011-10-17 20:41:46 +0000406 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
drh9339da12010-09-30 00:50:49 +0000407 z+=incr;
drh025586a2010-09-30 17:33:11 +0000408 eValid = 1;
drhc81c11f2009-11-10 01:30:52 +0000409 }
410 }
411
drh025586a2010-09-30 17:33:11 +0000412 /* skip trailing spaces */
413 if( nDigits && eValid ){
414 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
415 }
416
drh9339da12010-09-30 00:50:49 +0000417do_atof_calc:
drhc81c11f2009-11-10 01:30:52 +0000418 /* adjust exponent by d, and update sign */
419 e = (e*esign) + d;
420 if( e<0 ) {
421 esign = -1;
422 e *= -1;
423 } else {
424 esign = 1;
425 }
426
427 /* if 0 significand */
428 if( !s ) {
429 /* In the IEEE 754 standard, zero is signed.
430 ** Add the sign if we've seen at least one digit */
431 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
432 } else {
433 /* attempt to reduce exponent */
434 if( esign>0 ){
435 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
436 }else{
437 while( !(s%10) && e>0 ) e--,s/=10;
438 }
439
440 /* adjust the sign of significand */
441 s = sign<0 ? -s : s;
442
443 /* if exponent, scale significand as appropriate
444 ** and store in result. */
445 if( e ){
drh89f15082012-06-19 00:45:16 +0000446 LONGDOUBLE_TYPE scale = 1.0;
drhc81c11f2009-11-10 01:30:52 +0000447 /* attempt to handle extremely small/large numbers better */
448 if( e>307 && e<342 ){
449 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
450 if( esign<0 ){
451 result = s / scale;
452 result /= 1.0e+308;
453 }else{
454 result = s * scale;
455 result *= 1.0e+308;
456 }
drh2458a2e2011-10-17 12:14:26 +0000457 }else if( e>=342 ){
458 if( esign<0 ){
459 result = 0.0*s;
460 }else{
461 result = 1e308*1e308*s; /* Infinity */
462 }
drhc81c11f2009-11-10 01:30:52 +0000463 }else{
464 /* 1.0e+22 is the largest power of 10 than can be
465 ** represented exactly. */
466 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
467 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
468 if( esign<0 ){
469 result = s / scale;
470 }else{
471 result = s * scale;
472 }
473 }
474 } else {
475 result = (double)s;
476 }
477 }
478
479 /* store the result */
480 *pResult = result;
481
drh025586a2010-09-30 17:33:11 +0000482 /* return true if number and no extra non-whitespace chracters after */
drh0e5fba72013-03-20 12:04:29 +0000483 return z>=zEnd && nDigits>0 && eValid && nonNum==0;
drhc81c11f2009-11-10 01:30:52 +0000484#else
shaneh5f1d6b62010-09-30 16:51:25 +0000485 return !sqlite3Atoi64(z, pResult, length, enc);
drhc81c11f2009-11-10 01:30:52 +0000486#endif /* SQLITE_OMIT_FLOATING_POINT */
487}
488
489/*
490** Compare the 19-character string zNum against the text representation
491** value 2^63: 9223372036854775808. Return negative, zero, or positive
492** if zNum is less than, equal to, or greater than the string.
shaneh5f1d6b62010-09-30 16:51:25 +0000493** Note that zNum must contain exactly 19 characters.
drhc81c11f2009-11-10 01:30:52 +0000494**
495** Unlike memcmp() this routine is guaranteed to return the difference
496** in the values of the last digit if the only difference is in the
497** last digit. So, for example,
498**
drh9339da12010-09-30 00:50:49 +0000499** compare2pow63("9223372036854775800", 1)
drhc81c11f2009-11-10 01:30:52 +0000500**
501** will return -8.
502*/
drh9339da12010-09-30 00:50:49 +0000503static int compare2pow63(const char *zNum, int incr){
504 int c = 0;
505 int i;
506 /* 012345678901234567 */
507 const char *pow63 = "922337203685477580";
508 for(i=0; c==0 && i<18; i++){
509 c = (zNum[i*incr]-pow63[i])*10;
510 }
drhc81c11f2009-11-10 01:30:52 +0000511 if( c==0 ){
drh9339da12010-09-30 00:50:49 +0000512 c = zNum[18*incr] - '8';
drh44dbca82010-01-13 04:22:20 +0000513 testcase( c==(-1) );
514 testcase( c==0 );
515 testcase( c==(+1) );
drhc81c11f2009-11-10 01:30:52 +0000516 }
517 return c;
518}
519
drhc81c11f2009-11-10 01:30:52 +0000520/*
drh9296c182014-07-23 13:40:49 +0000521** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
522** routine does *not* accept hexadecimal notation.
drh158b9cb2011-03-05 20:59:46 +0000523**
524** If the zNum value is representable as a 64-bit twos-complement
525** integer, then write that value into *pNum and return 0.
526**
drha256c1a2013-12-01 01:18:29 +0000527** If zNum is exactly 9223372036854775808, return 2. This special
528** case is broken out because while 9223372036854775808 cannot be a
529** signed 64-bit integer, its negative -9223372036854775808 can be.
drh158b9cb2011-03-05 20:59:46 +0000530**
531** If zNum is too big for a 64-bit integer and is not
drha256c1a2013-12-01 01:18:29 +0000532** 9223372036854775808 or if zNum contains any non-numeric text,
drh0e5fba72013-03-20 12:04:29 +0000533** then return 1.
drhc81c11f2009-11-10 01:30:52 +0000534**
drh9339da12010-09-30 00:50:49 +0000535** length is the number of bytes in the string (bytes, not characters).
536** The string is not necessarily zero-terminated. The encoding is
537** given by enc.
drhc81c11f2009-11-10 01:30:52 +0000538*/
drh9339da12010-09-30 00:50:49 +0000539int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
drh0e5fba72013-03-20 12:04:29 +0000540 int incr;
drh158b9cb2011-03-05 20:59:46 +0000541 u64 u = 0;
shaneh5f1d6b62010-09-30 16:51:25 +0000542 int neg = 0; /* assume positive */
drh9339da12010-09-30 00:50:49 +0000543 int i;
544 int c = 0;
drh0e5fba72013-03-20 12:04:29 +0000545 int nonNum = 0;
drhc81c11f2009-11-10 01:30:52 +0000546 const char *zStart;
drh9339da12010-09-30 00:50:49 +0000547 const char *zEnd = zNum + length;
drh0e5fba72013-03-20 12:04:29 +0000548 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
549 if( enc==SQLITE_UTF8 ){
550 incr = 1;
551 }else{
552 incr = 2;
553 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
554 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
555 nonNum = i<length;
556 zEnd = zNum+i+enc-3;
557 zNum += (enc&1);
558 }
drh9339da12010-09-30 00:50:49 +0000559 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
drh158b9cb2011-03-05 20:59:46 +0000560 if( zNum<zEnd ){
561 if( *zNum=='-' ){
562 neg = 1;
563 zNum+=incr;
564 }else if( *zNum=='+' ){
565 zNum+=incr;
566 }
drhc81c11f2009-11-10 01:30:52 +0000567 }
568 zStart = zNum;
drh9339da12010-09-30 00:50:49 +0000569 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
570 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
drh158b9cb2011-03-05 20:59:46 +0000571 u = u*10 + c - '0';
drhc81c11f2009-11-10 01:30:52 +0000572 }
drh158b9cb2011-03-05 20:59:46 +0000573 if( u>LARGEST_INT64 ){
drhde1a8b82013-11-26 15:45:02 +0000574 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
drh158b9cb2011-03-05 20:59:46 +0000575 }else if( neg ){
576 *pNum = -(i64)u;
577 }else{
578 *pNum = (i64)u;
579 }
drh44dbca82010-01-13 04:22:20 +0000580 testcase( i==18 );
581 testcase( i==19 );
582 testcase( i==20 );
drh62aaa6c2015-11-21 17:27:42 +0000583 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum)
584 || i>19*incr || nonNum ){
drhc81c11f2009-11-10 01:30:52 +0000585 /* zNum is empty or contains non-numeric text or is longer
shaneh5f1d6b62010-09-30 16:51:25 +0000586 ** than 19 digits (thus guaranteeing that it is too large) */
587 return 1;
drh9339da12010-09-30 00:50:49 +0000588 }else if( i<19*incr ){
drhc81c11f2009-11-10 01:30:52 +0000589 /* Less than 19 digits, so we know that it fits in 64 bits */
drh158b9cb2011-03-05 20:59:46 +0000590 assert( u<=LARGEST_INT64 );
shaneh5f1d6b62010-09-30 16:51:25 +0000591 return 0;
drhc81c11f2009-11-10 01:30:52 +0000592 }else{
drh158b9cb2011-03-05 20:59:46 +0000593 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
594 c = compare2pow63(zNum, incr);
595 if( c<0 ){
596 /* zNum is less than 9223372036854775808 so it fits */
597 assert( u<=LARGEST_INT64 );
598 return 0;
599 }else if( c>0 ){
600 /* zNum is greater than 9223372036854775808 so it overflows */
601 return 1;
602 }else{
603 /* zNum is exactly 9223372036854775808. Fits if negative. The
604 ** special case 2 overflow if positive */
605 assert( u-1==LARGEST_INT64 );
drh158b9cb2011-03-05 20:59:46 +0000606 return neg ? 0 : 2;
607 }
drhc81c11f2009-11-10 01:30:52 +0000608 }
609}
610
611/*
drh9296c182014-07-23 13:40:49 +0000612** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
613** into a 64-bit signed integer. This routine accepts hexadecimal literals,
614** whereas sqlite3Atoi64() does not.
615**
616** Returns:
617**
618** 0 Successful transformation. Fits in a 64-bit signed integer.
619** 1 Integer too large for a 64-bit signed integer or is malformed
620** 2 Special case of 9223372036854775808
621*/
622int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
623#ifndef SQLITE_OMIT_HEX_INTEGER
624 if( z[0]=='0'
625 && (z[1]=='x' || z[1]=='X')
626 && sqlite3Isxdigit(z[2])
627 ){
628 u64 u = 0;
629 int i, k;
630 for(i=2; z[i]=='0'; i++){}
631 for(k=i; sqlite3Isxdigit(z[k]); k++){
632 u = u*16 + sqlite3HexToInt(z[k]);
633 }
634 memcpy(pOut, &u, 8);
635 return (z[k]==0 && k-i<=16) ? 0 : 1;
636 }else
637#endif /* SQLITE_OMIT_HEX_INTEGER */
638 {
639 return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
640 }
641}
642
643/*
drhc81c11f2009-11-10 01:30:52 +0000644** If zNum represents an integer that will fit in 32-bits, then set
645** *pValue to that integer and return true. Otherwise return false.
646**
drh9296c182014-07-23 13:40:49 +0000647** This routine accepts both decimal and hexadecimal notation for integers.
648**
drhc81c11f2009-11-10 01:30:52 +0000649** Any non-numeric characters that following zNum are ignored.
650** This is different from sqlite3Atoi64() which requires the
651** input number to be zero-terminated.
652*/
653int sqlite3GetInt32(const char *zNum, int *pValue){
654 sqlite_int64 v = 0;
655 int i, c;
656 int neg = 0;
657 if( zNum[0]=='-' ){
658 neg = 1;
659 zNum++;
660 }else if( zNum[0]=='+' ){
661 zNum++;
662 }
drh28e048c2014-07-23 01:26:51 +0000663#ifndef SQLITE_OMIT_HEX_INTEGER
664 else if( zNum[0]=='0'
665 && (zNum[1]=='x' || zNum[1]=='X')
666 && sqlite3Isxdigit(zNum[2])
667 ){
668 u32 u = 0;
669 zNum += 2;
670 while( zNum[0]=='0' ) zNum++;
671 for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
672 u = u*16 + sqlite3HexToInt(zNum[i]);
673 }
674 if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
675 memcpy(pValue, &u, 4);
676 return 1;
677 }else{
678 return 0;
679 }
680 }
681#endif
drh935f2e72015-04-18 04:45:00 +0000682 while( zNum[0]=='0' ) zNum++;
drhc81c11f2009-11-10 01:30:52 +0000683 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
684 v = v*10 + c;
685 }
686
687 /* The longest decimal representation of a 32 bit integer is 10 digits:
688 **
689 ** 1234567890
690 ** 2^31 -> 2147483648
691 */
drh44dbca82010-01-13 04:22:20 +0000692 testcase( i==10 );
drhc81c11f2009-11-10 01:30:52 +0000693 if( i>10 ){
694 return 0;
695 }
drh44dbca82010-01-13 04:22:20 +0000696 testcase( v-neg==2147483647 );
drhc81c11f2009-11-10 01:30:52 +0000697 if( v-neg>2147483647 ){
698 return 0;
699 }
700 if( neg ){
701 v = -v;
702 }
703 *pValue = (int)v;
704 return 1;
705}
706
707/*
drh60ac3f42010-11-23 18:59:27 +0000708** Return a 32-bit integer value extracted from a string. If the
709** string is not an integer, just return 0.
710*/
711int sqlite3Atoi(const char *z){
712 int x = 0;
713 if( z ) sqlite3GetInt32(z, &x);
714 return x;
715}
716
717/*
drhc81c11f2009-11-10 01:30:52 +0000718** The variable-length integer encoding is as follows:
719**
720** KEY:
721** A = 0xxxxxxx 7 bits of data and one flag bit
722** B = 1xxxxxxx 7 bits of data and one flag bit
723** C = xxxxxxxx 8 bits of data
724**
725** 7 bits - A
726** 14 bits - BA
727** 21 bits - BBA
728** 28 bits - BBBA
729** 35 bits - BBBBA
730** 42 bits - BBBBBA
731** 49 bits - BBBBBBA
732** 56 bits - BBBBBBBA
733** 64 bits - BBBBBBBBC
734*/
735
736/*
737** Write a 64-bit variable-length integer to memory starting at p[0].
738** The length of data write will be between 1 and 9 bytes. The number
739** of bytes written is returned.
740**
741** A variable-length integer consists of the lower 7 bits of each byte
742** for all bytes that have the 8th bit set and one byte with the 8th
743** bit clear. Except, if we get to the 9th byte, it stores the full
744** 8 bits and is the last byte.
745*/
drh2f2b2b82014-08-22 18:48:25 +0000746static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
drhc81c11f2009-11-10 01:30:52 +0000747 int i, j, n;
748 u8 buf[10];
749 if( v & (((u64)0xff000000)<<32) ){
750 p[8] = (u8)v;
751 v >>= 8;
752 for(i=7; i>=0; i--){
753 p[i] = (u8)((v & 0x7f) | 0x80);
754 v >>= 7;
755 }
756 return 9;
757 }
758 n = 0;
759 do{
760 buf[n++] = (u8)((v & 0x7f) | 0x80);
761 v >>= 7;
762 }while( v!=0 );
763 buf[0] &= 0x7f;
764 assert( n<=9 );
765 for(i=0, j=n-1; j>=0; j--, i++){
766 p[i] = buf[j];
767 }
768 return n;
769}
drh2f2b2b82014-08-22 18:48:25 +0000770int sqlite3PutVarint(unsigned char *p, u64 v){
771 if( v<=0x7f ){
772 p[0] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000773 return 1;
774 }
drh2f2b2b82014-08-22 18:48:25 +0000775 if( v<=0x3fff ){
776 p[0] = ((v>>7)&0x7f)|0x80;
777 p[1] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000778 return 2;
779 }
drh2f2b2b82014-08-22 18:48:25 +0000780 return putVarint64(p,v);
drhc81c11f2009-11-10 01:30:52 +0000781}
782
783/*
drh0b2864c2010-03-03 15:18:38 +0000784** Bitmasks used by sqlite3GetVarint(). These precomputed constants
785** are defined here rather than simply putting the constant expressions
786** inline in order to work around bugs in the RVT compiler.
787**
788** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
789**
790** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
791*/
792#define SLOT_2_0 0x001fc07f
793#define SLOT_4_2_0 0xf01fc07f
794
795
796/*
drhc81c11f2009-11-10 01:30:52 +0000797** Read a 64-bit variable-length integer from memory starting at p[0].
798** Return the number of bytes read. The value is stored in *v.
799*/
800u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
801 u32 a,b,s;
802
803 a = *p;
804 /* a: p0 (unmasked) */
805 if (!(a&0x80))
806 {
807 *v = a;
808 return 1;
809 }
810
811 p++;
812 b = *p;
813 /* b: p1 (unmasked) */
814 if (!(b&0x80))
815 {
816 a &= 0x7f;
817 a = a<<7;
818 a |= b;
819 *v = a;
820 return 2;
821 }
822
drh0b2864c2010-03-03 15:18:38 +0000823 /* Verify that constants are precomputed correctly */
824 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
shaneh1da207e2010-03-09 14:41:12 +0000825 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
drh0b2864c2010-03-03 15:18:38 +0000826
drhc81c11f2009-11-10 01:30:52 +0000827 p++;
828 a = a<<14;
829 a |= *p;
830 /* a: p0<<14 | p2 (unmasked) */
831 if (!(a&0x80))
832 {
drh0b2864c2010-03-03 15:18:38 +0000833 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000834 b &= 0x7f;
835 b = b<<7;
836 a |= b;
837 *v = a;
838 return 3;
839 }
840
841 /* CSE1 from below */
drh0b2864c2010-03-03 15:18:38 +0000842 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000843 p++;
844 b = b<<14;
845 b |= *p;
846 /* b: p1<<14 | p3 (unmasked) */
847 if (!(b&0x80))
848 {
drh0b2864c2010-03-03 15:18:38 +0000849 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000850 /* moved CSE1 up */
851 /* a &= (0x7f<<14)|(0x7f); */
852 a = a<<7;
853 a |= b;
854 *v = a;
855 return 4;
856 }
857
858 /* a: p0<<14 | p2 (masked) */
859 /* b: p1<<14 | p3 (unmasked) */
860 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
861 /* moved CSE1 up */
862 /* a &= (0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +0000863 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000864 s = a;
865 /* s: p0<<14 | p2 (masked) */
866
867 p++;
868 a = a<<14;
869 a |= *p;
870 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
871 if (!(a&0x80))
872 {
drh62aaa6c2015-11-21 17:27:42 +0000873 /* we can skip these cause they were (effectively) done above
874 ** while calculating s */
drhc81c11f2009-11-10 01:30:52 +0000875 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
876 /* b &= (0x7f<<14)|(0x7f); */
877 b = b<<7;
878 a |= b;
879 s = s>>18;
880 *v = ((u64)s)<<32 | a;
881 return 5;
882 }
883
884 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
885 s = s<<7;
886 s |= b;
887 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
888
889 p++;
890 b = b<<14;
891 b |= *p;
892 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
893 if (!(b&0x80))
894 {
895 /* we can skip this cause it was (effectively) done above in calc'ing s */
896 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +0000897 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000898 a = a<<7;
899 a |= b;
900 s = s>>18;
901 *v = ((u64)s)<<32 | a;
902 return 6;
903 }
904
905 p++;
906 a = a<<14;
907 a |= *p;
908 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
909 if (!(a&0x80))
910 {
drh0b2864c2010-03-03 15:18:38 +0000911 a &= SLOT_4_2_0;
912 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000913 b = b<<7;
914 a |= b;
915 s = s>>11;
916 *v = ((u64)s)<<32 | a;
917 return 7;
918 }
919
920 /* CSE2 from below */
drh0b2864c2010-03-03 15:18:38 +0000921 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000922 p++;
923 b = b<<14;
924 b |= *p;
925 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
926 if (!(b&0x80))
927 {
drh0b2864c2010-03-03 15:18:38 +0000928 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +0000929 /* moved CSE2 up */
930 /* a &= (0x7f<<14)|(0x7f); */
931 a = a<<7;
932 a |= b;
933 s = s>>4;
934 *v = ((u64)s)<<32 | a;
935 return 8;
936 }
937
938 p++;
939 a = a<<15;
940 a |= *p;
941 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
942
943 /* moved CSE2 up */
944 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
drh0b2864c2010-03-03 15:18:38 +0000945 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000946 b = b<<8;
947 a |= b;
948
949 s = s<<4;
950 b = p[-4];
951 b &= 0x7f;
952 b = b>>3;
953 s |= b;
954
955 *v = ((u64)s)<<32 | a;
956
957 return 9;
958}
959
960/*
961** Read a 32-bit variable-length integer from memory starting at p[0].
962** Return the number of bytes read. The value is stored in *v.
963**
964** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
965** integer, then set *v to 0xffffffff.
966**
967** A MACRO version, getVarint32, is provided which inlines the
968** single-byte case. All code should use the MACRO version as
969** this function assumes the single-byte case has already been handled.
970*/
971u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
972 u32 a,b;
973
974 /* The 1-byte case. Overwhelmingly the most common. Handled inline
975 ** by the getVarin32() macro */
976 a = *p;
977 /* a: p0 (unmasked) */
978#ifndef getVarint32
979 if (!(a&0x80))
980 {
981 /* Values between 0 and 127 */
982 *v = a;
983 return 1;
984 }
985#endif
986
987 /* The 2-byte case */
988 p++;
989 b = *p;
990 /* b: p1 (unmasked) */
991 if (!(b&0x80))
992 {
993 /* Values between 128 and 16383 */
994 a &= 0x7f;
995 a = a<<7;
996 *v = a | b;
997 return 2;
998 }
999
1000 /* The 3-byte case */
1001 p++;
1002 a = a<<14;
1003 a |= *p;
1004 /* a: p0<<14 | p2 (unmasked) */
1005 if (!(a&0x80))
1006 {
1007 /* Values between 16384 and 2097151 */
1008 a &= (0x7f<<14)|(0x7f);
1009 b &= 0x7f;
1010 b = b<<7;
1011 *v = a | b;
1012 return 3;
1013 }
1014
1015 /* A 32-bit varint is used to store size information in btrees.
1016 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
1017 ** A 3-byte varint is sufficient, for example, to record the size
1018 ** of a 1048569-byte BLOB or string.
1019 **
1020 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
1021 ** rare larger cases can be handled by the slower 64-bit varint
1022 ** routine.
1023 */
1024#if 1
1025 {
1026 u64 v64;
1027 u8 n;
1028
1029 p -= 2;
1030 n = sqlite3GetVarint(p, &v64);
1031 assert( n>3 && n<=9 );
1032 if( (v64 & SQLITE_MAX_U32)!=v64 ){
1033 *v = 0xffffffff;
1034 }else{
1035 *v = (u32)v64;
1036 }
1037 return n;
1038 }
1039
1040#else
1041 /* For following code (kept for historical record only) shows an
1042 ** unrolling for the 3- and 4-byte varint cases. This code is
1043 ** slightly faster, but it is also larger and much harder to test.
1044 */
1045 p++;
1046 b = b<<14;
1047 b |= *p;
1048 /* b: p1<<14 | p3 (unmasked) */
1049 if (!(b&0x80))
1050 {
1051 /* Values between 2097152 and 268435455 */
1052 b &= (0x7f<<14)|(0x7f);
1053 a &= (0x7f<<14)|(0x7f);
1054 a = a<<7;
1055 *v = a | b;
1056 return 4;
1057 }
1058
1059 p++;
1060 a = a<<14;
1061 a |= *p;
1062 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1063 if (!(a&0x80))
1064 {
dan3bbe7612010-03-03 16:02:05 +00001065 /* Values between 268435456 and 34359738367 */
1066 a &= SLOT_4_2_0;
1067 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +00001068 b = b<<7;
1069 *v = a | b;
1070 return 5;
1071 }
1072
1073 /* We can only reach this point when reading a corrupt database
1074 ** file. In that case we are not in any hurry. Use the (relatively
1075 ** slow) general-purpose sqlite3GetVarint() routine to extract the
1076 ** value. */
1077 {
1078 u64 v64;
1079 u8 n;
1080
1081 p -= 4;
1082 n = sqlite3GetVarint(p, &v64);
1083 assert( n>5 && n<=9 );
1084 *v = (u32)v64;
1085 return n;
1086 }
1087#endif
1088}
1089
1090/*
1091** Return the number of bytes that will be needed to store the given
1092** 64-bit integer.
1093*/
1094int sqlite3VarintLen(u64 v){
drh59a53642015-09-01 22:29:07 +00001095 int i;
drh6f17c092016-03-04 21:18:09 +00001096 for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
drhc81c11f2009-11-10 01:30:52 +00001097 return i;
1098}
1099
1100
1101/*
1102** Read or write a four-byte big-endian integer value.
1103*/
1104u32 sqlite3Get4byte(const u8 *p){
drh5372e4d2015-06-30 12:47:09 +00001105#if SQLITE_BYTEORDER==4321
1106 u32 x;
1107 memcpy(&x,p,4);
1108 return x;
mistachkin60e08072015-07-29 21:47:39 +00001109#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1110 && defined(__GNUC__) && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:09 +00001111 u32 x;
1112 memcpy(&x,p,4);
1113 return __builtin_bswap32(x);
mistachkin60e08072015-07-29 21:47:39 +00001114#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1115 && defined(_MSC_VER) && _MSC_VER>=1300
mistachkin647ca462015-06-30 17:28:40 +00001116 u32 x;
1117 memcpy(&x,p,4);
1118 return _byteswap_ulong(x);
drh5372e4d2015-06-30 12:47:09 +00001119#else
drh693e6712014-01-24 22:58:00 +00001120 testcase( p[0]&0x80 );
1121 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
drh5372e4d2015-06-30 12:47:09 +00001122#endif
drhc81c11f2009-11-10 01:30:52 +00001123}
1124void sqlite3Put4byte(unsigned char *p, u32 v){
drh5372e4d2015-06-30 12:47:09 +00001125#if SQLITE_BYTEORDER==4321
1126 memcpy(p,&v,4);
drh469753d2016-02-19 13:20:02 +00001127#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1128 && defined(__GNUC__) && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:09 +00001129 u32 x = __builtin_bswap32(v);
1130 memcpy(p,&x,4);
drh469753d2016-02-19 13:20:02 +00001131#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1132 && defined(_MSC_VER) && _MSC_VER>=1300
mistachkin647ca462015-06-30 17:28:40 +00001133 u32 x = _byteswap_ulong(v);
1134 memcpy(p,&x,4);
drh5372e4d2015-06-30 12:47:09 +00001135#else
drhc81c11f2009-11-10 01:30:52 +00001136 p[0] = (u8)(v>>24);
1137 p[1] = (u8)(v>>16);
1138 p[2] = (u8)(v>>8);
1139 p[3] = (u8)v;
drh5372e4d2015-06-30 12:47:09 +00001140#endif
drhc81c11f2009-11-10 01:30:52 +00001141}
1142
drh9296c182014-07-23 13:40:49 +00001143
1144
1145/*
1146** Translate a single byte of Hex into an integer.
1147** This routine only works if h really is a valid hexadecimal
1148** character: 0..9a..fA..F
1149*/
1150u8 sqlite3HexToInt(int h){
1151 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
1152#ifdef SQLITE_ASCII
1153 h += 9*(1&(h>>6));
1154#endif
1155#ifdef SQLITE_EBCDIC
1156 h += 9*(1&~(h>>4));
1157#endif
1158 return (u8)(h & 0xf);
1159}
1160
drhc81c11f2009-11-10 01:30:52 +00001161#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
1162/*
1163** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
1164** value. Return a pointer to its binary value. Space to hold the
1165** binary value has been obtained from malloc and must be freed by
1166** the calling routine.
1167*/
1168void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
1169 char *zBlob;
1170 int i;
1171
drh575fad62016-02-05 13:38:36 +00001172 zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
drhc81c11f2009-11-10 01:30:52 +00001173 n--;
1174 if( zBlob ){
1175 for(i=0; i<n; i+=2){
dancd74b612011-04-22 19:37:32 +00001176 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
drhc81c11f2009-11-10 01:30:52 +00001177 }
1178 zBlob[i/2] = 0;
1179 }
1180 return zBlob;
1181}
1182#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
1183
drh413c3d32010-02-23 20:11:56 +00001184/*
1185** Log an error that is an API call on a connection pointer that should
1186** not have been used. The "type" of connection pointer is given as the
1187** argument. The zType is a word like "NULL" or "closed" or "invalid".
1188*/
1189static void logBadConnection(const char *zType){
1190 sqlite3_log(SQLITE_MISUSE,
1191 "API call with %s database connection pointer",
1192 zType
1193 );
1194}
drhc81c11f2009-11-10 01:30:52 +00001195
1196/*
drhc81c11f2009-11-10 01:30:52 +00001197** Check to make sure we have a valid db pointer. This test is not
1198** foolproof but it does provide some measure of protection against
1199** misuse of the interface such as passing in db pointers that are
1200** NULL or which have been previously closed. If this routine returns
1201** 1 it means that the db pointer is valid and 0 if it should not be
1202** dereferenced for any reason. The calling function should invoke
1203** SQLITE_MISUSE immediately.
1204**
1205** sqlite3SafetyCheckOk() requires that the db pointer be valid for
1206** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
1207** open properly and is not fit for general use but which can be
1208** used as an argument to sqlite3_errmsg() or sqlite3_close().
1209*/
1210int sqlite3SafetyCheckOk(sqlite3 *db){
1211 u32 magic;
drh413c3d32010-02-23 20:11:56 +00001212 if( db==0 ){
1213 logBadConnection("NULL");
1214 return 0;
1215 }
drhc81c11f2009-11-10 01:30:52 +00001216 magic = db->magic;
drh9978c972010-02-23 17:36:32 +00001217 if( magic!=SQLITE_MAGIC_OPEN ){
drhe294da02010-02-25 23:44:15 +00001218 if( sqlite3SafetyCheckSickOrOk(db) ){
1219 testcase( sqlite3GlobalConfig.xLog!=0 );
drh413c3d32010-02-23 20:11:56 +00001220 logBadConnection("unopened");
1221 }
drhc81c11f2009-11-10 01:30:52 +00001222 return 0;
1223 }else{
1224 return 1;
1225 }
1226}
1227int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
1228 u32 magic;
1229 magic = db->magic;
1230 if( magic!=SQLITE_MAGIC_SICK &&
1231 magic!=SQLITE_MAGIC_OPEN &&
drh413c3d32010-02-23 20:11:56 +00001232 magic!=SQLITE_MAGIC_BUSY ){
drhe294da02010-02-25 23:44:15 +00001233 testcase( sqlite3GlobalConfig.xLog!=0 );
drhaf46dc12010-02-24 21:44:07 +00001234 logBadConnection("invalid");
drh413c3d32010-02-23 20:11:56 +00001235 return 0;
1236 }else{
1237 return 1;
1238 }
drhc81c11f2009-11-10 01:30:52 +00001239}
drh158b9cb2011-03-05 20:59:46 +00001240
1241/*
1242** Attempt to add, substract, or multiply the 64-bit signed value iB against
1243** the other 64-bit signed integer at *pA and store the result in *pA.
1244** Return 0 on success. Or if the operation would have resulted in an
1245** overflow, leave *pA unchanged and return 1.
1246*/
1247int sqlite3AddInt64(i64 *pA, i64 iB){
1248 i64 iA = *pA;
1249 testcase( iA==0 ); testcase( iA==1 );
1250 testcase( iB==-1 ); testcase( iB==0 );
1251 if( iB>=0 ){
1252 testcase( iA>0 && LARGEST_INT64 - iA == iB );
1253 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
1254 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001255 }else{
1256 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
1257 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
1258 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001259 }
drh53a6eb32014-02-10 12:59:15 +00001260 *pA += iB;
drh158b9cb2011-03-05 20:59:46 +00001261 return 0;
1262}
1263int sqlite3SubInt64(i64 *pA, i64 iB){
1264 testcase( iB==SMALLEST_INT64+1 );
1265 if( iB==SMALLEST_INT64 ){
1266 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
1267 if( (*pA)>=0 ) return 1;
1268 *pA -= iB;
1269 return 0;
1270 }else{
1271 return sqlite3AddInt64(pA, -iB);
1272 }
1273}
1274#define TWOPOWER32 (((i64)1)<<32)
1275#define TWOPOWER31 (((i64)1)<<31)
1276int sqlite3MulInt64(i64 *pA, i64 iB){
1277 i64 iA = *pA;
1278 i64 iA1, iA0, iB1, iB0, r;
1279
drh158b9cb2011-03-05 20:59:46 +00001280 iA1 = iA/TWOPOWER32;
1281 iA0 = iA % TWOPOWER32;
1282 iB1 = iB/TWOPOWER32;
1283 iB0 = iB % TWOPOWER32;
drh53a6eb32014-02-10 12:59:15 +00001284 if( iA1==0 ){
1285 if( iB1==0 ){
1286 *pA *= iB;
1287 return 0;
1288 }
1289 r = iA0*iB1;
1290 }else if( iB1==0 ){
1291 r = iA1*iB0;
1292 }else{
1293 /* If both iA1 and iB1 are non-zero, overflow will result */
1294 return 1;
1295 }
drh158b9cb2011-03-05 20:59:46 +00001296 testcase( r==(-TWOPOWER31)-1 );
1297 testcase( r==(-TWOPOWER31) );
1298 testcase( r==TWOPOWER31 );
1299 testcase( r==TWOPOWER31-1 );
1300 if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
1301 r *= TWOPOWER32;
1302 if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
1303 *pA = r;
1304 return 0;
1305}
drhd50ffc42011-03-08 02:38:28 +00001306
1307/*
1308** Compute the absolute value of a 32-bit signed integer, of possible. Or
1309** if the integer has a value of -2147483648, return +2147483647
1310*/
1311int sqlite3AbsInt32(int x){
1312 if( x>=0 ) return x;
drh87e79ae2011-03-08 13:06:41 +00001313 if( x==(int)0x80000000 ) return 0x7fffffff;
drhd50ffc42011-03-08 02:38:28 +00001314 return -x;
1315}
drh81cc5162011-05-17 20:36:21 +00001316
1317#ifdef SQLITE_ENABLE_8_3_NAMES
1318/*
drhb51bf432011-07-21 21:29:35 +00001319** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
drh81cc5162011-05-17 20:36:21 +00001320** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
1321** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
1322** three characters, then shorten the suffix on z[] to be the last three
1323** characters of the original suffix.
1324**
drhb51bf432011-07-21 21:29:35 +00001325** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
1326** do the suffix shortening regardless of URI parameter.
1327**
drh81cc5162011-05-17 20:36:21 +00001328** Examples:
1329**
1330** test.db-journal => test.nal
1331** test.db-wal => test.wal
1332** test.db-shm => test.shm
drhf5808602011-12-16 00:33:04 +00001333** test.db-mj7f3319fa => test.9fa
drh81cc5162011-05-17 20:36:21 +00001334*/
1335void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
drhb51bf432011-07-21 21:29:35 +00001336#if SQLITE_ENABLE_8_3_NAMES<2
drh7d39e172012-01-02 12:41:53 +00001337 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
drhb51bf432011-07-21 21:29:35 +00001338#endif
1339 {
drh81cc5162011-05-17 20:36:21 +00001340 int i, sz;
1341 sz = sqlite3Strlen30(z);
drhc83f2d42011-05-18 02:41:10 +00001342 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
drhc02a43a2012-01-10 23:18:38 +00001343 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
drh81cc5162011-05-17 20:36:21 +00001344 }
1345}
1346#endif
drhbf539c42013-10-05 18:16:02 +00001347
1348/*
1349** Find (an approximate) sum of two LogEst values. This computation is
1350** not a simple "+" operator because LogEst is stored as a logarithmic
1351** value.
1352**
1353*/
1354LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
1355 static const unsigned char x[] = {
1356 10, 10, /* 0,1 */
1357 9, 9, /* 2,3 */
1358 8, 8, /* 4,5 */
1359 7, 7, 7, /* 6,7,8 */
1360 6, 6, 6, /* 9,10,11 */
1361 5, 5, 5, /* 12-14 */
1362 4, 4, 4, 4, /* 15-18 */
1363 3, 3, 3, 3, 3, 3, /* 19-24 */
1364 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
1365 };
1366 if( a>=b ){
1367 if( a>b+49 ) return a;
1368 if( a>b+31 ) return a+1;
1369 return a+x[a-b];
1370 }else{
1371 if( b>a+49 ) return b;
1372 if( b>a+31 ) return b+1;
1373 return b+x[b-a];
1374 }
1375}
1376
1377/*
drh224155d2014-04-30 13:19:09 +00001378** Convert an integer into a LogEst. In other words, compute an
1379** approximation for 10*log2(x).
drhbf539c42013-10-05 18:16:02 +00001380*/
1381LogEst sqlite3LogEst(u64 x){
1382 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1383 LogEst y = 40;
1384 if( x<8 ){
1385 if( x<2 ) return 0;
1386 while( x<8 ){ y -= 10; x <<= 1; }
1387 }else{
1388 while( x>255 ){ y += 40; x >>= 4; }
1389 while( x>15 ){ y += 10; x >>= 1; }
1390 }
1391 return a[x&7] + y - 10;
1392}
1393
1394#ifndef SQLITE_OMIT_VIRTUALTABLE
1395/*
1396** Convert a double into a LogEst
1397** In other words, compute an approximation for 10*log2(x).
1398*/
1399LogEst sqlite3LogEstFromDouble(double x){
1400 u64 a;
1401 LogEst e;
1402 assert( sizeof(x)==8 && sizeof(a)==8 );
1403 if( x<=1 ) return 0;
1404 if( x<=2000000000 ) return sqlite3LogEst((u64)x);
1405 memcpy(&a, &x, 8);
1406 e = (a>>52) - 1022;
1407 return e*10;
1408}
1409#endif /* SQLITE_OMIT_VIRTUALTABLE */
1410
drh14bfd992016-03-05 14:00:09 +00001411#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
drhd566c952016-02-25 21:19:03 +00001412 defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
1413 defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
drhbf539c42013-10-05 18:16:02 +00001414/*
1415** Convert a LogEst into an integer.
drhd566c952016-02-25 21:19:03 +00001416**
1417** Note that this routine is only used when one or more of various
1418** non-standard compile-time options is enabled.
drhbf539c42013-10-05 18:16:02 +00001419*/
1420u64 sqlite3LogEstToInt(LogEst x){
1421 u64 n;
1422 if( x<10 ) return 1;
1423 n = x%10;
1424 x /= 10;
1425 if( n>=5 ) n -= 2;
1426 else if( n>=1 ) n -= 1;
drh47676fe2013-12-05 16:41:55 +00001427 if( x>=3 ){
1428 return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
1429 }
drhbf539c42013-10-05 18:16:02 +00001430 return (n+8)>>(3-x);
1431}
drhd566c952016-02-25 21:19:03 +00001432#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */