blob: 928d2492157a7fb245313a55bd6d5afbb2cf718e [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/*
drh13f40da2014-08-22 18:00:11 +0000113** Set the current error code to err_code and clear any prior error message.
114*/
115void sqlite3Error(sqlite3 *db, int err_code){
116 assert( db!=0 );
117 db->errCode = err_code;
118 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
119}
120
121/*
drhc81c11f2009-11-10 01:30:52 +0000122** Set the most recent error code and error string for the sqlite
123** handle "db". The error code is set to "err_code".
124**
125** If it is not NULL, string zFormat specifies the format of the
126** error string in the style of the printf functions: The following
127** format characters are allowed:
128**
129** %s Insert a string
130** %z A string that should be freed after use
131** %d Insert an integer
132** %T Insert a token
133** %S Insert the first element of a SrcList
134**
135** zFormat and any string tokens that follow it are assumed to be
136** encoded in UTF-8.
137**
138** To clear the most recent error for sqlite handle "db", sqlite3Error
139** should be called with err_code set to SQLITE_OK and zFormat set
140** to NULL.
141*/
drh13f40da2014-08-22 18:00:11 +0000142void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
drha3cc0072013-12-13 16:23:55 +0000143 assert( db!=0 );
144 db->errCode = err_code;
drh13f40da2014-08-22 18:00:11 +0000145 if( zFormat==0 ){
146 sqlite3Error(db, err_code);
147 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
drha3cc0072013-12-13 16:23:55 +0000148 char *z;
149 va_list ap;
150 va_start(ap, zFormat);
151 z = sqlite3VMPrintf(db, zFormat, ap);
152 va_end(ap);
153 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
drhc81c11f2009-11-10 01:30:52 +0000154 }
155}
156
157/*
158** Add an error message to pParse->zErrMsg and increment pParse->nErr.
159** The following formatting characters are allowed:
160**
161** %s Insert a string
162** %z A string that should be freed after use
163** %d Insert an integer
164** %T Insert a token
165** %S Insert the first element of a SrcList
166**
drh13f40da2014-08-22 18:00:11 +0000167** This function should be used to report any error that occurs while
drhc81c11f2009-11-10 01:30:52 +0000168** compiling an SQL statement (i.e. within sqlite3_prepare()). The
169** last thing the sqlite3_prepare() function does is copy the error
170** stored by this function into the database handle using sqlite3Error().
drh13f40da2014-08-22 18:00:11 +0000171** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
172** during statement execution (sqlite3_step() etc.).
drhc81c11f2009-11-10 01:30:52 +0000173*/
174void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
drha7564662010-02-22 19:32:31 +0000175 char *zMsg;
drhc81c11f2009-11-10 01:30:52 +0000176 va_list ap;
177 sqlite3 *db = pParse->db;
drhc81c11f2009-11-10 01:30:52 +0000178 va_start(ap, zFormat);
drha7564662010-02-22 19:32:31 +0000179 zMsg = sqlite3VMPrintf(db, zFormat, ap);
drhc81c11f2009-11-10 01:30:52 +0000180 va_end(ap);
drha7564662010-02-22 19:32:31 +0000181 if( db->suppressErr ){
182 sqlite3DbFree(db, zMsg);
183 }else{
184 pParse->nErr++;
185 sqlite3DbFree(db, pParse->zErrMsg);
186 pParse->zErrMsg = zMsg;
187 pParse->rc = SQLITE_ERROR;
drha7564662010-02-22 19:32:31 +0000188 }
drhc81c11f2009-11-10 01:30:52 +0000189}
190
191/*
192** Convert an SQL-style quoted string into a normal string by removing
193** the quote characters. The conversion is done in-place. If the
194** input does not begin with a quote character, then this routine
195** is a no-op.
196**
197** The input string must be zero-terminated. A new zero-terminator
198** is added to the dequoted string.
199**
200** The return value is -1 if no dequoting occurs or the length of the
201** dequoted string, exclusive of the zero terminator, if dequoting does
202** occur.
203**
204** 2002-Feb-14: This routine is extended to remove MS-Access style
peter.d.reid60ec9142014-09-06 16:39:46 +0000205** brackets from around identifiers. For example: "[a-b-c]" becomes
drhc81c11f2009-11-10 01:30:52 +0000206** "a-b-c".
207*/
208int sqlite3Dequote(char *z){
209 char quote;
210 int i, j;
211 if( z==0 ) return -1;
212 quote = z[0];
213 switch( quote ){
214 case '\'': break;
215 case '"': break;
216 case '`': break; /* For MySQL compatibility */
217 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
218 default: return -1;
219 }
drh9ccd8652013-09-13 16:36:46 +0000220 for(i=1, j=0;; i++){
221 assert( z[i] );
drhc81c11f2009-11-10 01:30:52 +0000222 if( z[i]==quote ){
223 if( z[i+1]==quote ){
224 z[j++] = quote;
225 i++;
226 }else{
227 break;
228 }
229 }else{
230 z[j++] = z[i];
231 }
232 }
233 z[j] = 0;
234 return j;
235}
236
drh40aced52016-01-22 17:48:09 +0000237/*
238** Generate a Token object from a string
239*/
240void sqlite3TokenInit(Token *p, char *z){
241 p->z = z;
242 p->n = sqlite3Strlen30(z);
243}
244
drhc81c11f2009-11-10 01:30:52 +0000245/* Convenient short-hand */
246#define UpperToLower sqlite3UpperToLower
247
248/*
249** Some systems have stricmp(). Others have strcasecmp(). Because
250** there is no consistency, we will define our own.
drh9f129f42010-08-31 15:27:32 +0000251**
drh0299b402012-03-19 17:42:46 +0000252** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
253** sqlite3_strnicmp() APIs allow applications and extensions to compare
254** the contents of two buffers containing UTF-8 strings in a
255** case-independent fashion, using the same definition of "case
256** independence" that SQLite uses internally when comparing identifiers.
drhc81c11f2009-11-10 01:30:52 +0000257*/
drh3fa97302012-02-22 16:58:36 +0000258int sqlite3_stricmp(const char *zLeft, const char *zRight){
drh9ca95732014-10-24 00:35:58 +0000259 if( zLeft==0 ){
260 return zRight ? -1 : 0;
261 }else if( zRight==0 ){
262 return 1;
263 }
drh80738d92016-02-15 00:34:16 +0000264 return sqlite3StrICmp(zLeft, zRight);
265}
266int sqlite3StrICmp(const char *zLeft, const char *zRight){
267 unsigned char *a, *b;
268 int c;
drhc81c11f2009-11-10 01:30:52 +0000269 a = (unsigned char *)zLeft;
270 b = (unsigned char *)zRight;
drh80738d92016-02-15 00:34:16 +0000271 for(;;){
272 c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
273 if( c || *a==0 ) break;
274 a++;
275 b++;
276 }
277 return c;
drhc81c11f2009-11-10 01:30:52 +0000278}
279int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
280 register unsigned char *a, *b;
drh9ca95732014-10-24 00:35:58 +0000281 if( zLeft==0 ){
282 return zRight ? -1 : 0;
283 }else if( zRight==0 ){
284 return 1;
285 }
drhc81c11f2009-11-10 01:30:52 +0000286 a = (unsigned char *)zLeft;
287 b = (unsigned char *)zRight;
288 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
289 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
290}
291
292/*
drh9339da12010-09-30 00:50:49 +0000293** The string z[] is an text representation of a real number.
drh025586a2010-09-30 17:33:11 +0000294** Convert this string to a double and write it into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000295**
drh9339da12010-09-30 00:50:49 +0000296** The string z[] is length bytes in length (bytes, not characters) and
297** uses the encoding enc. The string is not necessarily zero-terminated.
drhc81c11f2009-11-10 01:30:52 +0000298**
drh9339da12010-09-30 00:50:49 +0000299** Return TRUE if the result is a valid real number (or integer) and FALSE
drh025586a2010-09-30 17:33:11 +0000300** if the string is empty or contains extraneous text. Valid numbers
301** are in one of these formats:
302**
303** [+-]digits[E[+-]digits]
304** [+-]digits.[digits][E[+-]digits]
305** [+-].digits[E[+-]digits]
306**
307** Leading and trailing whitespace is ignored for the purpose of determining
308** validity.
309**
310** If some prefix of the input string is a valid number, this routine
311** returns FALSE but it still converts the prefix and writes the result
312** into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000313*/
drh9339da12010-09-30 00:50:49 +0000314int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
drhc81c11f2009-11-10 01:30:52 +0000315#ifndef SQLITE_OMIT_FLOATING_POINT
drh0e5fba72013-03-20 12:04:29 +0000316 int incr;
drh9339da12010-09-30 00:50:49 +0000317 const char *zEnd = z + length;
drhc81c11f2009-11-10 01:30:52 +0000318 /* sign * significand * (10 ^ (esign * exponent)) */
drh025586a2010-09-30 17:33:11 +0000319 int sign = 1; /* sign of significand */
320 i64 s = 0; /* significand */
321 int d = 0; /* adjust exponent for shifting decimal point */
322 int esign = 1; /* sign of exponent */
323 int e = 0; /* exponent */
324 int eValid = 1; /* True exponent is either not used or is well-formed */
drhc81c11f2009-11-10 01:30:52 +0000325 double result;
326 int nDigits = 0;
drh0e5fba72013-03-20 12:04:29 +0000327 int nonNum = 0;
drhc81c11f2009-11-10 01:30:52 +0000328
drh0e5fba72013-03-20 12:04:29 +0000329 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
drh025586a2010-09-30 17:33:11 +0000330 *pResult = 0.0; /* Default return value, in case of an error */
331
drh0e5fba72013-03-20 12:04:29 +0000332 if( enc==SQLITE_UTF8 ){
333 incr = 1;
334 }else{
335 int i;
336 incr = 2;
337 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
338 for(i=3-enc; i<length && z[i]==0; i+=2){}
339 nonNum = i<length;
340 zEnd = z+i+enc-3;
341 z += (enc&1);
342 }
drh9339da12010-09-30 00:50:49 +0000343
drhc81c11f2009-11-10 01:30:52 +0000344 /* skip leading spaces */
drh9339da12010-09-30 00:50:49 +0000345 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
drh025586a2010-09-30 17:33:11 +0000346 if( z>=zEnd ) return 0;
drh9339da12010-09-30 00:50:49 +0000347
drhc81c11f2009-11-10 01:30:52 +0000348 /* get sign of significand */
349 if( *z=='-' ){
350 sign = -1;
drh9339da12010-09-30 00:50:49 +0000351 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000352 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000353 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000354 }
drh9339da12010-09-30 00:50:49 +0000355
drhc81c11f2009-11-10 01:30:52 +0000356 /* skip leading zeroes */
drh9339da12010-09-30 00:50:49 +0000357 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000358
359 /* copy max significant digits to significand */
drh9339da12010-09-30 00:50:49 +0000360 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
drhc81c11f2009-11-10 01:30:52 +0000361 s = s*10 + (*z - '0');
drh9339da12010-09-30 00:50:49 +0000362 z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000363 }
drh9339da12010-09-30 00:50:49 +0000364
drhc81c11f2009-11-10 01:30:52 +0000365 /* skip non-significant significand digits
366 ** (increase exponent by d to shift decimal left) */
drh9339da12010-09-30 00:50:49 +0000367 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
368 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000369
370 /* if decimal point is present */
371 if( *z=='.' ){
drh9339da12010-09-30 00:50:49 +0000372 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000373 /* copy digits from after decimal to significand
374 ** (decrease exponent by d to shift decimal right) */
drh9339da12010-09-30 00:50:49 +0000375 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
drhc81c11f2009-11-10 01:30:52 +0000376 s = s*10 + (*z - '0');
drh9339da12010-09-30 00:50:49 +0000377 z+=incr, nDigits++, d--;
drhc81c11f2009-11-10 01:30:52 +0000378 }
379 /* skip non-significant digits */
drh9339da12010-09-30 00:50:49 +0000380 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000381 }
drh9339da12010-09-30 00:50:49 +0000382 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000383
384 /* if exponent is present */
385 if( *z=='e' || *z=='E' ){
drh9339da12010-09-30 00:50:49 +0000386 z+=incr;
drh025586a2010-09-30 17:33:11 +0000387 eValid = 0;
drh9339da12010-09-30 00:50:49 +0000388 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000389 /* get sign of exponent */
390 if( *z=='-' ){
391 esign = -1;
drh9339da12010-09-30 00:50:49 +0000392 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000393 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000394 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000395 }
396 /* copy digits to exponent */
drh9339da12010-09-30 00:50:49 +0000397 while( z<zEnd && sqlite3Isdigit(*z) ){
drh57db4a72011-10-17 20:41:46 +0000398 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
drh9339da12010-09-30 00:50:49 +0000399 z+=incr;
drh025586a2010-09-30 17:33:11 +0000400 eValid = 1;
drhc81c11f2009-11-10 01:30:52 +0000401 }
402 }
403
drh025586a2010-09-30 17:33:11 +0000404 /* skip trailing spaces */
405 if( nDigits && eValid ){
406 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
407 }
408
drh9339da12010-09-30 00:50:49 +0000409do_atof_calc:
drhc81c11f2009-11-10 01:30:52 +0000410 /* adjust exponent by d, and update sign */
411 e = (e*esign) + d;
412 if( e<0 ) {
413 esign = -1;
414 e *= -1;
415 } else {
416 esign = 1;
417 }
418
419 /* if 0 significand */
420 if( !s ) {
421 /* In the IEEE 754 standard, zero is signed.
422 ** Add the sign if we've seen at least one digit */
423 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
424 } else {
425 /* attempt to reduce exponent */
426 if( esign>0 ){
427 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
428 }else{
429 while( !(s%10) && e>0 ) e--,s/=10;
430 }
431
432 /* adjust the sign of significand */
433 s = sign<0 ? -s : s;
434
435 /* if exponent, scale significand as appropriate
436 ** and store in result. */
437 if( e ){
drh89f15082012-06-19 00:45:16 +0000438 LONGDOUBLE_TYPE scale = 1.0;
drhc81c11f2009-11-10 01:30:52 +0000439 /* attempt to handle extremely small/large numbers better */
440 if( e>307 && e<342 ){
441 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
442 if( esign<0 ){
443 result = s / scale;
444 result /= 1.0e+308;
445 }else{
446 result = s * scale;
447 result *= 1.0e+308;
448 }
drh2458a2e2011-10-17 12:14:26 +0000449 }else if( e>=342 ){
450 if( esign<0 ){
451 result = 0.0*s;
452 }else{
453 result = 1e308*1e308*s; /* Infinity */
454 }
drhc81c11f2009-11-10 01:30:52 +0000455 }else{
456 /* 1.0e+22 is the largest power of 10 than can be
457 ** represented exactly. */
458 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
459 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
460 if( esign<0 ){
461 result = s / scale;
462 }else{
463 result = s * scale;
464 }
465 }
466 } else {
467 result = (double)s;
468 }
469 }
470
471 /* store the result */
472 *pResult = result;
473
drh025586a2010-09-30 17:33:11 +0000474 /* return true if number and no extra non-whitespace chracters after */
drh0e5fba72013-03-20 12:04:29 +0000475 return z>=zEnd && nDigits>0 && eValid && nonNum==0;
drhc81c11f2009-11-10 01:30:52 +0000476#else
shaneh5f1d6b62010-09-30 16:51:25 +0000477 return !sqlite3Atoi64(z, pResult, length, enc);
drhc81c11f2009-11-10 01:30:52 +0000478#endif /* SQLITE_OMIT_FLOATING_POINT */
479}
480
481/*
482** Compare the 19-character string zNum against the text representation
483** value 2^63: 9223372036854775808. Return negative, zero, or positive
484** if zNum is less than, equal to, or greater than the string.
shaneh5f1d6b62010-09-30 16:51:25 +0000485** Note that zNum must contain exactly 19 characters.
drhc81c11f2009-11-10 01:30:52 +0000486**
487** Unlike memcmp() this routine is guaranteed to return the difference
488** in the values of the last digit if the only difference is in the
489** last digit. So, for example,
490**
drh9339da12010-09-30 00:50:49 +0000491** compare2pow63("9223372036854775800", 1)
drhc81c11f2009-11-10 01:30:52 +0000492**
493** will return -8.
494*/
drh9339da12010-09-30 00:50:49 +0000495static int compare2pow63(const char *zNum, int incr){
496 int c = 0;
497 int i;
498 /* 012345678901234567 */
499 const char *pow63 = "922337203685477580";
500 for(i=0; c==0 && i<18; i++){
501 c = (zNum[i*incr]-pow63[i])*10;
502 }
drhc81c11f2009-11-10 01:30:52 +0000503 if( c==0 ){
drh9339da12010-09-30 00:50:49 +0000504 c = zNum[18*incr] - '8';
drh44dbca82010-01-13 04:22:20 +0000505 testcase( c==(-1) );
506 testcase( c==0 );
507 testcase( c==(+1) );
drhc81c11f2009-11-10 01:30:52 +0000508 }
509 return c;
510}
511
drhc81c11f2009-11-10 01:30:52 +0000512/*
drh9296c182014-07-23 13:40:49 +0000513** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
514** routine does *not* accept hexadecimal notation.
drh158b9cb2011-03-05 20:59:46 +0000515**
516** If the zNum value is representable as a 64-bit twos-complement
517** integer, then write that value into *pNum and return 0.
518**
drha256c1a2013-12-01 01:18:29 +0000519** If zNum is exactly 9223372036854775808, return 2. This special
520** case is broken out because while 9223372036854775808 cannot be a
521** signed 64-bit integer, its negative -9223372036854775808 can be.
drh158b9cb2011-03-05 20:59:46 +0000522**
523** If zNum is too big for a 64-bit integer and is not
drha256c1a2013-12-01 01:18:29 +0000524** 9223372036854775808 or if zNum contains any non-numeric text,
drh0e5fba72013-03-20 12:04:29 +0000525** then return 1.
drhc81c11f2009-11-10 01:30:52 +0000526**
drh9339da12010-09-30 00:50:49 +0000527** length is the number of bytes in the string (bytes, not characters).
528** The string is not necessarily zero-terminated. The encoding is
529** given by enc.
drhc81c11f2009-11-10 01:30:52 +0000530*/
drh9339da12010-09-30 00:50:49 +0000531int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
drh0e5fba72013-03-20 12:04:29 +0000532 int incr;
drh158b9cb2011-03-05 20:59:46 +0000533 u64 u = 0;
shaneh5f1d6b62010-09-30 16:51:25 +0000534 int neg = 0; /* assume positive */
drh9339da12010-09-30 00:50:49 +0000535 int i;
536 int c = 0;
drh0e5fba72013-03-20 12:04:29 +0000537 int nonNum = 0;
drhc81c11f2009-11-10 01:30:52 +0000538 const char *zStart;
drh9339da12010-09-30 00:50:49 +0000539 const char *zEnd = zNum + length;
drh0e5fba72013-03-20 12:04:29 +0000540 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
541 if( enc==SQLITE_UTF8 ){
542 incr = 1;
543 }else{
544 incr = 2;
545 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
546 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
547 nonNum = i<length;
548 zEnd = zNum+i+enc-3;
549 zNum += (enc&1);
550 }
drh9339da12010-09-30 00:50:49 +0000551 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
drh158b9cb2011-03-05 20:59:46 +0000552 if( zNum<zEnd ){
553 if( *zNum=='-' ){
554 neg = 1;
555 zNum+=incr;
556 }else if( *zNum=='+' ){
557 zNum+=incr;
558 }
drhc81c11f2009-11-10 01:30:52 +0000559 }
560 zStart = zNum;
drh9339da12010-09-30 00:50:49 +0000561 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
562 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
drh158b9cb2011-03-05 20:59:46 +0000563 u = u*10 + c - '0';
drhc81c11f2009-11-10 01:30:52 +0000564 }
drh158b9cb2011-03-05 20:59:46 +0000565 if( u>LARGEST_INT64 ){
drhde1a8b82013-11-26 15:45:02 +0000566 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
drh158b9cb2011-03-05 20:59:46 +0000567 }else if( neg ){
568 *pNum = -(i64)u;
569 }else{
570 *pNum = (i64)u;
571 }
drh44dbca82010-01-13 04:22:20 +0000572 testcase( i==18 );
573 testcase( i==19 );
574 testcase( i==20 );
drh62aaa6c2015-11-21 17:27:42 +0000575 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum)
576 || i>19*incr || nonNum ){
drhc81c11f2009-11-10 01:30:52 +0000577 /* zNum is empty or contains non-numeric text or is longer
shaneh5f1d6b62010-09-30 16:51:25 +0000578 ** than 19 digits (thus guaranteeing that it is too large) */
579 return 1;
drh9339da12010-09-30 00:50:49 +0000580 }else if( i<19*incr ){
drhc81c11f2009-11-10 01:30:52 +0000581 /* Less than 19 digits, so we know that it fits in 64 bits */
drh158b9cb2011-03-05 20:59:46 +0000582 assert( u<=LARGEST_INT64 );
shaneh5f1d6b62010-09-30 16:51:25 +0000583 return 0;
drhc81c11f2009-11-10 01:30:52 +0000584 }else{
drh158b9cb2011-03-05 20:59:46 +0000585 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
586 c = compare2pow63(zNum, incr);
587 if( c<0 ){
588 /* zNum is less than 9223372036854775808 so it fits */
589 assert( u<=LARGEST_INT64 );
590 return 0;
591 }else if( c>0 ){
592 /* zNum is greater than 9223372036854775808 so it overflows */
593 return 1;
594 }else{
595 /* zNum is exactly 9223372036854775808. Fits if negative. The
596 ** special case 2 overflow if positive */
597 assert( u-1==LARGEST_INT64 );
drh158b9cb2011-03-05 20:59:46 +0000598 return neg ? 0 : 2;
599 }
drhc81c11f2009-11-10 01:30:52 +0000600 }
601}
602
603/*
drh9296c182014-07-23 13:40:49 +0000604** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
605** into a 64-bit signed integer. This routine accepts hexadecimal literals,
606** whereas sqlite3Atoi64() does not.
607**
608** Returns:
609**
610** 0 Successful transformation. Fits in a 64-bit signed integer.
611** 1 Integer too large for a 64-bit signed integer or is malformed
612** 2 Special case of 9223372036854775808
613*/
614int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
615#ifndef SQLITE_OMIT_HEX_INTEGER
616 if( z[0]=='0'
617 && (z[1]=='x' || z[1]=='X')
618 && sqlite3Isxdigit(z[2])
619 ){
620 u64 u = 0;
621 int i, k;
622 for(i=2; z[i]=='0'; i++){}
623 for(k=i; sqlite3Isxdigit(z[k]); k++){
624 u = u*16 + sqlite3HexToInt(z[k]);
625 }
626 memcpy(pOut, &u, 8);
627 return (z[k]==0 && k-i<=16) ? 0 : 1;
628 }else
629#endif /* SQLITE_OMIT_HEX_INTEGER */
630 {
631 return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
632 }
633}
634
635/*
drhc81c11f2009-11-10 01:30:52 +0000636** If zNum represents an integer that will fit in 32-bits, then set
637** *pValue to that integer and return true. Otherwise return false.
638**
drh9296c182014-07-23 13:40:49 +0000639** This routine accepts both decimal and hexadecimal notation for integers.
640**
drhc81c11f2009-11-10 01:30:52 +0000641** Any non-numeric characters that following zNum are ignored.
642** This is different from sqlite3Atoi64() which requires the
643** input number to be zero-terminated.
644*/
645int sqlite3GetInt32(const char *zNum, int *pValue){
646 sqlite_int64 v = 0;
647 int i, c;
648 int neg = 0;
649 if( zNum[0]=='-' ){
650 neg = 1;
651 zNum++;
652 }else if( zNum[0]=='+' ){
653 zNum++;
654 }
drh28e048c2014-07-23 01:26:51 +0000655#ifndef SQLITE_OMIT_HEX_INTEGER
656 else if( zNum[0]=='0'
657 && (zNum[1]=='x' || zNum[1]=='X')
658 && sqlite3Isxdigit(zNum[2])
659 ){
660 u32 u = 0;
661 zNum += 2;
662 while( zNum[0]=='0' ) zNum++;
663 for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
664 u = u*16 + sqlite3HexToInt(zNum[i]);
665 }
666 if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
667 memcpy(pValue, &u, 4);
668 return 1;
669 }else{
670 return 0;
671 }
672 }
673#endif
drh935f2e72015-04-18 04:45:00 +0000674 while( zNum[0]=='0' ) zNum++;
drhc81c11f2009-11-10 01:30:52 +0000675 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
676 v = v*10 + c;
677 }
678
679 /* The longest decimal representation of a 32 bit integer is 10 digits:
680 **
681 ** 1234567890
682 ** 2^31 -> 2147483648
683 */
drh44dbca82010-01-13 04:22:20 +0000684 testcase( i==10 );
drhc81c11f2009-11-10 01:30:52 +0000685 if( i>10 ){
686 return 0;
687 }
drh44dbca82010-01-13 04:22:20 +0000688 testcase( v-neg==2147483647 );
drhc81c11f2009-11-10 01:30:52 +0000689 if( v-neg>2147483647 ){
690 return 0;
691 }
692 if( neg ){
693 v = -v;
694 }
695 *pValue = (int)v;
696 return 1;
697}
698
699/*
drh60ac3f42010-11-23 18:59:27 +0000700** Return a 32-bit integer value extracted from a string. If the
701** string is not an integer, just return 0.
702*/
703int sqlite3Atoi(const char *z){
704 int x = 0;
705 if( z ) sqlite3GetInt32(z, &x);
706 return x;
707}
708
709/*
drhc81c11f2009-11-10 01:30:52 +0000710** The variable-length integer encoding is as follows:
711**
712** KEY:
713** A = 0xxxxxxx 7 bits of data and one flag bit
714** B = 1xxxxxxx 7 bits of data and one flag bit
715** C = xxxxxxxx 8 bits of data
716**
717** 7 bits - A
718** 14 bits - BA
719** 21 bits - BBA
720** 28 bits - BBBA
721** 35 bits - BBBBA
722** 42 bits - BBBBBA
723** 49 bits - BBBBBBA
724** 56 bits - BBBBBBBA
725** 64 bits - BBBBBBBBC
726*/
727
728/*
729** Write a 64-bit variable-length integer to memory starting at p[0].
730** The length of data write will be between 1 and 9 bytes. The number
731** of bytes written is returned.
732**
733** A variable-length integer consists of the lower 7 bits of each byte
734** for all bytes that have the 8th bit set and one byte with the 8th
735** bit clear. Except, if we get to the 9th byte, it stores the full
736** 8 bits and is the last byte.
737*/
drh2f2b2b82014-08-22 18:48:25 +0000738static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
drhc81c11f2009-11-10 01:30:52 +0000739 int i, j, n;
740 u8 buf[10];
741 if( v & (((u64)0xff000000)<<32) ){
742 p[8] = (u8)v;
743 v >>= 8;
744 for(i=7; i>=0; i--){
745 p[i] = (u8)((v & 0x7f) | 0x80);
746 v >>= 7;
747 }
748 return 9;
749 }
750 n = 0;
751 do{
752 buf[n++] = (u8)((v & 0x7f) | 0x80);
753 v >>= 7;
754 }while( v!=0 );
755 buf[0] &= 0x7f;
756 assert( n<=9 );
757 for(i=0, j=n-1; j>=0; j--, i++){
758 p[i] = buf[j];
759 }
760 return n;
761}
drh2f2b2b82014-08-22 18:48:25 +0000762int sqlite3PutVarint(unsigned char *p, u64 v){
763 if( v<=0x7f ){
764 p[0] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000765 return 1;
766 }
drh2f2b2b82014-08-22 18:48:25 +0000767 if( v<=0x3fff ){
768 p[0] = ((v>>7)&0x7f)|0x80;
769 p[1] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000770 return 2;
771 }
drh2f2b2b82014-08-22 18:48:25 +0000772 return putVarint64(p,v);
drhc81c11f2009-11-10 01:30:52 +0000773}
774
775/*
drh0b2864c2010-03-03 15:18:38 +0000776** Bitmasks used by sqlite3GetVarint(). These precomputed constants
777** are defined here rather than simply putting the constant expressions
778** inline in order to work around bugs in the RVT compiler.
779**
780** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
781**
782** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
783*/
784#define SLOT_2_0 0x001fc07f
785#define SLOT_4_2_0 0xf01fc07f
786
787
788/*
drhc81c11f2009-11-10 01:30:52 +0000789** Read a 64-bit variable-length integer from memory starting at p[0].
790** Return the number of bytes read. The value is stored in *v.
791*/
792u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
793 u32 a,b,s;
794
795 a = *p;
796 /* a: p0 (unmasked) */
797 if (!(a&0x80))
798 {
799 *v = a;
800 return 1;
801 }
802
803 p++;
804 b = *p;
805 /* b: p1 (unmasked) */
806 if (!(b&0x80))
807 {
808 a &= 0x7f;
809 a = a<<7;
810 a |= b;
811 *v = a;
812 return 2;
813 }
814
drh0b2864c2010-03-03 15:18:38 +0000815 /* Verify that constants are precomputed correctly */
816 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
shaneh1da207e2010-03-09 14:41:12 +0000817 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
drh0b2864c2010-03-03 15:18:38 +0000818
drhc81c11f2009-11-10 01:30:52 +0000819 p++;
820 a = a<<14;
821 a |= *p;
822 /* a: p0<<14 | p2 (unmasked) */
823 if (!(a&0x80))
824 {
drh0b2864c2010-03-03 15:18:38 +0000825 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000826 b &= 0x7f;
827 b = b<<7;
828 a |= b;
829 *v = a;
830 return 3;
831 }
832
833 /* CSE1 from below */
drh0b2864c2010-03-03 15:18:38 +0000834 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000835 p++;
836 b = b<<14;
837 b |= *p;
838 /* b: p1<<14 | p3 (unmasked) */
839 if (!(b&0x80))
840 {
drh0b2864c2010-03-03 15:18:38 +0000841 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000842 /* moved CSE1 up */
843 /* a &= (0x7f<<14)|(0x7f); */
844 a = a<<7;
845 a |= b;
846 *v = a;
847 return 4;
848 }
849
850 /* a: p0<<14 | p2 (masked) */
851 /* b: p1<<14 | p3 (unmasked) */
852 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
853 /* moved CSE1 up */
854 /* a &= (0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +0000855 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000856 s = a;
857 /* s: p0<<14 | p2 (masked) */
858
859 p++;
860 a = a<<14;
861 a |= *p;
862 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
863 if (!(a&0x80))
864 {
drh62aaa6c2015-11-21 17:27:42 +0000865 /* we can skip these cause they were (effectively) done above
866 ** while calculating s */
drhc81c11f2009-11-10 01:30:52 +0000867 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
868 /* b &= (0x7f<<14)|(0x7f); */
869 b = b<<7;
870 a |= b;
871 s = s>>18;
872 *v = ((u64)s)<<32 | a;
873 return 5;
874 }
875
876 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
877 s = s<<7;
878 s |= b;
879 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
880
881 p++;
882 b = b<<14;
883 b |= *p;
884 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
885 if (!(b&0x80))
886 {
887 /* we can skip this cause it was (effectively) done above in calc'ing s */
888 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +0000889 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000890 a = a<<7;
891 a |= b;
892 s = s>>18;
893 *v = ((u64)s)<<32 | a;
894 return 6;
895 }
896
897 p++;
898 a = a<<14;
899 a |= *p;
900 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
901 if (!(a&0x80))
902 {
drh0b2864c2010-03-03 15:18:38 +0000903 a &= SLOT_4_2_0;
904 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000905 b = b<<7;
906 a |= b;
907 s = s>>11;
908 *v = ((u64)s)<<32 | a;
909 return 7;
910 }
911
912 /* CSE2 from below */
drh0b2864c2010-03-03 15:18:38 +0000913 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000914 p++;
915 b = b<<14;
916 b |= *p;
917 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
918 if (!(b&0x80))
919 {
drh0b2864c2010-03-03 15:18:38 +0000920 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +0000921 /* moved CSE2 up */
922 /* a &= (0x7f<<14)|(0x7f); */
923 a = a<<7;
924 a |= b;
925 s = s>>4;
926 *v = ((u64)s)<<32 | a;
927 return 8;
928 }
929
930 p++;
931 a = a<<15;
932 a |= *p;
933 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
934
935 /* moved CSE2 up */
936 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
drh0b2864c2010-03-03 15:18:38 +0000937 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000938 b = b<<8;
939 a |= b;
940
941 s = s<<4;
942 b = p[-4];
943 b &= 0x7f;
944 b = b>>3;
945 s |= b;
946
947 *v = ((u64)s)<<32 | a;
948
949 return 9;
950}
951
952/*
953** Read a 32-bit variable-length integer from memory starting at p[0].
954** Return the number of bytes read. The value is stored in *v.
955**
956** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
957** integer, then set *v to 0xffffffff.
958**
959** A MACRO version, getVarint32, is provided which inlines the
960** single-byte case. All code should use the MACRO version as
961** this function assumes the single-byte case has already been handled.
962*/
963u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
964 u32 a,b;
965
966 /* The 1-byte case. Overwhelmingly the most common. Handled inline
967 ** by the getVarin32() macro */
968 a = *p;
969 /* a: p0 (unmasked) */
970#ifndef getVarint32
971 if (!(a&0x80))
972 {
973 /* Values between 0 and 127 */
974 *v = a;
975 return 1;
976 }
977#endif
978
979 /* The 2-byte case */
980 p++;
981 b = *p;
982 /* b: p1 (unmasked) */
983 if (!(b&0x80))
984 {
985 /* Values between 128 and 16383 */
986 a &= 0x7f;
987 a = a<<7;
988 *v = a | b;
989 return 2;
990 }
991
992 /* The 3-byte case */
993 p++;
994 a = a<<14;
995 a |= *p;
996 /* a: p0<<14 | p2 (unmasked) */
997 if (!(a&0x80))
998 {
999 /* Values between 16384 and 2097151 */
1000 a &= (0x7f<<14)|(0x7f);
1001 b &= 0x7f;
1002 b = b<<7;
1003 *v = a | b;
1004 return 3;
1005 }
1006
1007 /* A 32-bit varint is used to store size information in btrees.
1008 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
1009 ** A 3-byte varint is sufficient, for example, to record the size
1010 ** of a 1048569-byte BLOB or string.
1011 **
1012 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
1013 ** rare larger cases can be handled by the slower 64-bit varint
1014 ** routine.
1015 */
1016#if 1
1017 {
1018 u64 v64;
1019 u8 n;
1020
1021 p -= 2;
1022 n = sqlite3GetVarint(p, &v64);
1023 assert( n>3 && n<=9 );
1024 if( (v64 & SQLITE_MAX_U32)!=v64 ){
1025 *v = 0xffffffff;
1026 }else{
1027 *v = (u32)v64;
1028 }
1029 return n;
1030 }
1031
1032#else
1033 /* For following code (kept for historical record only) shows an
1034 ** unrolling for the 3- and 4-byte varint cases. This code is
1035 ** slightly faster, but it is also larger and much harder to test.
1036 */
1037 p++;
1038 b = b<<14;
1039 b |= *p;
1040 /* b: p1<<14 | p3 (unmasked) */
1041 if (!(b&0x80))
1042 {
1043 /* Values between 2097152 and 268435455 */
1044 b &= (0x7f<<14)|(0x7f);
1045 a &= (0x7f<<14)|(0x7f);
1046 a = a<<7;
1047 *v = a | b;
1048 return 4;
1049 }
1050
1051 p++;
1052 a = a<<14;
1053 a |= *p;
1054 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1055 if (!(a&0x80))
1056 {
dan3bbe7612010-03-03 16:02:05 +00001057 /* Values between 268435456 and 34359738367 */
1058 a &= SLOT_4_2_0;
1059 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +00001060 b = b<<7;
1061 *v = a | b;
1062 return 5;
1063 }
1064
1065 /* We can only reach this point when reading a corrupt database
1066 ** file. In that case we are not in any hurry. Use the (relatively
1067 ** slow) general-purpose sqlite3GetVarint() routine to extract the
1068 ** value. */
1069 {
1070 u64 v64;
1071 u8 n;
1072
1073 p -= 4;
1074 n = sqlite3GetVarint(p, &v64);
1075 assert( n>5 && n<=9 );
1076 *v = (u32)v64;
1077 return n;
1078 }
1079#endif
1080}
1081
1082/*
1083** Return the number of bytes that will be needed to store the given
1084** 64-bit integer.
1085*/
1086int sqlite3VarintLen(u64 v){
drh59a53642015-09-01 22:29:07 +00001087 int i;
1088 for(i=1; (v >>= 7)!=0; i++){ assert( i<9 ); }
drhc81c11f2009-11-10 01:30:52 +00001089 return i;
1090}
1091
1092
1093/*
1094** Read or write a four-byte big-endian integer value.
1095*/
1096u32 sqlite3Get4byte(const u8 *p){
drh5372e4d2015-06-30 12:47:09 +00001097#if SQLITE_BYTEORDER==4321
1098 u32 x;
1099 memcpy(&x,p,4);
1100 return x;
mistachkin60e08072015-07-29 21:47:39 +00001101#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1102 && defined(__GNUC__) && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:09 +00001103 u32 x;
1104 memcpy(&x,p,4);
1105 return __builtin_bswap32(x);
mistachkin60e08072015-07-29 21:47:39 +00001106#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1107 && defined(_MSC_VER) && _MSC_VER>=1300
mistachkin647ca462015-06-30 17:28:40 +00001108 u32 x;
1109 memcpy(&x,p,4);
1110 return _byteswap_ulong(x);
drh5372e4d2015-06-30 12:47:09 +00001111#else
drh693e6712014-01-24 22:58:00 +00001112 testcase( p[0]&0x80 );
1113 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
drh5372e4d2015-06-30 12:47:09 +00001114#endif
drhc81c11f2009-11-10 01:30:52 +00001115}
1116void sqlite3Put4byte(unsigned char *p, u32 v){
drh5372e4d2015-06-30 12:47:09 +00001117#if SQLITE_BYTEORDER==4321
1118 memcpy(p,&v,4);
mistachkinf156c9b2015-07-03 17:54:49 +00001119#elif SQLITE_BYTEORDER==1234 && defined(__GNUC__) && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:09 +00001120 u32 x = __builtin_bswap32(v);
1121 memcpy(p,&x,4);
mistachkin647ca462015-06-30 17:28:40 +00001122#elif SQLITE_BYTEORDER==1234 && defined(_MSC_VER) && _MSC_VER>=1300
1123 u32 x = _byteswap_ulong(v);
1124 memcpy(p,&x,4);
drh5372e4d2015-06-30 12:47:09 +00001125#else
drhc81c11f2009-11-10 01:30:52 +00001126 p[0] = (u8)(v>>24);
1127 p[1] = (u8)(v>>16);
1128 p[2] = (u8)(v>>8);
1129 p[3] = (u8)v;
drh5372e4d2015-06-30 12:47:09 +00001130#endif
drhc81c11f2009-11-10 01:30:52 +00001131}
1132
drh9296c182014-07-23 13:40:49 +00001133
1134
1135/*
1136** Translate a single byte of Hex into an integer.
1137** This routine only works if h really is a valid hexadecimal
1138** character: 0..9a..fA..F
1139*/
1140u8 sqlite3HexToInt(int h){
1141 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
1142#ifdef SQLITE_ASCII
1143 h += 9*(1&(h>>6));
1144#endif
1145#ifdef SQLITE_EBCDIC
1146 h += 9*(1&~(h>>4));
1147#endif
1148 return (u8)(h & 0xf);
1149}
1150
drhc81c11f2009-11-10 01:30:52 +00001151#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
1152/*
1153** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
1154** value. Return a pointer to its binary value. Space to hold the
1155** binary value has been obtained from malloc and must be freed by
1156** the calling routine.
1157*/
1158void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
1159 char *zBlob;
1160 int i;
1161
drh575fad62016-02-05 13:38:36 +00001162 zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
drhc81c11f2009-11-10 01:30:52 +00001163 n--;
1164 if( zBlob ){
1165 for(i=0; i<n; i+=2){
dancd74b612011-04-22 19:37:32 +00001166 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
drhc81c11f2009-11-10 01:30:52 +00001167 }
1168 zBlob[i/2] = 0;
1169 }
1170 return zBlob;
1171}
1172#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
1173
drh413c3d32010-02-23 20:11:56 +00001174/*
1175** Log an error that is an API call on a connection pointer that should
1176** not have been used. The "type" of connection pointer is given as the
1177** argument. The zType is a word like "NULL" or "closed" or "invalid".
1178*/
1179static void logBadConnection(const char *zType){
1180 sqlite3_log(SQLITE_MISUSE,
1181 "API call with %s database connection pointer",
1182 zType
1183 );
1184}
drhc81c11f2009-11-10 01:30:52 +00001185
1186/*
drhc81c11f2009-11-10 01:30:52 +00001187** Check to make sure we have a valid db pointer. This test is not
1188** foolproof but it does provide some measure of protection against
1189** misuse of the interface such as passing in db pointers that are
1190** NULL or which have been previously closed. If this routine returns
1191** 1 it means that the db pointer is valid and 0 if it should not be
1192** dereferenced for any reason. The calling function should invoke
1193** SQLITE_MISUSE immediately.
1194**
1195** sqlite3SafetyCheckOk() requires that the db pointer be valid for
1196** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
1197** open properly and is not fit for general use but which can be
1198** used as an argument to sqlite3_errmsg() or sqlite3_close().
1199*/
1200int sqlite3SafetyCheckOk(sqlite3 *db){
1201 u32 magic;
drh413c3d32010-02-23 20:11:56 +00001202 if( db==0 ){
1203 logBadConnection("NULL");
1204 return 0;
1205 }
drhc81c11f2009-11-10 01:30:52 +00001206 magic = db->magic;
drh9978c972010-02-23 17:36:32 +00001207 if( magic!=SQLITE_MAGIC_OPEN ){
drhe294da02010-02-25 23:44:15 +00001208 if( sqlite3SafetyCheckSickOrOk(db) ){
1209 testcase( sqlite3GlobalConfig.xLog!=0 );
drh413c3d32010-02-23 20:11:56 +00001210 logBadConnection("unopened");
1211 }
drhc81c11f2009-11-10 01:30:52 +00001212 return 0;
1213 }else{
1214 return 1;
1215 }
1216}
1217int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
1218 u32 magic;
1219 magic = db->magic;
1220 if( magic!=SQLITE_MAGIC_SICK &&
1221 magic!=SQLITE_MAGIC_OPEN &&
drh413c3d32010-02-23 20:11:56 +00001222 magic!=SQLITE_MAGIC_BUSY ){
drhe294da02010-02-25 23:44:15 +00001223 testcase( sqlite3GlobalConfig.xLog!=0 );
drhaf46dc12010-02-24 21:44:07 +00001224 logBadConnection("invalid");
drh413c3d32010-02-23 20:11:56 +00001225 return 0;
1226 }else{
1227 return 1;
1228 }
drhc81c11f2009-11-10 01:30:52 +00001229}
drh158b9cb2011-03-05 20:59:46 +00001230
1231/*
1232** Attempt to add, substract, or multiply the 64-bit signed value iB against
1233** the other 64-bit signed integer at *pA and store the result in *pA.
1234** Return 0 on success. Or if the operation would have resulted in an
1235** overflow, leave *pA unchanged and return 1.
1236*/
1237int sqlite3AddInt64(i64 *pA, i64 iB){
1238 i64 iA = *pA;
1239 testcase( iA==0 ); testcase( iA==1 );
1240 testcase( iB==-1 ); testcase( iB==0 );
1241 if( iB>=0 ){
1242 testcase( iA>0 && LARGEST_INT64 - iA == iB );
1243 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
1244 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001245 }else{
1246 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
1247 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
1248 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001249 }
drh53a6eb32014-02-10 12:59:15 +00001250 *pA += iB;
drh158b9cb2011-03-05 20:59:46 +00001251 return 0;
1252}
1253int sqlite3SubInt64(i64 *pA, i64 iB){
1254 testcase( iB==SMALLEST_INT64+1 );
1255 if( iB==SMALLEST_INT64 ){
1256 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
1257 if( (*pA)>=0 ) return 1;
1258 *pA -= iB;
1259 return 0;
1260 }else{
1261 return sqlite3AddInt64(pA, -iB);
1262 }
1263}
1264#define TWOPOWER32 (((i64)1)<<32)
1265#define TWOPOWER31 (((i64)1)<<31)
1266int sqlite3MulInt64(i64 *pA, i64 iB){
1267 i64 iA = *pA;
1268 i64 iA1, iA0, iB1, iB0, r;
1269
drh158b9cb2011-03-05 20:59:46 +00001270 iA1 = iA/TWOPOWER32;
1271 iA0 = iA % TWOPOWER32;
1272 iB1 = iB/TWOPOWER32;
1273 iB0 = iB % TWOPOWER32;
drh53a6eb32014-02-10 12:59:15 +00001274 if( iA1==0 ){
1275 if( iB1==0 ){
1276 *pA *= iB;
1277 return 0;
1278 }
1279 r = iA0*iB1;
1280 }else if( iB1==0 ){
1281 r = iA1*iB0;
1282 }else{
1283 /* If both iA1 and iB1 are non-zero, overflow will result */
1284 return 1;
1285 }
drh158b9cb2011-03-05 20:59:46 +00001286 testcase( r==(-TWOPOWER31)-1 );
1287 testcase( r==(-TWOPOWER31) );
1288 testcase( r==TWOPOWER31 );
1289 testcase( r==TWOPOWER31-1 );
1290 if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
1291 r *= TWOPOWER32;
1292 if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
1293 *pA = r;
1294 return 0;
1295}
drhd50ffc42011-03-08 02:38:28 +00001296
1297/*
1298** Compute the absolute value of a 32-bit signed integer, of possible. Or
1299** if the integer has a value of -2147483648, return +2147483647
1300*/
1301int sqlite3AbsInt32(int x){
1302 if( x>=0 ) return x;
drh87e79ae2011-03-08 13:06:41 +00001303 if( x==(int)0x80000000 ) return 0x7fffffff;
drhd50ffc42011-03-08 02:38:28 +00001304 return -x;
1305}
drh81cc5162011-05-17 20:36:21 +00001306
1307#ifdef SQLITE_ENABLE_8_3_NAMES
1308/*
drhb51bf432011-07-21 21:29:35 +00001309** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
drh81cc5162011-05-17 20:36:21 +00001310** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
1311** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
1312** three characters, then shorten the suffix on z[] to be the last three
1313** characters of the original suffix.
1314**
drhb51bf432011-07-21 21:29:35 +00001315** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
1316** do the suffix shortening regardless of URI parameter.
1317**
drh81cc5162011-05-17 20:36:21 +00001318** Examples:
1319**
1320** test.db-journal => test.nal
1321** test.db-wal => test.wal
1322** test.db-shm => test.shm
drhf5808602011-12-16 00:33:04 +00001323** test.db-mj7f3319fa => test.9fa
drh81cc5162011-05-17 20:36:21 +00001324*/
1325void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
drhb51bf432011-07-21 21:29:35 +00001326#if SQLITE_ENABLE_8_3_NAMES<2
drh7d39e172012-01-02 12:41:53 +00001327 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
drhb51bf432011-07-21 21:29:35 +00001328#endif
1329 {
drh81cc5162011-05-17 20:36:21 +00001330 int i, sz;
1331 sz = sqlite3Strlen30(z);
drhc83f2d42011-05-18 02:41:10 +00001332 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
drhc02a43a2012-01-10 23:18:38 +00001333 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
drh81cc5162011-05-17 20:36:21 +00001334 }
1335}
1336#endif
drhbf539c42013-10-05 18:16:02 +00001337
1338/*
1339** Find (an approximate) sum of two LogEst values. This computation is
1340** not a simple "+" operator because LogEst is stored as a logarithmic
1341** value.
1342**
1343*/
1344LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
1345 static const unsigned char x[] = {
1346 10, 10, /* 0,1 */
1347 9, 9, /* 2,3 */
1348 8, 8, /* 4,5 */
1349 7, 7, 7, /* 6,7,8 */
1350 6, 6, 6, /* 9,10,11 */
1351 5, 5, 5, /* 12-14 */
1352 4, 4, 4, 4, /* 15-18 */
1353 3, 3, 3, 3, 3, 3, /* 19-24 */
1354 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
1355 };
1356 if( a>=b ){
1357 if( a>b+49 ) return a;
1358 if( a>b+31 ) return a+1;
1359 return a+x[a-b];
1360 }else{
1361 if( b>a+49 ) return b;
1362 if( b>a+31 ) return b+1;
1363 return b+x[b-a];
1364 }
1365}
1366
1367/*
drh224155d2014-04-30 13:19:09 +00001368** Convert an integer into a LogEst. In other words, compute an
1369** approximation for 10*log2(x).
drhbf539c42013-10-05 18:16:02 +00001370*/
1371LogEst sqlite3LogEst(u64 x){
1372 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1373 LogEst y = 40;
1374 if( x<8 ){
1375 if( x<2 ) return 0;
1376 while( x<8 ){ y -= 10; x <<= 1; }
1377 }else{
1378 while( x>255 ){ y += 40; x >>= 4; }
1379 while( x>15 ){ y += 10; x >>= 1; }
1380 }
1381 return a[x&7] + y - 10;
1382}
1383
1384#ifndef SQLITE_OMIT_VIRTUALTABLE
1385/*
1386** Convert a double into a LogEst
1387** In other words, compute an approximation for 10*log2(x).
1388*/
1389LogEst sqlite3LogEstFromDouble(double x){
1390 u64 a;
1391 LogEst e;
1392 assert( sizeof(x)==8 && sizeof(a)==8 );
1393 if( x<=1 ) return 0;
1394 if( x<=2000000000 ) return sqlite3LogEst((u64)x);
1395 memcpy(&a, &x, 8);
1396 e = (a>>52) - 1022;
1397 return e*10;
1398}
1399#endif /* SQLITE_OMIT_VIRTUALTABLE */
1400
1401/*
1402** Convert a LogEst into an integer.
1403*/
1404u64 sqlite3LogEstToInt(LogEst x){
1405 u64 n;
1406 if( x<10 ) return 1;
1407 n = x%10;
1408 x /= 10;
1409 if( n>=5 ) n -= 2;
1410 else if( n>=1 ) n -= 1;
drh47676fe2013-12-05 16:41:55 +00001411 if( x>=3 ){
1412 return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
1413 }
drhbf539c42013-10-05 18:16:02 +00001414 return (n+8)>>(3-x);
1415}