blob: f218bb7941781a69c89f72908314523271efe09d [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
237/* Convenient short-hand */
238#define UpperToLower sqlite3UpperToLower
239
240/*
241** Some systems have stricmp(). Others have strcasecmp(). Because
242** there is no consistency, we will define our own.
drh9f129f42010-08-31 15:27:32 +0000243**
drh0299b402012-03-19 17:42:46 +0000244** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
245** sqlite3_strnicmp() APIs allow applications and extensions to compare
246** the contents of two buffers containing UTF-8 strings in a
247** case-independent fashion, using the same definition of "case
248** independence" that SQLite uses internally when comparing identifiers.
drhc81c11f2009-11-10 01:30:52 +0000249*/
drh3fa97302012-02-22 16:58:36 +0000250int sqlite3_stricmp(const char *zLeft, const char *zRight){
drhc81c11f2009-11-10 01:30:52 +0000251 register unsigned char *a, *b;
drh9ca95732014-10-24 00:35:58 +0000252 if( zLeft==0 ){
253 return zRight ? -1 : 0;
254 }else if( zRight==0 ){
255 return 1;
256 }
drhc81c11f2009-11-10 01:30:52 +0000257 a = (unsigned char *)zLeft;
258 b = (unsigned char *)zRight;
259 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
260 return UpperToLower[*a] - UpperToLower[*b];
261}
262int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
263 register unsigned char *a, *b;
drh9ca95732014-10-24 00:35:58 +0000264 if( zLeft==0 ){
265 return zRight ? -1 : 0;
266 }else if( zRight==0 ){
267 return 1;
268 }
drhc81c11f2009-11-10 01:30:52 +0000269 a = (unsigned char *)zLeft;
270 b = (unsigned char *)zRight;
271 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
272 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
273}
274
275/*
drh9339da12010-09-30 00:50:49 +0000276** The string z[] is an text representation of a real number.
drh025586a2010-09-30 17:33:11 +0000277** Convert this string to a double and write it into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000278**
drh9339da12010-09-30 00:50:49 +0000279** The string z[] is length bytes in length (bytes, not characters) and
280** uses the encoding enc. The string is not necessarily zero-terminated.
drhc81c11f2009-11-10 01:30:52 +0000281**
drh9339da12010-09-30 00:50:49 +0000282** Return TRUE if the result is a valid real number (or integer) and FALSE
drh025586a2010-09-30 17:33:11 +0000283** if the string is empty or contains extraneous text. Valid numbers
284** are in one of these formats:
285**
286** [+-]digits[E[+-]digits]
287** [+-]digits.[digits][E[+-]digits]
288** [+-].digits[E[+-]digits]
289**
290** Leading and trailing whitespace is ignored for the purpose of determining
291** validity.
292**
293** If some prefix of the input string is a valid number, this routine
294** returns FALSE but it still converts the prefix and writes the result
295** into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000296*/
drh9339da12010-09-30 00:50:49 +0000297int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
drhc81c11f2009-11-10 01:30:52 +0000298#ifndef SQLITE_OMIT_FLOATING_POINT
drh0e5fba72013-03-20 12:04:29 +0000299 int incr;
drh9339da12010-09-30 00:50:49 +0000300 const char *zEnd = z + length;
drhc81c11f2009-11-10 01:30:52 +0000301 /* sign * significand * (10 ^ (esign * exponent)) */
drh025586a2010-09-30 17:33:11 +0000302 int sign = 1; /* sign of significand */
303 i64 s = 0; /* significand */
304 int d = 0; /* adjust exponent for shifting decimal point */
305 int esign = 1; /* sign of exponent */
306 int e = 0; /* exponent */
307 int eValid = 1; /* True exponent is either not used or is well-formed */
drhc81c11f2009-11-10 01:30:52 +0000308 double result;
309 int nDigits = 0;
drh0e5fba72013-03-20 12:04:29 +0000310 int nonNum = 0;
drhc81c11f2009-11-10 01:30:52 +0000311
drh0e5fba72013-03-20 12:04:29 +0000312 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
drh025586a2010-09-30 17:33:11 +0000313 *pResult = 0.0; /* Default return value, in case of an error */
314
drh0e5fba72013-03-20 12:04:29 +0000315 if( enc==SQLITE_UTF8 ){
316 incr = 1;
317 }else{
318 int i;
319 incr = 2;
320 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
321 for(i=3-enc; i<length && z[i]==0; i+=2){}
322 nonNum = i<length;
323 zEnd = z+i+enc-3;
324 z += (enc&1);
325 }
drh9339da12010-09-30 00:50:49 +0000326
drhc81c11f2009-11-10 01:30:52 +0000327 /* skip leading spaces */
drh9339da12010-09-30 00:50:49 +0000328 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
drh025586a2010-09-30 17:33:11 +0000329 if( z>=zEnd ) return 0;
drh9339da12010-09-30 00:50:49 +0000330
drhc81c11f2009-11-10 01:30:52 +0000331 /* get sign of significand */
332 if( *z=='-' ){
333 sign = -1;
drh9339da12010-09-30 00:50:49 +0000334 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000335 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000336 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000337 }
drh9339da12010-09-30 00:50:49 +0000338
drhc81c11f2009-11-10 01:30:52 +0000339 /* skip leading zeroes */
drh9339da12010-09-30 00:50:49 +0000340 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000341
342 /* copy max significant digits to significand */
drh9339da12010-09-30 00:50:49 +0000343 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
drhc81c11f2009-11-10 01:30:52 +0000344 s = s*10 + (*z - '0');
drh9339da12010-09-30 00:50:49 +0000345 z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000346 }
drh9339da12010-09-30 00:50:49 +0000347
drhc81c11f2009-11-10 01:30:52 +0000348 /* skip non-significant significand digits
349 ** (increase exponent by d to shift decimal left) */
drh9339da12010-09-30 00:50:49 +0000350 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
351 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000352
353 /* if decimal point is present */
354 if( *z=='.' ){
drh9339da12010-09-30 00:50:49 +0000355 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000356 /* copy digits from after decimal to significand
357 ** (decrease exponent by d to shift decimal right) */
drh9339da12010-09-30 00:50:49 +0000358 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
drhc81c11f2009-11-10 01:30:52 +0000359 s = s*10 + (*z - '0');
drh9339da12010-09-30 00:50:49 +0000360 z+=incr, nDigits++, d--;
drhc81c11f2009-11-10 01:30:52 +0000361 }
362 /* skip non-significant digits */
drh9339da12010-09-30 00:50:49 +0000363 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000364 }
drh9339da12010-09-30 00:50:49 +0000365 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000366
367 /* if exponent is present */
368 if( *z=='e' || *z=='E' ){
drh9339da12010-09-30 00:50:49 +0000369 z+=incr;
drh025586a2010-09-30 17:33:11 +0000370 eValid = 0;
drh9339da12010-09-30 00:50:49 +0000371 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000372 /* get sign of exponent */
373 if( *z=='-' ){
374 esign = -1;
drh9339da12010-09-30 00:50:49 +0000375 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000376 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000377 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000378 }
379 /* copy digits to exponent */
drh9339da12010-09-30 00:50:49 +0000380 while( z<zEnd && sqlite3Isdigit(*z) ){
drh57db4a72011-10-17 20:41:46 +0000381 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
drh9339da12010-09-30 00:50:49 +0000382 z+=incr;
drh025586a2010-09-30 17:33:11 +0000383 eValid = 1;
drhc81c11f2009-11-10 01:30:52 +0000384 }
385 }
386
drh025586a2010-09-30 17:33:11 +0000387 /* skip trailing spaces */
388 if( nDigits && eValid ){
389 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
390 }
391
drh9339da12010-09-30 00:50:49 +0000392do_atof_calc:
drhc81c11f2009-11-10 01:30:52 +0000393 /* adjust exponent by d, and update sign */
394 e = (e*esign) + d;
395 if( e<0 ) {
396 esign = -1;
397 e *= -1;
398 } else {
399 esign = 1;
400 }
401
402 /* if 0 significand */
403 if( !s ) {
404 /* In the IEEE 754 standard, zero is signed.
405 ** Add the sign if we've seen at least one digit */
406 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
407 } else {
408 /* attempt to reduce exponent */
409 if( esign>0 ){
410 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
411 }else{
412 while( !(s%10) && e>0 ) e--,s/=10;
413 }
414
415 /* adjust the sign of significand */
416 s = sign<0 ? -s : s;
417
418 /* if exponent, scale significand as appropriate
419 ** and store in result. */
420 if( e ){
drh89f15082012-06-19 00:45:16 +0000421 LONGDOUBLE_TYPE scale = 1.0;
drhc81c11f2009-11-10 01:30:52 +0000422 /* attempt to handle extremely small/large numbers better */
423 if( e>307 && e<342 ){
424 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
425 if( esign<0 ){
426 result = s / scale;
427 result /= 1.0e+308;
428 }else{
429 result = s * scale;
430 result *= 1.0e+308;
431 }
drh2458a2e2011-10-17 12:14:26 +0000432 }else if( e>=342 ){
433 if( esign<0 ){
434 result = 0.0*s;
435 }else{
436 result = 1e308*1e308*s; /* Infinity */
437 }
drhc81c11f2009-11-10 01:30:52 +0000438 }else{
439 /* 1.0e+22 is the largest power of 10 than can be
440 ** represented exactly. */
441 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
442 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
443 if( esign<0 ){
444 result = s / scale;
445 }else{
446 result = s * scale;
447 }
448 }
449 } else {
450 result = (double)s;
451 }
452 }
453
454 /* store the result */
455 *pResult = result;
456
drh025586a2010-09-30 17:33:11 +0000457 /* return true if number and no extra non-whitespace chracters after */
drh0e5fba72013-03-20 12:04:29 +0000458 return z>=zEnd && nDigits>0 && eValid && nonNum==0;
drhc81c11f2009-11-10 01:30:52 +0000459#else
shaneh5f1d6b62010-09-30 16:51:25 +0000460 return !sqlite3Atoi64(z, pResult, length, enc);
drhc81c11f2009-11-10 01:30:52 +0000461#endif /* SQLITE_OMIT_FLOATING_POINT */
462}
463
464/*
465** Compare the 19-character string zNum against the text representation
466** value 2^63: 9223372036854775808. Return negative, zero, or positive
467** if zNum is less than, equal to, or greater than the string.
shaneh5f1d6b62010-09-30 16:51:25 +0000468** Note that zNum must contain exactly 19 characters.
drhc81c11f2009-11-10 01:30:52 +0000469**
470** Unlike memcmp() this routine is guaranteed to return the difference
471** in the values of the last digit if the only difference is in the
472** last digit. So, for example,
473**
drh9339da12010-09-30 00:50:49 +0000474** compare2pow63("9223372036854775800", 1)
drhc81c11f2009-11-10 01:30:52 +0000475**
476** will return -8.
477*/
drh9339da12010-09-30 00:50:49 +0000478static int compare2pow63(const char *zNum, int incr){
479 int c = 0;
480 int i;
481 /* 012345678901234567 */
482 const char *pow63 = "922337203685477580";
483 for(i=0; c==0 && i<18; i++){
484 c = (zNum[i*incr]-pow63[i])*10;
485 }
drhc81c11f2009-11-10 01:30:52 +0000486 if( c==0 ){
drh9339da12010-09-30 00:50:49 +0000487 c = zNum[18*incr] - '8';
drh44dbca82010-01-13 04:22:20 +0000488 testcase( c==(-1) );
489 testcase( c==0 );
490 testcase( c==(+1) );
drhc81c11f2009-11-10 01:30:52 +0000491 }
492 return c;
493}
494
drhc81c11f2009-11-10 01:30:52 +0000495/*
drh9296c182014-07-23 13:40:49 +0000496** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
497** routine does *not* accept hexadecimal notation.
drh158b9cb2011-03-05 20:59:46 +0000498**
499** If the zNum value is representable as a 64-bit twos-complement
500** integer, then write that value into *pNum and return 0.
501**
drha256c1a2013-12-01 01:18:29 +0000502** If zNum is exactly 9223372036854775808, return 2. This special
503** case is broken out because while 9223372036854775808 cannot be a
504** signed 64-bit integer, its negative -9223372036854775808 can be.
drh158b9cb2011-03-05 20:59:46 +0000505**
506** If zNum is too big for a 64-bit integer and is not
drha256c1a2013-12-01 01:18:29 +0000507** 9223372036854775808 or if zNum contains any non-numeric text,
drh0e5fba72013-03-20 12:04:29 +0000508** then return 1.
drhc81c11f2009-11-10 01:30:52 +0000509**
drh9339da12010-09-30 00:50:49 +0000510** length is the number of bytes in the string (bytes, not characters).
511** The string is not necessarily zero-terminated. The encoding is
512** given by enc.
drhc81c11f2009-11-10 01:30:52 +0000513*/
drh9339da12010-09-30 00:50:49 +0000514int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
drh0e5fba72013-03-20 12:04:29 +0000515 int incr;
drh158b9cb2011-03-05 20:59:46 +0000516 u64 u = 0;
shaneh5f1d6b62010-09-30 16:51:25 +0000517 int neg = 0; /* assume positive */
drh9339da12010-09-30 00:50:49 +0000518 int i;
519 int c = 0;
drh0e5fba72013-03-20 12:04:29 +0000520 int nonNum = 0;
drhc81c11f2009-11-10 01:30:52 +0000521 const char *zStart;
drh9339da12010-09-30 00:50:49 +0000522 const char *zEnd = zNum + length;
drh0e5fba72013-03-20 12:04:29 +0000523 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
524 if( enc==SQLITE_UTF8 ){
525 incr = 1;
526 }else{
527 incr = 2;
528 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
529 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
530 nonNum = i<length;
531 zEnd = zNum+i+enc-3;
532 zNum += (enc&1);
533 }
drh9339da12010-09-30 00:50:49 +0000534 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
drh158b9cb2011-03-05 20:59:46 +0000535 if( zNum<zEnd ){
536 if( *zNum=='-' ){
537 neg = 1;
538 zNum+=incr;
539 }else if( *zNum=='+' ){
540 zNum+=incr;
541 }
drhc81c11f2009-11-10 01:30:52 +0000542 }
543 zStart = zNum;
drh9339da12010-09-30 00:50:49 +0000544 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
545 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
drh158b9cb2011-03-05 20:59:46 +0000546 u = u*10 + c - '0';
drhc81c11f2009-11-10 01:30:52 +0000547 }
drh158b9cb2011-03-05 20:59:46 +0000548 if( u>LARGEST_INT64 ){
drhde1a8b82013-11-26 15:45:02 +0000549 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
drh158b9cb2011-03-05 20:59:46 +0000550 }else if( neg ){
551 *pNum = -(i64)u;
552 }else{
553 *pNum = (i64)u;
554 }
drh44dbca82010-01-13 04:22:20 +0000555 testcase( i==18 );
556 testcase( i==19 );
557 testcase( i==20 );
drh12886632013-03-28 11:40:14 +0000558 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
drhc81c11f2009-11-10 01:30:52 +0000559 /* zNum is empty or contains non-numeric text or is longer
shaneh5f1d6b62010-09-30 16:51:25 +0000560 ** than 19 digits (thus guaranteeing that it is too large) */
561 return 1;
drh9339da12010-09-30 00:50:49 +0000562 }else if( i<19*incr ){
drhc81c11f2009-11-10 01:30:52 +0000563 /* Less than 19 digits, so we know that it fits in 64 bits */
drh158b9cb2011-03-05 20:59:46 +0000564 assert( u<=LARGEST_INT64 );
shaneh5f1d6b62010-09-30 16:51:25 +0000565 return 0;
drhc81c11f2009-11-10 01:30:52 +0000566 }else{
drh158b9cb2011-03-05 20:59:46 +0000567 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
568 c = compare2pow63(zNum, incr);
569 if( c<0 ){
570 /* zNum is less than 9223372036854775808 so it fits */
571 assert( u<=LARGEST_INT64 );
572 return 0;
573 }else if( c>0 ){
574 /* zNum is greater than 9223372036854775808 so it overflows */
575 return 1;
576 }else{
577 /* zNum is exactly 9223372036854775808. Fits if negative. The
578 ** special case 2 overflow if positive */
579 assert( u-1==LARGEST_INT64 );
drh158b9cb2011-03-05 20:59:46 +0000580 return neg ? 0 : 2;
581 }
drhc81c11f2009-11-10 01:30:52 +0000582 }
583}
584
585/*
drh9296c182014-07-23 13:40:49 +0000586** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
587** into a 64-bit signed integer. This routine accepts hexadecimal literals,
588** whereas sqlite3Atoi64() does not.
589**
590** Returns:
591**
592** 0 Successful transformation. Fits in a 64-bit signed integer.
593** 1 Integer too large for a 64-bit signed integer or is malformed
594** 2 Special case of 9223372036854775808
595*/
596int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
597#ifndef SQLITE_OMIT_HEX_INTEGER
598 if( z[0]=='0'
599 && (z[1]=='x' || z[1]=='X')
600 && sqlite3Isxdigit(z[2])
601 ){
602 u64 u = 0;
603 int i, k;
604 for(i=2; z[i]=='0'; i++){}
605 for(k=i; sqlite3Isxdigit(z[k]); k++){
606 u = u*16 + sqlite3HexToInt(z[k]);
607 }
608 memcpy(pOut, &u, 8);
609 return (z[k]==0 && k-i<=16) ? 0 : 1;
610 }else
611#endif /* SQLITE_OMIT_HEX_INTEGER */
612 {
613 return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
614 }
615}
616
617/*
drhc81c11f2009-11-10 01:30:52 +0000618** If zNum represents an integer that will fit in 32-bits, then set
619** *pValue to that integer and return true. Otherwise return false.
620**
drh9296c182014-07-23 13:40:49 +0000621** This routine accepts both decimal and hexadecimal notation for integers.
622**
drhc81c11f2009-11-10 01:30:52 +0000623** Any non-numeric characters that following zNum are ignored.
624** This is different from sqlite3Atoi64() which requires the
625** input number to be zero-terminated.
626*/
627int sqlite3GetInt32(const char *zNum, int *pValue){
628 sqlite_int64 v = 0;
629 int i, c;
630 int neg = 0;
631 if( zNum[0]=='-' ){
632 neg = 1;
633 zNum++;
634 }else if( zNum[0]=='+' ){
635 zNum++;
636 }
drh28e048c2014-07-23 01:26:51 +0000637#ifndef SQLITE_OMIT_HEX_INTEGER
638 else if( zNum[0]=='0'
639 && (zNum[1]=='x' || zNum[1]=='X')
640 && sqlite3Isxdigit(zNum[2])
641 ){
642 u32 u = 0;
643 zNum += 2;
644 while( zNum[0]=='0' ) zNum++;
645 for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
646 u = u*16 + sqlite3HexToInt(zNum[i]);
647 }
648 if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
649 memcpy(pValue, &u, 4);
650 return 1;
651 }else{
652 return 0;
653 }
654 }
655#endif
drh935f2e72015-04-18 04:45:00 +0000656 while( zNum[0]=='0' ) zNum++;
drhc81c11f2009-11-10 01:30:52 +0000657 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
658 v = v*10 + c;
659 }
660
661 /* The longest decimal representation of a 32 bit integer is 10 digits:
662 **
663 ** 1234567890
664 ** 2^31 -> 2147483648
665 */
drh44dbca82010-01-13 04:22:20 +0000666 testcase( i==10 );
drhc81c11f2009-11-10 01:30:52 +0000667 if( i>10 ){
668 return 0;
669 }
drh44dbca82010-01-13 04:22:20 +0000670 testcase( v-neg==2147483647 );
drhc81c11f2009-11-10 01:30:52 +0000671 if( v-neg>2147483647 ){
672 return 0;
673 }
674 if( neg ){
675 v = -v;
676 }
677 *pValue = (int)v;
678 return 1;
679}
680
681/*
drh60ac3f42010-11-23 18:59:27 +0000682** Return a 32-bit integer value extracted from a string. If the
683** string is not an integer, just return 0.
684*/
685int sqlite3Atoi(const char *z){
686 int x = 0;
687 if( z ) sqlite3GetInt32(z, &x);
688 return x;
689}
690
691/*
drhc81c11f2009-11-10 01:30:52 +0000692** The variable-length integer encoding is as follows:
693**
694** KEY:
695** A = 0xxxxxxx 7 bits of data and one flag bit
696** B = 1xxxxxxx 7 bits of data and one flag bit
697** C = xxxxxxxx 8 bits of data
698**
699** 7 bits - A
700** 14 bits - BA
701** 21 bits - BBA
702** 28 bits - BBBA
703** 35 bits - BBBBA
704** 42 bits - BBBBBA
705** 49 bits - BBBBBBA
706** 56 bits - BBBBBBBA
707** 64 bits - BBBBBBBBC
708*/
709
710/*
711** Write a 64-bit variable-length integer to memory starting at p[0].
712** The length of data write will be between 1 and 9 bytes. The number
713** of bytes written is returned.
714**
715** A variable-length integer consists of the lower 7 bits of each byte
716** for all bytes that have the 8th bit set and one byte with the 8th
717** bit clear. Except, if we get to the 9th byte, it stores the full
718** 8 bits and is the last byte.
719*/
drh2f2b2b82014-08-22 18:48:25 +0000720static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
drhc81c11f2009-11-10 01:30:52 +0000721 int i, j, n;
722 u8 buf[10];
723 if( v & (((u64)0xff000000)<<32) ){
724 p[8] = (u8)v;
725 v >>= 8;
726 for(i=7; i>=0; i--){
727 p[i] = (u8)((v & 0x7f) | 0x80);
728 v >>= 7;
729 }
730 return 9;
731 }
732 n = 0;
733 do{
734 buf[n++] = (u8)((v & 0x7f) | 0x80);
735 v >>= 7;
736 }while( v!=0 );
737 buf[0] &= 0x7f;
738 assert( n<=9 );
739 for(i=0, j=n-1; j>=0; j--, i++){
740 p[i] = buf[j];
741 }
742 return n;
743}
drh2f2b2b82014-08-22 18:48:25 +0000744int sqlite3PutVarint(unsigned char *p, u64 v){
745 if( v<=0x7f ){
746 p[0] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000747 return 1;
748 }
drh2f2b2b82014-08-22 18:48:25 +0000749 if( v<=0x3fff ){
750 p[0] = ((v>>7)&0x7f)|0x80;
751 p[1] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000752 return 2;
753 }
drh2f2b2b82014-08-22 18:48:25 +0000754 return putVarint64(p,v);
drhc81c11f2009-11-10 01:30:52 +0000755}
756
757/*
drh0b2864c2010-03-03 15:18:38 +0000758** Bitmasks used by sqlite3GetVarint(). These precomputed constants
759** are defined here rather than simply putting the constant expressions
760** inline in order to work around bugs in the RVT compiler.
761**
762** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
763**
764** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
765*/
766#define SLOT_2_0 0x001fc07f
767#define SLOT_4_2_0 0xf01fc07f
768
769
770/*
drhc81c11f2009-11-10 01:30:52 +0000771** Read a 64-bit variable-length integer from memory starting at p[0].
772** Return the number of bytes read. The value is stored in *v.
773*/
774u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
775 u32 a,b,s;
776
777 a = *p;
778 /* a: p0 (unmasked) */
779 if (!(a&0x80))
780 {
781 *v = a;
782 return 1;
783 }
784
785 p++;
786 b = *p;
787 /* b: p1 (unmasked) */
788 if (!(b&0x80))
789 {
790 a &= 0x7f;
791 a = a<<7;
792 a |= b;
793 *v = a;
794 return 2;
795 }
796
drh0b2864c2010-03-03 15:18:38 +0000797 /* Verify that constants are precomputed correctly */
798 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
shaneh1da207e2010-03-09 14:41:12 +0000799 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
drh0b2864c2010-03-03 15:18:38 +0000800
drhc81c11f2009-11-10 01:30:52 +0000801 p++;
802 a = a<<14;
803 a |= *p;
804 /* a: p0<<14 | p2 (unmasked) */
805 if (!(a&0x80))
806 {
drh0b2864c2010-03-03 15:18:38 +0000807 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000808 b &= 0x7f;
809 b = b<<7;
810 a |= b;
811 *v = a;
812 return 3;
813 }
814
815 /* CSE1 from below */
drh0b2864c2010-03-03 15:18:38 +0000816 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000817 p++;
818 b = b<<14;
819 b |= *p;
820 /* b: p1<<14 | p3 (unmasked) */
821 if (!(b&0x80))
822 {
drh0b2864c2010-03-03 15:18:38 +0000823 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000824 /* moved CSE1 up */
825 /* a &= (0x7f<<14)|(0x7f); */
826 a = a<<7;
827 a |= b;
828 *v = a;
829 return 4;
830 }
831
832 /* a: p0<<14 | p2 (masked) */
833 /* b: p1<<14 | p3 (unmasked) */
834 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
835 /* moved CSE1 up */
836 /* a &= (0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +0000837 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000838 s = a;
839 /* s: p0<<14 | p2 (masked) */
840
841 p++;
842 a = a<<14;
843 a |= *p;
844 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
845 if (!(a&0x80))
846 {
847 /* we can skip these cause they were (effectively) done above in calc'ing s */
848 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
849 /* b &= (0x7f<<14)|(0x7f); */
850 b = b<<7;
851 a |= b;
852 s = s>>18;
853 *v = ((u64)s)<<32 | a;
854 return 5;
855 }
856
857 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
858 s = s<<7;
859 s |= b;
860 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
861
862 p++;
863 b = b<<14;
864 b |= *p;
865 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
866 if (!(b&0x80))
867 {
868 /* we can skip this cause it was (effectively) done above in calc'ing s */
869 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +0000870 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000871 a = a<<7;
872 a |= b;
873 s = s>>18;
874 *v = ((u64)s)<<32 | a;
875 return 6;
876 }
877
878 p++;
879 a = a<<14;
880 a |= *p;
881 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
882 if (!(a&0x80))
883 {
drh0b2864c2010-03-03 15:18:38 +0000884 a &= SLOT_4_2_0;
885 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000886 b = b<<7;
887 a |= b;
888 s = s>>11;
889 *v = ((u64)s)<<32 | a;
890 return 7;
891 }
892
893 /* CSE2 from below */
drh0b2864c2010-03-03 15:18:38 +0000894 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000895 p++;
896 b = b<<14;
897 b |= *p;
898 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
899 if (!(b&0x80))
900 {
drh0b2864c2010-03-03 15:18:38 +0000901 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +0000902 /* moved CSE2 up */
903 /* a &= (0x7f<<14)|(0x7f); */
904 a = a<<7;
905 a |= b;
906 s = s>>4;
907 *v = ((u64)s)<<32 | a;
908 return 8;
909 }
910
911 p++;
912 a = a<<15;
913 a |= *p;
914 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
915
916 /* moved CSE2 up */
917 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
drh0b2864c2010-03-03 15:18:38 +0000918 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000919 b = b<<8;
920 a |= b;
921
922 s = s<<4;
923 b = p[-4];
924 b &= 0x7f;
925 b = b>>3;
926 s |= b;
927
928 *v = ((u64)s)<<32 | a;
929
930 return 9;
931}
932
933/*
934** Read a 32-bit variable-length integer from memory starting at p[0].
935** Return the number of bytes read. The value is stored in *v.
936**
937** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
938** integer, then set *v to 0xffffffff.
939**
940** A MACRO version, getVarint32, is provided which inlines the
941** single-byte case. All code should use the MACRO version as
942** this function assumes the single-byte case has already been handled.
943*/
944u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
945 u32 a,b;
946
947 /* The 1-byte case. Overwhelmingly the most common. Handled inline
948 ** by the getVarin32() macro */
949 a = *p;
950 /* a: p0 (unmasked) */
951#ifndef getVarint32
952 if (!(a&0x80))
953 {
954 /* Values between 0 and 127 */
955 *v = a;
956 return 1;
957 }
958#endif
959
960 /* The 2-byte case */
961 p++;
962 b = *p;
963 /* b: p1 (unmasked) */
964 if (!(b&0x80))
965 {
966 /* Values between 128 and 16383 */
967 a &= 0x7f;
968 a = a<<7;
969 *v = a | b;
970 return 2;
971 }
972
973 /* The 3-byte case */
974 p++;
975 a = a<<14;
976 a |= *p;
977 /* a: p0<<14 | p2 (unmasked) */
978 if (!(a&0x80))
979 {
980 /* Values between 16384 and 2097151 */
981 a &= (0x7f<<14)|(0x7f);
982 b &= 0x7f;
983 b = b<<7;
984 *v = a | b;
985 return 3;
986 }
987
988 /* A 32-bit varint is used to store size information in btrees.
989 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
990 ** A 3-byte varint is sufficient, for example, to record the size
991 ** of a 1048569-byte BLOB or string.
992 **
993 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
994 ** rare larger cases can be handled by the slower 64-bit varint
995 ** routine.
996 */
997#if 1
998 {
999 u64 v64;
1000 u8 n;
1001
1002 p -= 2;
1003 n = sqlite3GetVarint(p, &v64);
1004 assert( n>3 && n<=9 );
1005 if( (v64 & SQLITE_MAX_U32)!=v64 ){
1006 *v = 0xffffffff;
1007 }else{
1008 *v = (u32)v64;
1009 }
1010 return n;
1011 }
1012
1013#else
1014 /* For following code (kept for historical record only) shows an
1015 ** unrolling for the 3- and 4-byte varint cases. This code is
1016 ** slightly faster, but it is also larger and much harder to test.
1017 */
1018 p++;
1019 b = b<<14;
1020 b |= *p;
1021 /* b: p1<<14 | p3 (unmasked) */
1022 if (!(b&0x80))
1023 {
1024 /* Values between 2097152 and 268435455 */
1025 b &= (0x7f<<14)|(0x7f);
1026 a &= (0x7f<<14)|(0x7f);
1027 a = a<<7;
1028 *v = a | b;
1029 return 4;
1030 }
1031
1032 p++;
1033 a = a<<14;
1034 a |= *p;
1035 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1036 if (!(a&0x80))
1037 {
dan3bbe7612010-03-03 16:02:05 +00001038 /* Values between 268435456 and 34359738367 */
1039 a &= SLOT_4_2_0;
1040 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +00001041 b = b<<7;
1042 *v = a | b;
1043 return 5;
1044 }
1045
1046 /* We can only reach this point when reading a corrupt database
1047 ** file. In that case we are not in any hurry. Use the (relatively
1048 ** slow) general-purpose sqlite3GetVarint() routine to extract the
1049 ** value. */
1050 {
1051 u64 v64;
1052 u8 n;
1053
1054 p -= 4;
1055 n = sqlite3GetVarint(p, &v64);
1056 assert( n>5 && n<=9 );
1057 *v = (u32)v64;
1058 return n;
1059 }
1060#endif
1061}
1062
1063/*
1064** Return the number of bytes that will be needed to store the given
1065** 64-bit integer.
1066*/
1067int sqlite3VarintLen(u64 v){
drh59a53642015-09-01 22:29:07 +00001068 int i;
1069 for(i=1; (v >>= 7)!=0; i++){ assert( i<9 ); }
drhc81c11f2009-11-10 01:30:52 +00001070 return i;
1071}
1072
1073
1074/*
1075** Read or write a four-byte big-endian integer value.
1076*/
1077u32 sqlite3Get4byte(const u8 *p){
drh5372e4d2015-06-30 12:47:09 +00001078#if SQLITE_BYTEORDER==4321
1079 u32 x;
1080 memcpy(&x,p,4);
1081 return x;
mistachkin60e08072015-07-29 21:47:39 +00001082#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1083 && defined(__GNUC__) && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:09 +00001084 u32 x;
1085 memcpy(&x,p,4);
1086 return __builtin_bswap32(x);
mistachkin60e08072015-07-29 21:47:39 +00001087#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
1088 && defined(_MSC_VER) && _MSC_VER>=1300
mistachkin647ca462015-06-30 17:28:40 +00001089 u32 x;
1090 memcpy(&x,p,4);
1091 return _byteswap_ulong(x);
drh5372e4d2015-06-30 12:47:09 +00001092#else
drh693e6712014-01-24 22:58:00 +00001093 testcase( p[0]&0x80 );
1094 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
drh5372e4d2015-06-30 12:47:09 +00001095#endif
drhc81c11f2009-11-10 01:30:52 +00001096}
1097void sqlite3Put4byte(unsigned char *p, u32 v){
drh5372e4d2015-06-30 12:47:09 +00001098#if SQLITE_BYTEORDER==4321
1099 memcpy(p,&v,4);
mistachkinf156c9b2015-07-03 17:54:49 +00001100#elif SQLITE_BYTEORDER==1234 && defined(__GNUC__) && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:09 +00001101 u32 x = __builtin_bswap32(v);
1102 memcpy(p,&x,4);
mistachkin647ca462015-06-30 17:28:40 +00001103#elif SQLITE_BYTEORDER==1234 && defined(_MSC_VER) && _MSC_VER>=1300
1104 u32 x = _byteswap_ulong(v);
1105 memcpy(p,&x,4);
drh5372e4d2015-06-30 12:47:09 +00001106#else
drhc81c11f2009-11-10 01:30:52 +00001107 p[0] = (u8)(v>>24);
1108 p[1] = (u8)(v>>16);
1109 p[2] = (u8)(v>>8);
1110 p[3] = (u8)v;
drh5372e4d2015-06-30 12:47:09 +00001111#endif
drhc81c11f2009-11-10 01:30:52 +00001112}
1113
drh9296c182014-07-23 13:40:49 +00001114
1115
1116/*
1117** Translate a single byte of Hex into an integer.
1118** This routine only works if h really is a valid hexadecimal
1119** character: 0..9a..fA..F
1120*/
1121u8 sqlite3HexToInt(int h){
1122 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
1123#ifdef SQLITE_ASCII
1124 h += 9*(1&(h>>6));
1125#endif
1126#ifdef SQLITE_EBCDIC
1127 h += 9*(1&~(h>>4));
1128#endif
1129 return (u8)(h & 0xf);
1130}
1131
drhc81c11f2009-11-10 01:30:52 +00001132#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
1133/*
1134** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
1135** value. Return a pointer to its binary value. Space to hold the
1136** binary value has been obtained from malloc and must be freed by
1137** the calling routine.
1138*/
1139void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
1140 char *zBlob;
1141 int i;
1142
1143 zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
1144 n--;
1145 if( zBlob ){
1146 for(i=0; i<n; i+=2){
dancd74b612011-04-22 19:37:32 +00001147 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
drhc81c11f2009-11-10 01:30:52 +00001148 }
1149 zBlob[i/2] = 0;
1150 }
1151 return zBlob;
1152}
1153#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
1154
drh413c3d32010-02-23 20:11:56 +00001155/*
1156** Log an error that is an API call on a connection pointer that should
1157** not have been used. The "type" of connection pointer is given as the
1158** argument. The zType is a word like "NULL" or "closed" or "invalid".
1159*/
1160static void logBadConnection(const char *zType){
1161 sqlite3_log(SQLITE_MISUSE,
1162 "API call with %s database connection pointer",
1163 zType
1164 );
1165}
drhc81c11f2009-11-10 01:30:52 +00001166
1167/*
drhc81c11f2009-11-10 01:30:52 +00001168** Check to make sure we have a valid db pointer. This test is not
1169** foolproof but it does provide some measure of protection against
1170** misuse of the interface such as passing in db pointers that are
1171** NULL or which have been previously closed. If this routine returns
1172** 1 it means that the db pointer is valid and 0 if it should not be
1173** dereferenced for any reason. The calling function should invoke
1174** SQLITE_MISUSE immediately.
1175**
1176** sqlite3SafetyCheckOk() requires that the db pointer be valid for
1177** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
1178** open properly and is not fit for general use but which can be
1179** used as an argument to sqlite3_errmsg() or sqlite3_close().
1180*/
1181int sqlite3SafetyCheckOk(sqlite3 *db){
1182 u32 magic;
drh413c3d32010-02-23 20:11:56 +00001183 if( db==0 ){
1184 logBadConnection("NULL");
1185 return 0;
1186 }
drhc81c11f2009-11-10 01:30:52 +00001187 magic = db->magic;
drh9978c972010-02-23 17:36:32 +00001188 if( magic!=SQLITE_MAGIC_OPEN ){
drhe294da02010-02-25 23:44:15 +00001189 if( sqlite3SafetyCheckSickOrOk(db) ){
1190 testcase( sqlite3GlobalConfig.xLog!=0 );
drh413c3d32010-02-23 20:11:56 +00001191 logBadConnection("unopened");
1192 }
drhc81c11f2009-11-10 01:30:52 +00001193 return 0;
1194 }else{
1195 return 1;
1196 }
1197}
1198int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
1199 u32 magic;
1200 magic = db->magic;
1201 if( magic!=SQLITE_MAGIC_SICK &&
1202 magic!=SQLITE_MAGIC_OPEN &&
drh413c3d32010-02-23 20:11:56 +00001203 magic!=SQLITE_MAGIC_BUSY ){
drhe294da02010-02-25 23:44:15 +00001204 testcase( sqlite3GlobalConfig.xLog!=0 );
drhaf46dc12010-02-24 21:44:07 +00001205 logBadConnection("invalid");
drh413c3d32010-02-23 20:11:56 +00001206 return 0;
1207 }else{
1208 return 1;
1209 }
drhc81c11f2009-11-10 01:30:52 +00001210}
drh158b9cb2011-03-05 20:59:46 +00001211
1212/*
1213** Attempt to add, substract, or multiply the 64-bit signed value iB against
1214** the other 64-bit signed integer at *pA and store the result in *pA.
1215** Return 0 on success. Or if the operation would have resulted in an
1216** overflow, leave *pA unchanged and return 1.
1217*/
1218int sqlite3AddInt64(i64 *pA, i64 iB){
1219 i64 iA = *pA;
1220 testcase( iA==0 ); testcase( iA==1 );
1221 testcase( iB==-1 ); testcase( iB==0 );
1222 if( iB>=0 ){
1223 testcase( iA>0 && LARGEST_INT64 - iA == iB );
1224 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
1225 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001226 }else{
1227 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
1228 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
1229 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001230 }
drh53a6eb32014-02-10 12:59:15 +00001231 *pA += iB;
drh158b9cb2011-03-05 20:59:46 +00001232 return 0;
1233}
1234int sqlite3SubInt64(i64 *pA, i64 iB){
1235 testcase( iB==SMALLEST_INT64+1 );
1236 if( iB==SMALLEST_INT64 ){
1237 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
1238 if( (*pA)>=0 ) return 1;
1239 *pA -= iB;
1240 return 0;
1241 }else{
1242 return sqlite3AddInt64(pA, -iB);
1243 }
1244}
1245#define TWOPOWER32 (((i64)1)<<32)
1246#define TWOPOWER31 (((i64)1)<<31)
1247int sqlite3MulInt64(i64 *pA, i64 iB){
1248 i64 iA = *pA;
1249 i64 iA1, iA0, iB1, iB0, r;
1250
drh158b9cb2011-03-05 20:59:46 +00001251 iA1 = iA/TWOPOWER32;
1252 iA0 = iA % TWOPOWER32;
1253 iB1 = iB/TWOPOWER32;
1254 iB0 = iB % TWOPOWER32;
drh53a6eb32014-02-10 12:59:15 +00001255 if( iA1==0 ){
1256 if( iB1==0 ){
1257 *pA *= iB;
1258 return 0;
1259 }
1260 r = iA0*iB1;
1261 }else if( iB1==0 ){
1262 r = iA1*iB0;
1263 }else{
1264 /* If both iA1 and iB1 are non-zero, overflow will result */
1265 return 1;
1266 }
drh158b9cb2011-03-05 20:59:46 +00001267 testcase( r==(-TWOPOWER31)-1 );
1268 testcase( r==(-TWOPOWER31) );
1269 testcase( r==TWOPOWER31 );
1270 testcase( r==TWOPOWER31-1 );
1271 if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
1272 r *= TWOPOWER32;
1273 if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
1274 *pA = r;
1275 return 0;
1276}
drhd50ffc42011-03-08 02:38:28 +00001277
1278/*
1279** Compute the absolute value of a 32-bit signed integer, of possible. Or
1280** if the integer has a value of -2147483648, return +2147483647
1281*/
1282int sqlite3AbsInt32(int x){
1283 if( x>=0 ) return x;
drh87e79ae2011-03-08 13:06:41 +00001284 if( x==(int)0x80000000 ) return 0x7fffffff;
drhd50ffc42011-03-08 02:38:28 +00001285 return -x;
1286}
drh81cc5162011-05-17 20:36:21 +00001287
1288#ifdef SQLITE_ENABLE_8_3_NAMES
1289/*
drhb51bf432011-07-21 21:29:35 +00001290** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
drh81cc5162011-05-17 20:36:21 +00001291** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
1292** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
1293** three characters, then shorten the suffix on z[] to be the last three
1294** characters of the original suffix.
1295**
drhb51bf432011-07-21 21:29:35 +00001296** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
1297** do the suffix shortening regardless of URI parameter.
1298**
drh81cc5162011-05-17 20:36:21 +00001299** Examples:
1300**
1301** test.db-journal => test.nal
1302** test.db-wal => test.wal
1303** test.db-shm => test.shm
drhf5808602011-12-16 00:33:04 +00001304** test.db-mj7f3319fa => test.9fa
drh81cc5162011-05-17 20:36:21 +00001305*/
1306void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
drhb51bf432011-07-21 21:29:35 +00001307#if SQLITE_ENABLE_8_3_NAMES<2
drh7d39e172012-01-02 12:41:53 +00001308 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
drhb51bf432011-07-21 21:29:35 +00001309#endif
1310 {
drh81cc5162011-05-17 20:36:21 +00001311 int i, sz;
1312 sz = sqlite3Strlen30(z);
drhc83f2d42011-05-18 02:41:10 +00001313 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
drhc02a43a2012-01-10 23:18:38 +00001314 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
drh81cc5162011-05-17 20:36:21 +00001315 }
1316}
1317#endif
drhbf539c42013-10-05 18:16:02 +00001318
1319/*
1320** Find (an approximate) sum of two LogEst values. This computation is
1321** not a simple "+" operator because LogEst is stored as a logarithmic
1322** value.
1323**
1324*/
1325LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
1326 static const unsigned char x[] = {
1327 10, 10, /* 0,1 */
1328 9, 9, /* 2,3 */
1329 8, 8, /* 4,5 */
1330 7, 7, 7, /* 6,7,8 */
1331 6, 6, 6, /* 9,10,11 */
1332 5, 5, 5, /* 12-14 */
1333 4, 4, 4, 4, /* 15-18 */
1334 3, 3, 3, 3, 3, 3, /* 19-24 */
1335 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
1336 };
1337 if( a>=b ){
1338 if( a>b+49 ) return a;
1339 if( a>b+31 ) return a+1;
1340 return a+x[a-b];
1341 }else{
1342 if( b>a+49 ) return b;
1343 if( b>a+31 ) return b+1;
1344 return b+x[b-a];
1345 }
1346}
1347
1348/*
drh224155d2014-04-30 13:19:09 +00001349** Convert an integer into a LogEst. In other words, compute an
1350** approximation for 10*log2(x).
drhbf539c42013-10-05 18:16:02 +00001351*/
1352LogEst sqlite3LogEst(u64 x){
1353 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1354 LogEst y = 40;
1355 if( x<8 ){
1356 if( x<2 ) return 0;
1357 while( x<8 ){ y -= 10; x <<= 1; }
1358 }else{
1359 while( x>255 ){ y += 40; x >>= 4; }
1360 while( x>15 ){ y += 10; x >>= 1; }
1361 }
1362 return a[x&7] + y - 10;
1363}
1364
1365#ifndef SQLITE_OMIT_VIRTUALTABLE
1366/*
1367** Convert a double into a LogEst
1368** In other words, compute an approximation for 10*log2(x).
1369*/
1370LogEst sqlite3LogEstFromDouble(double x){
1371 u64 a;
1372 LogEst e;
1373 assert( sizeof(x)==8 && sizeof(a)==8 );
1374 if( x<=1 ) return 0;
1375 if( x<=2000000000 ) return sqlite3LogEst((u64)x);
1376 memcpy(&a, &x, 8);
1377 e = (a>>52) - 1022;
1378 return e*10;
1379}
1380#endif /* SQLITE_OMIT_VIRTUALTABLE */
1381
1382/*
1383** Convert a LogEst into an integer.
1384*/
1385u64 sqlite3LogEstToInt(LogEst x){
1386 u64 n;
1387 if( x<10 ) return 1;
1388 n = x%10;
1389 x /= 10;
1390 if( n>=5 ) n -= 2;
1391 else if( n>=1 ) n -= 1;
drh47676fe2013-12-05 16:41:55 +00001392 if( x>=3 ){
1393 return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
1394 }
drhbf539c42013-10-05 18:16:02 +00001395 return (n+8)>>(3-x);
1396}