blob: 6e64242e876c1d9b4dbeb45ed2e22b3841f85cc6 [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){
108 const char *z2 = z;
109 if( z==0 ) return 0;
110 while( *z2 ){ z2++; }
111 return 0x3fffffff & (int)(z2 - z);
112}
113
114/*
drh13f40da2014-08-22 18:00:11 +0000115** Set the current error code to err_code and clear any prior error message.
116*/
117void sqlite3Error(sqlite3 *db, int err_code){
118 assert( db!=0 );
119 db->errCode = err_code;
120 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
121}
122
123/*
drhc81c11f2009-11-10 01:30:52 +0000124** Set the most recent error code and error string for the sqlite
125** handle "db". The error code is set to "err_code".
126**
127** If it is not NULL, string zFormat specifies the format of the
128** error string in the style of the printf functions: The following
129** format characters are allowed:
130**
131** %s Insert a string
132** %z A string that should be freed after use
133** %d Insert an integer
134** %T Insert a token
135** %S Insert the first element of a SrcList
136**
137** zFormat and any string tokens that follow it are assumed to be
138** encoded in UTF-8.
139**
140** To clear the most recent error for sqlite handle "db", sqlite3Error
141** should be called with err_code set to SQLITE_OK and zFormat set
142** to NULL.
143*/
drh13f40da2014-08-22 18:00:11 +0000144void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
drha3cc0072013-12-13 16:23:55 +0000145 assert( db!=0 );
146 db->errCode = err_code;
drh13f40da2014-08-22 18:00:11 +0000147 if( zFormat==0 ){
148 sqlite3Error(db, err_code);
149 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
drha3cc0072013-12-13 16:23:55 +0000150 char *z;
151 va_list ap;
152 va_start(ap, zFormat);
153 z = sqlite3VMPrintf(db, zFormat, ap);
154 va_end(ap);
155 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
drhc81c11f2009-11-10 01:30:52 +0000156 }
157}
158
159/*
160** Add an error message to pParse->zErrMsg and increment pParse->nErr.
161** The following formatting characters are allowed:
162**
163** %s Insert a string
164** %z A string that should be freed after use
165** %d Insert an integer
166** %T Insert a token
167** %S Insert the first element of a SrcList
168**
drh13f40da2014-08-22 18:00:11 +0000169** This function should be used to report any error that occurs while
drhc81c11f2009-11-10 01:30:52 +0000170** compiling an SQL statement (i.e. within sqlite3_prepare()). The
171** last thing the sqlite3_prepare() function does is copy the error
172** stored by this function into the database handle using sqlite3Error().
drh13f40da2014-08-22 18:00:11 +0000173** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
174** during statement execution (sqlite3_step() etc.).
drhc81c11f2009-11-10 01:30:52 +0000175*/
176void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
drha7564662010-02-22 19:32:31 +0000177 char *zMsg;
drhc81c11f2009-11-10 01:30:52 +0000178 va_list ap;
179 sqlite3 *db = pParse->db;
drhc81c11f2009-11-10 01:30:52 +0000180 va_start(ap, zFormat);
drha7564662010-02-22 19:32:31 +0000181 zMsg = sqlite3VMPrintf(db, zFormat, ap);
drhc81c11f2009-11-10 01:30:52 +0000182 va_end(ap);
drha7564662010-02-22 19:32:31 +0000183 if( db->suppressErr ){
184 sqlite3DbFree(db, zMsg);
185 }else{
186 pParse->nErr++;
187 sqlite3DbFree(db, pParse->zErrMsg);
188 pParse->zErrMsg = zMsg;
189 pParse->rc = SQLITE_ERROR;
drha7564662010-02-22 19:32:31 +0000190 }
drhc81c11f2009-11-10 01:30:52 +0000191}
192
193/*
194** Convert an SQL-style quoted string into a normal string by removing
195** the quote characters. The conversion is done in-place. If the
196** input does not begin with a quote character, then this routine
197** is a no-op.
198**
199** The input string must be zero-terminated. A new zero-terminator
200** is added to the dequoted string.
201**
202** The return value is -1 if no dequoting occurs or the length of the
203** dequoted string, exclusive of the zero terminator, if dequoting does
204** occur.
205**
206** 2002-Feb-14: This routine is extended to remove MS-Access style
peter.d.reid60ec9142014-09-06 16:39:46 +0000207** brackets from around identifiers. For example: "[a-b-c]" becomes
drhc81c11f2009-11-10 01:30:52 +0000208** "a-b-c".
209*/
210int sqlite3Dequote(char *z){
211 char quote;
212 int i, j;
213 if( z==0 ) return -1;
214 quote = z[0];
215 switch( quote ){
216 case '\'': break;
217 case '"': break;
218 case '`': break; /* For MySQL compatibility */
219 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
220 default: return -1;
221 }
drh9ccd8652013-09-13 16:36:46 +0000222 for(i=1, j=0;; i++){
223 assert( z[i] );
drhc81c11f2009-11-10 01:30:52 +0000224 if( z[i]==quote ){
225 if( z[i+1]==quote ){
226 z[j++] = quote;
227 i++;
228 }else{
229 break;
230 }
231 }else{
232 z[j++] = z[i];
233 }
234 }
235 z[j] = 0;
236 return j;
237}
238
239/* Convenient short-hand */
240#define UpperToLower sqlite3UpperToLower
241
242/*
243** Some systems have stricmp(). Others have strcasecmp(). Because
244** there is no consistency, we will define our own.
drh9f129f42010-08-31 15:27:32 +0000245**
drh0299b402012-03-19 17:42:46 +0000246** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
247** sqlite3_strnicmp() APIs allow applications and extensions to compare
248** the contents of two buffers containing UTF-8 strings in a
249** case-independent fashion, using the same definition of "case
250** independence" that SQLite uses internally when comparing identifiers.
drhc81c11f2009-11-10 01:30:52 +0000251*/
drh3fa97302012-02-22 16:58:36 +0000252int sqlite3_stricmp(const char *zLeft, const char *zRight){
drhc81c11f2009-11-10 01:30:52 +0000253 register unsigned char *a, *b;
drh9ca95732014-10-24 00:35:58 +0000254 if( zLeft==0 ){
255 return zRight ? -1 : 0;
256 }else if( zRight==0 ){
257 return 1;
258 }
drhc81c11f2009-11-10 01:30:52 +0000259 a = (unsigned char *)zLeft;
260 b = (unsigned char *)zRight;
261 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
262 return UpperToLower[*a] - UpperToLower[*b];
263}
264int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
265 register unsigned char *a, *b;
drh9ca95732014-10-24 00:35:58 +0000266 if( zLeft==0 ){
267 return zRight ? -1 : 0;
268 }else if( zRight==0 ){
269 return 1;
270 }
drhc81c11f2009-11-10 01:30:52 +0000271 a = (unsigned char *)zLeft;
272 b = (unsigned char *)zRight;
273 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
274 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
275}
276
277/*
drh9339da12010-09-30 00:50:49 +0000278** The string z[] is an text representation of a real number.
drh025586a2010-09-30 17:33:11 +0000279** Convert this string to a double and write it into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000280**
drh9339da12010-09-30 00:50:49 +0000281** The string z[] is length bytes in length (bytes, not characters) and
282** uses the encoding enc. The string is not necessarily zero-terminated.
drhc81c11f2009-11-10 01:30:52 +0000283**
drh9339da12010-09-30 00:50:49 +0000284** Return TRUE if the result is a valid real number (or integer) and FALSE
drh025586a2010-09-30 17:33:11 +0000285** if the string is empty or contains extraneous text. Valid numbers
286** are in one of these formats:
287**
288** [+-]digits[E[+-]digits]
289** [+-]digits.[digits][E[+-]digits]
290** [+-].digits[E[+-]digits]
291**
292** Leading and trailing whitespace is ignored for the purpose of determining
293** validity.
294**
295** If some prefix of the input string is a valid number, this routine
296** returns FALSE but it still converts the prefix and writes the result
297** into *pResult.
drhc81c11f2009-11-10 01:30:52 +0000298*/
drh9339da12010-09-30 00:50:49 +0000299int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
drhc81c11f2009-11-10 01:30:52 +0000300#ifndef SQLITE_OMIT_FLOATING_POINT
drh0e5fba72013-03-20 12:04:29 +0000301 int incr;
drh9339da12010-09-30 00:50:49 +0000302 const char *zEnd = z + length;
drhc81c11f2009-11-10 01:30:52 +0000303 /* sign * significand * (10 ^ (esign * exponent)) */
drh025586a2010-09-30 17:33:11 +0000304 int sign = 1; /* sign of significand */
305 i64 s = 0; /* significand */
306 int d = 0; /* adjust exponent for shifting decimal point */
307 int esign = 1; /* sign of exponent */
308 int e = 0; /* exponent */
309 int eValid = 1; /* True exponent is either not used or is well-formed */
drhc81c11f2009-11-10 01:30:52 +0000310 double result;
311 int nDigits = 0;
drh0e5fba72013-03-20 12:04:29 +0000312 int nonNum = 0;
drhc81c11f2009-11-10 01:30:52 +0000313
drh0e5fba72013-03-20 12:04:29 +0000314 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
drh025586a2010-09-30 17:33:11 +0000315 *pResult = 0.0; /* Default return value, in case of an error */
316
drh0e5fba72013-03-20 12:04:29 +0000317 if( enc==SQLITE_UTF8 ){
318 incr = 1;
319 }else{
320 int i;
321 incr = 2;
322 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
323 for(i=3-enc; i<length && z[i]==0; i+=2){}
324 nonNum = i<length;
325 zEnd = z+i+enc-3;
326 z += (enc&1);
327 }
drh9339da12010-09-30 00:50:49 +0000328
drhc81c11f2009-11-10 01:30:52 +0000329 /* skip leading spaces */
drh9339da12010-09-30 00:50:49 +0000330 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
drh025586a2010-09-30 17:33:11 +0000331 if( z>=zEnd ) return 0;
drh9339da12010-09-30 00:50:49 +0000332
drhc81c11f2009-11-10 01:30:52 +0000333 /* get sign of significand */
334 if( *z=='-' ){
335 sign = -1;
drh9339da12010-09-30 00:50:49 +0000336 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000337 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000338 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000339 }
drh9339da12010-09-30 00:50:49 +0000340
drhc81c11f2009-11-10 01:30:52 +0000341 /* skip leading zeroes */
drh9339da12010-09-30 00:50:49 +0000342 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000343
344 /* copy max significant digits to significand */
drh9339da12010-09-30 00:50:49 +0000345 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
drhc81c11f2009-11-10 01:30:52 +0000346 s = s*10 + (*z - '0');
drh9339da12010-09-30 00:50:49 +0000347 z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000348 }
drh9339da12010-09-30 00:50:49 +0000349
drhc81c11f2009-11-10 01:30:52 +0000350 /* skip non-significant significand digits
351 ** (increase exponent by d to shift decimal left) */
drh9339da12010-09-30 00:50:49 +0000352 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
353 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000354
355 /* if decimal point is present */
356 if( *z=='.' ){
drh9339da12010-09-30 00:50:49 +0000357 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000358 /* copy digits from after decimal to significand
359 ** (decrease exponent by d to shift decimal right) */
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++, d--;
drhc81c11f2009-11-10 01:30:52 +0000363 }
364 /* skip non-significant digits */
drh9339da12010-09-30 00:50:49 +0000365 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
drhc81c11f2009-11-10 01:30:52 +0000366 }
drh9339da12010-09-30 00:50:49 +0000367 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000368
369 /* if exponent is present */
370 if( *z=='e' || *z=='E' ){
drh9339da12010-09-30 00:50:49 +0000371 z+=incr;
drh025586a2010-09-30 17:33:11 +0000372 eValid = 0;
drh9339da12010-09-30 00:50:49 +0000373 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52 +0000374 /* get sign of exponent */
375 if( *z=='-' ){
376 esign = -1;
drh9339da12010-09-30 00:50:49 +0000377 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000378 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49 +0000379 z+=incr;
drhc81c11f2009-11-10 01:30:52 +0000380 }
381 /* copy digits to exponent */
drh9339da12010-09-30 00:50:49 +0000382 while( z<zEnd && sqlite3Isdigit(*z) ){
drh57db4a72011-10-17 20:41:46 +0000383 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
drh9339da12010-09-30 00:50:49 +0000384 z+=incr;
drh025586a2010-09-30 17:33:11 +0000385 eValid = 1;
drhc81c11f2009-11-10 01:30:52 +0000386 }
387 }
388
drh025586a2010-09-30 17:33:11 +0000389 /* skip trailing spaces */
390 if( nDigits && eValid ){
391 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
392 }
393
drh9339da12010-09-30 00:50:49 +0000394do_atof_calc:
drhc81c11f2009-11-10 01:30:52 +0000395 /* adjust exponent by d, and update sign */
396 e = (e*esign) + d;
397 if( e<0 ) {
398 esign = -1;
399 e *= -1;
400 } else {
401 esign = 1;
402 }
403
404 /* if 0 significand */
405 if( !s ) {
406 /* In the IEEE 754 standard, zero is signed.
407 ** Add the sign if we've seen at least one digit */
408 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
409 } else {
410 /* attempt to reduce exponent */
411 if( esign>0 ){
412 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
413 }else{
414 while( !(s%10) && e>0 ) e--,s/=10;
415 }
416
417 /* adjust the sign of significand */
418 s = sign<0 ? -s : s;
419
420 /* if exponent, scale significand as appropriate
421 ** and store in result. */
422 if( e ){
drh89f15082012-06-19 00:45:16 +0000423 LONGDOUBLE_TYPE scale = 1.0;
drhc81c11f2009-11-10 01:30:52 +0000424 /* attempt to handle extremely small/large numbers better */
425 if( e>307 && e<342 ){
426 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
427 if( esign<0 ){
428 result = s / scale;
429 result /= 1.0e+308;
430 }else{
431 result = s * scale;
432 result *= 1.0e+308;
433 }
drh2458a2e2011-10-17 12:14:26 +0000434 }else if( e>=342 ){
435 if( esign<0 ){
436 result = 0.0*s;
437 }else{
438 result = 1e308*1e308*s; /* Infinity */
439 }
drhc81c11f2009-11-10 01:30:52 +0000440 }else{
441 /* 1.0e+22 is the largest power of 10 than can be
442 ** represented exactly. */
443 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
444 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
445 if( esign<0 ){
446 result = s / scale;
447 }else{
448 result = s * scale;
449 }
450 }
451 } else {
452 result = (double)s;
453 }
454 }
455
456 /* store the result */
457 *pResult = result;
458
drh025586a2010-09-30 17:33:11 +0000459 /* return true if number and no extra non-whitespace chracters after */
drh0e5fba72013-03-20 12:04:29 +0000460 return z>=zEnd && nDigits>0 && eValid && nonNum==0;
drhc81c11f2009-11-10 01:30:52 +0000461#else
shaneh5f1d6b62010-09-30 16:51:25 +0000462 return !sqlite3Atoi64(z, pResult, length, enc);
drhc81c11f2009-11-10 01:30:52 +0000463#endif /* SQLITE_OMIT_FLOATING_POINT */
464}
465
466/*
467** Compare the 19-character string zNum against the text representation
468** value 2^63: 9223372036854775808. Return negative, zero, or positive
469** if zNum is less than, equal to, or greater than the string.
shaneh5f1d6b62010-09-30 16:51:25 +0000470** Note that zNum must contain exactly 19 characters.
drhc81c11f2009-11-10 01:30:52 +0000471**
472** Unlike memcmp() this routine is guaranteed to return the difference
473** in the values of the last digit if the only difference is in the
474** last digit. So, for example,
475**
drh9339da12010-09-30 00:50:49 +0000476** compare2pow63("9223372036854775800", 1)
drhc81c11f2009-11-10 01:30:52 +0000477**
478** will return -8.
479*/
drh9339da12010-09-30 00:50:49 +0000480static int compare2pow63(const char *zNum, int incr){
481 int c = 0;
482 int i;
483 /* 012345678901234567 */
484 const char *pow63 = "922337203685477580";
485 for(i=0; c==0 && i<18; i++){
486 c = (zNum[i*incr]-pow63[i])*10;
487 }
drhc81c11f2009-11-10 01:30:52 +0000488 if( c==0 ){
drh9339da12010-09-30 00:50:49 +0000489 c = zNum[18*incr] - '8';
drh44dbca82010-01-13 04:22:20 +0000490 testcase( c==(-1) );
491 testcase( c==0 );
492 testcase( c==(+1) );
drhc81c11f2009-11-10 01:30:52 +0000493 }
494 return c;
495}
496
drhc81c11f2009-11-10 01:30:52 +0000497/*
drh9296c182014-07-23 13:40:49 +0000498** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
499** routine does *not* accept hexadecimal notation.
drh158b9cb2011-03-05 20:59:46 +0000500**
501** If the zNum value is representable as a 64-bit twos-complement
502** integer, then write that value into *pNum and return 0.
503**
drha256c1a2013-12-01 01:18:29 +0000504** If zNum is exactly 9223372036854775808, return 2. This special
505** case is broken out because while 9223372036854775808 cannot be a
506** signed 64-bit integer, its negative -9223372036854775808 can be.
drh158b9cb2011-03-05 20:59:46 +0000507**
508** If zNum is too big for a 64-bit integer and is not
drha256c1a2013-12-01 01:18:29 +0000509** 9223372036854775808 or if zNum contains any non-numeric text,
drh0e5fba72013-03-20 12:04:29 +0000510** then return 1.
drhc81c11f2009-11-10 01:30:52 +0000511**
drh9339da12010-09-30 00:50:49 +0000512** length is the number of bytes in the string (bytes, not characters).
513** The string is not necessarily zero-terminated. The encoding is
514** given by enc.
drhc81c11f2009-11-10 01:30:52 +0000515*/
drh9339da12010-09-30 00:50:49 +0000516int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
drh0e5fba72013-03-20 12:04:29 +0000517 int incr;
drh158b9cb2011-03-05 20:59:46 +0000518 u64 u = 0;
shaneh5f1d6b62010-09-30 16:51:25 +0000519 int neg = 0; /* assume positive */
drh9339da12010-09-30 00:50:49 +0000520 int i;
521 int c = 0;
drh0e5fba72013-03-20 12:04:29 +0000522 int nonNum = 0;
drhc81c11f2009-11-10 01:30:52 +0000523 const char *zStart;
drh9339da12010-09-30 00:50:49 +0000524 const char *zEnd = zNum + length;
drh0e5fba72013-03-20 12:04:29 +0000525 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
526 if( enc==SQLITE_UTF8 ){
527 incr = 1;
528 }else{
529 incr = 2;
530 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
531 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
532 nonNum = i<length;
533 zEnd = zNum+i+enc-3;
534 zNum += (enc&1);
535 }
drh9339da12010-09-30 00:50:49 +0000536 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
drh158b9cb2011-03-05 20:59:46 +0000537 if( zNum<zEnd ){
538 if( *zNum=='-' ){
539 neg = 1;
540 zNum+=incr;
541 }else if( *zNum=='+' ){
542 zNum+=incr;
543 }
drhc81c11f2009-11-10 01:30:52 +0000544 }
545 zStart = zNum;
drh9339da12010-09-30 00:50:49 +0000546 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
547 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
drh158b9cb2011-03-05 20:59:46 +0000548 u = u*10 + c - '0';
drhc81c11f2009-11-10 01:30:52 +0000549 }
drh158b9cb2011-03-05 20:59:46 +0000550 if( u>LARGEST_INT64 ){
drhde1a8b82013-11-26 15:45:02 +0000551 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
drh158b9cb2011-03-05 20:59:46 +0000552 }else if( neg ){
553 *pNum = -(i64)u;
554 }else{
555 *pNum = (i64)u;
556 }
drh44dbca82010-01-13 04:22:20 +0000557 testcase( i==18 );
558 testcase( i==19 );
559 testcase( i==20 );
drh12886632013-03-28 11:40:14 +0000560 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
drhc81c11f2009-11-10 01:30:52 +0000561 /* zNum is empty or contains non-numeric text or is longer
shaneh5f1d6b62010-09-30 16:51:25 +0000562 ** than 19 digits (thus guaranteeing that it is too large) */
563 return 1;
drh9339da12010-09-30 00:50:49 +0000564 }else if( i<19*incr ){
drhc81c11f2009-11-10 01:30:52 +0000565 /* Less than 19 digits, so we know that it fits in 64 bits */
drh158b9cb2011-03-05 20:59:46 +0000566 assert( u<=LARGEST_INT64 );
shaneh5f1d6b62010-09-30 16:51:25 +0000567 return 0;
drhc81c11f2009-11-10 01:30:52 +0000568 }else{
drh158b9cb2011-03-05 20:59:46 +0000569 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
570 c = compare2pow63(zNum, incr);
571 if( c<0 ){
572 /* zNum is less than 9223372036854775808 so it fits */
573 assert( u<=LARGEST_INT64 );
574 return 0;
575 }else if( c>0 ){
576 /* zNum is greater than 9223372036854775808 so it overflows */
577 return 1;
578 }else{
579 /* zNum is exactly 9223372036854775808. Fits if negative. The
580 ** special case 2 overflow if positive */
581 assert( u-1==LARGEST_INT64 );
drh158b9cb2011-03-05 20:59:46 +0000582 return neg ? 0 : 2;
583 }
drhc81c11f2009-11-10 01:30:52 +0000584 }
585}
586
587/*
drh9296c182014-07-23 13:40:49 +0000588** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
589** into a 64-bit signed integer. This routine accepts hexadecimal literals,
590** whereas sqlite3Atoi64() does not.
591**
592** Returns:
593**
594** 0 Successful transformation. Fits in a 64-bit signed integer.
595** 1 Integer too large for a 64-bit signed integer or is malformed
596** 2 Special case of 9223372036854775808
597*/
598int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
599#ifndef SQLITE_OMIT_HEX_INTEGER
600 if( z[0]=='0'
601 && (z[1]=='x' || z[1]=='X')
602 && sqlite3Isxdigit(z[2])
603 ){
604 u64 u = 0;
605 int i, k;
606 for(i=2; z[i]=='0'; i++){}
607 for(k=i; sqlite3Isxdigit(z[k]); k++){
608 u = u*16 + sqlite3HexToInt(z[k]);
609 }
610 memcpy(pOut, &u, 8);
611 return (z[k]==0 && k-i<=16) ? 0 : 1;
612 }else
613#endif /* SQLITE_OMIT_HEX_INTEGER */
614 {
615 return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
616 }
617}
618
619/*
drhc81c11f2009-11-10 01:30:52 +0000620** If zNum represents an integer that will fit in 32-bits, then set
621** *pValue to that integer and return true. Otherwise return false.
622**
drh9296c182014-07-23 13:40:49 +0000623** This routine accepts both decimal and hexadecimal notation for integers.
624**
drhc81c11f2009-11-10 01:30:52 +0000625** Any non-numeric characters that following zNum are ignored.
626** This is different from sqlite3Atoi64() which requires the
627** input number to be zero-terminated.
628*/
629int sqlite3GetInt32(const char *zNum, int *pValue){
630 sqlite_int64 v = 0;
631 int i, c;
632 int neg = 0;
633 if( zNum[0]=='-' ){
634 neg = 1;
635 zNum++;
636 }else if( zNum[0]=='+' ){
637 zNum++;
638 }
drh28e048c2014-07-23 01:26:51 +0000639#ifndef SQLITE_OMIT_HEX_INTEGER
640 else if( zNum[0]=='0'
641 && (zNum[1]=='x' || zNum[1]=='X')
642 && sqlite3Isxdigit(zNum[2])
643 ){
644 u32 u = 0;
645 zNum += 2;
646 while( zNum[0]=='0' ) zNum++;
647 for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
648 u = u*16 + sqlite3HexToInt(zNum[i]);
649 }
650 if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
651 memcpy(pValue, &u, 4);
652 return 1;
653 }else{
654 return 0;
655 }
656 }
657#endif
drhc81c11f2009-11-10 01:30:52 +0000658 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
659 v = v*10 + c;
660 }
661
662 /* The longest decimal representation of a 32 bit integer is 10 digits:
663 **
664 ** 1234567890
665 ** 2^31 -> 2147483648
666 */
drh44dbca82010-01-13 04:22:20 +0000667 testcase( i==10 );
drhc81c11f2009-11-10 01:30:52 +0000668 if( i>10 ){
669 return 0;
670 }
drh44dbca82010-01-13 04:22:20 +0000671 testcase( v-neg==2147483647 );
drhc81c11f2009-11-10 01:30:52 +0000672 if( v-neg>2147483647 ){
673 return 0;
674 }
675 if( neg ){
676 v = -v;
677 }
678 *pValue = (int)v;
679 return 1;
680}
681
682/*
drh60ac3f42010-11-23 18:59:27 +0000683** Return a 32-bit integer value extracted from a string. If the
684** string is not an integer, just return 0.
685*/
686int sqlite3Atoi(const char *z){
687 int x = 0;
688 if( z ) sqlite3GetInt32(z, &x);
689 return x;
690}
691
692/*
drhc81c11f2009-11-10 01:30:52 +0000693** The variable-length integer encoding is as follows:
694**
695** KEY:
696** A = 0xxxxxxx 7 bits of data and one flag bit
697** B = 1xxxxxxx 7 bits of data and one flag bit
698** C = xxxxxxxx 8 bits of data
699**
700** 7 bits - A
701** 14 bits - BA
702** 21 bits - BBA
703** 28 bits - BBBA
704** 35 bits - BBBBA
705** 42 bits - BBBBBA
706** 49 bits - BBBBBBA
707** 56 bits - BBBBBBBA
708** 64 bits - BBBBBBBBC
709*/
710
711/*
712** Write a 64-bit variable-length integer to memory starting at p[0].
713** The length of data write will be between 1 and 9 bytes. The number
714** of bytes written is returned.
715**
716** A variable-length integer consists of the lower 7 bits of each byte
717** for all bytes that have the 8th bit set and one byte with the 8th
718** bit clear. Except, if we get to the 9th byte, it stores the full
719** 8 bits and is the last byte.
720*/
drh2f2b2b82014-08-22 18:48:25 +0000721static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
drhc81c11f2009-11-10 01:30:52 +0000722 int i, j, n;
723 u8 buf[10];
724 if( v & (((u64)0xff000000)<<32) ){
725 p[8] = (u8)v;
726 v >>= 8;
727 for(i=7; i>=0; i--){
728 p[i] = (u8)((v & 0x7f) | 0x80);
729 v >>= 7;
730 }
731 return 9;
732 }
733 n = 0;
734 do{
735 buf[n++] = (u8)((v & 0x7f) | 0x80);
736 v >>= 7;
737 }while( v!=0 );
738 buf[0] &= 0x7f;
739 assert( n<=9 );
740 for(i=0, j=n-1; j>=0; j--, i++){
741 p[i] = buf[j];
742 }
743 return n;
744}
drh2f2b2b82014-08-22 18:48:25 +0000745int sqlite3PutVarint(unsigned char *p, u64 v){
746 if( v<=0x7f ){
747 p[0] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000748 return 1;
749 }
drh2f2b2b82014-08-22 18:48:25 +0000750 if( v<=0x3fff ){
751 p[0] = ((v>>7)&0x7f)|0x80;
752 p[1] = v&0x7f;
drhc81c11f2009-11-10 01:30:52 +0000753 return 2;
754 }
drh2f2b2b82014-08-22 18:48:25 +0000755 return putVarint64(p,v);
drhc81c11f2009-11-10 01:30:52 +0000756}
757
758/*
drh0b2864c2010-03-03 15:18:38 +0000759** Bitmasks used by sqlite3GetVarint(). These precomputed constants
760** are defined here rather than simply putting the constant expressions
761** inline in order to work around bugs in the RVT compiler.
762**
763** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
764**
765** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
766*/
767#define SLOT_2_0 0x001fc07f
768#define SLOT_4_2_0 0xf01fc07f
769
770
771/*
drhc81c11f2009-11-10 01:30:52 +0000772** Read a 64-bit variable-length integer from memory starting at p[0].
773** Return the number of bytes read. The value is stored in *v.
774*/
775u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
776 u32 a,b,s;
777
778 a = *p;
779 /* a: p0 (unmasked) */
780 if (!(a&0x80))
781 {
782 *v = a;
783 return 1;
784 }
785
786 p++;
787 b = *p;
788 /* b: p1 (unmasked) */
789 if (!(b&0x80))
790 {
791 a &= 0x7f;
792 a = a<<7;
793 a |= b;
794 *v = a;
795 return 2;
796 }
797
drh0b2864c2010-03-03 15:18:38 +0000798 /* Verify that constants are precomputed correctly */
799 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
shaneh1da207e2010-03-09 14:41:12 +0000800 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
drh0b2864c2010-03-03 15:18:38 +0000801
drhc81c11f2009-11-10 01:30:52 +0000802 p++;
803 a = a<<14;
804 a |= *p;
805 /* a: p0<<14 | p2 (unmasked) */
806 if (!(a&0x80))
807 {
drh0b2864c2010-03-03 15:18:38 +0000808 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000809 b &= 0x7f;
810 b = b<<7;
811 a |= b;
812 *v = a;
813 return 3;
814 }
815
816 /* CSE1 from below */
drh0b2864c2010-03-03 15:18:38 +0000817 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000818 p++;
819 b = b<<14;
820 b |= *p;
821 /* b: p1<<14 | p3 (unmasked) */
822 if (!(b&0x80))
823 {
drh0b2864c2010-03-03 15:18:38 +0000824 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000825 /* moved CSE1 up */
826 /* a &= (0x7f<<14)|(0x7f); */
827 a = a<<7;
828 a |= b;
829 *v = a;
830 return 4;
831 }
832
833 /* a: p0<<14 | p2 (masked) */
834 /* b: p1<<14 | p3 (unmasked) */
835 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
836 /* moved CSE1 up */
837 /* a &= (0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +0000838 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000839 s = a;
840 /* s: p0<<14 | p2 (masked) */
841
842 p++;
843 a = a<<14;
844 a |= *p;
845 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
846 if (!(a&0x80))
847 {
848 /* we can skip these cause they were (effectively) done above in calc'ing s */
849 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
850 /* b &= (0x7f<<14)|(0x7f); */
851 b = b<<7;
852 a |= b;
853 s = s>>18;
854 *v = ((u64)s)<<32 | a;
855 return 5;
856 }
857
858 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
859 s = s<<7;
860 s |= b;
861 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
862
863 p++;
864 b = b<<14;
865 b |= *p;
866 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
867 if (!(b&0x80))
868 {
869 /* we can skip this cause it was (effectively) done above in calc'ing s */
870 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:38 +0000871 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000872 a = a<<7;
873 a |= b;
874 s = s>>18;
875 *v = ((u64)s)<<32 | a;
876 return 6;
877 }
878
879 p++;
880 a = a<<14;
881 a |= *p;
882 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
883 if (!(a&0x80))
884 {
drh0b2864c2010-03-03 15:18:38 +0000885 a &= SLOT_4_2_0;
886 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000887 b = b<<7;
888 a |= b;
889 s = s>>11;
890 *v = ((u64)s)<<32 | a;
891 return 7;
892 }
893
894 /* CSE2 from below */
drh0b2864c2010-03-03 15:18:38 +0000895 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000896 p++;
897 b = b<<14;
898 b |= *p;
899 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
900 if (!(b&0x80))
901 {
drh0b2864c2010-03-03 15:18:38 +0000902 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +0000903 /* moved CSE2 up */
904 /* a &= (0x7f<<14)|(0x7f); */
905 a = a<<7;
906 a |= b;
907 s = s>>4;
908 *v = ((u64)s)<<32 | a;
909 return 8;
910 }
911
912 p++;
913 a = a<<15;
914 a |= *p;
915 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
916
917 /* moved CSE2 up */
918 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
drh0b2864c2010-03-03 15:18:38 +0000919 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:52 +0000920 b = b<<8;
921 a |= b;
922
923 s = s<<4;
924 b = p[-4];
925 b &= 0x7f;
926 b = b>>3;
927 s |= b;
928
929 *v = ((u64)s)<<32 | a;
930
931 return 9;
932}
933
934/*
935** Read a 32-bit variable-length integer from memory starting at p[0].
936** Return the number of bytes read. The value is stored in *v.
937**
938** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
939** integer, then set *v to 0xffffffff.
940**
941** A MACRO version, getVarint32, is provided which inlines the
942** single-byte case. All code should use the MACRO version as
943** this function assumes the single-byte case has already been handled.
944*/
945u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
946 u32 a,b;
947
948 /* The 1-byte case. Overwhelmingly the most common. Handled inline
949 ** by the getVarin32() macro */
950 a = *p;
951 /* a: p0 (unmasked) */
952#ifndef getVarint32
953 if (!(a&0x80))
954 {
955 /* Values between 0 and 127 */
956 *v = a;
957 return 1;
958 }
959#endif
960
961 /* The 2-byte case */
962 p++;
963 b = *p;
964 /* b: p1 (unmasked) */
965 if (!(b&0x80))
966 {
967 /* Values between 128 and 16383 */
968 a &= 0x7f;
969 a = a<<7;
970 *v = a | b;
971 return 2;
972 }
973
974 /* The 3-byte case */
975 p++;
976 a = a<<14;
977 a |= *p;
978 /* a: p0<<14 | p2 (unmasked) */
979 if (!(a&0x80))
980 {
981 /* Values between 16384 and 2097151 */
982 a &= (0x7f<<14)|(0x7f);
983 b &= 0x7f;
984 b = b<<7;
985 *v = a | b;
986 return 3;
987 }
988
989 /* A 32-bit varint is used to store size information in btrees.
990 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
991 ** A 3-byte varint is sufficient, for example, to record the size
992 ** of a 1048569-byte BLOB or string.
993 **
994 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
995 ** rare larger cases can be handled by the slower 64-bit varint
996 ** routine.
997 */
998#if 1
999 {
1000 u64 v64;
1001 u8 n;
1002
1003 p -= 2;
1004 n = sqlite3GetVarint(p, &v64);
1005 assert( n>3 && n<=9 );
1006 if( (v64 & SQLITE_MAX_U32)!=v64 ){
1007 *v = 0xffffffff;
1008 }else{
1009 *v = (u32)v64;
1010 }
1011 return n;
1012 }
1013
1014#else
1015 /* For following code (kept for historical record only) shows an
1016 ** unrolling for the 3- and 4-byte varint cases. This code is
1017 ** slightly faster, but it is also larger and much harder to test.
1018 */
1019 p++;
1020 b = b<<14;
1021 b |= *p;
1022 /* b: p1<<14 | p3 (unmasked) */
1023 if (!(b&0x80))
1024 {
1025 /* Values between 2097152 and 268435455 */
1026 b &= (0x7f<<14)|(0x7f);
1027 a &= (0x7f<<14)|(0x7f);
1028 a = a<<7;
1029 *v = a | b;
1030 return 4;
1031 }
1032
1033 p++;
1034 a = a<<14;
1035 a |= *p;
1036 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1037 if (!(a&0x80))
1038 {
dan3bbe7612010-03-03 16:02:05 +00001039 /* Values between 268435456 and 34359738367 */
1040 a &= SLOT_4_2_0;
1041 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:52 +00001042 b = b<<7;
1043 *v = a | b;
1044 return 5;
1045 }
1046
1047 /* We can only reach this point when reading a corrupt database
1048 ** file. In that case we are not in any hurry. Use the (relatively
1049 ** slow) general-purpose sqlite3GetVarint() routine to extract the
1050 ** value. */
1051 {
1052 u64 v64;
1053 u8 n;
1054
1055 p -= 4;
1056 n = sqlite3GetVarint(p, &v64);
1057 assert( n>5 && n<=9 );
1058 *v = (u32)v64;
1059 return n;
1060 }
1061#endif
1062}
1063
1064/*
1065** Return the number of bytes that will be needed to store the given
1066** 64-bit integer.
1067*/
1068int sqlite3VarintLen(u64 v){
1069 int i = 0;
1070 do{
1071 i++;
1072 v >>= 7;
1073 }while( v!=0 && ALWAYS(i<9) );
1074 return i;
1075}
1076
1077
1078/*
1079** Read or write a four-byte big-endian integer value.
1080*/
1081u32 sqlite3Get4byte(const u8 *p){
drh693e6712014-01-24 22:58:00 +00001082 testcase( p[0]&0x80 );
1083 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
drhc81c11f2009-11-10 01:30:52 +00001084}
1085void sqlite3Put4byte(unsigned char *p, u32 v){
1086 p[0] = (u8)(v>>24);
1087 p[1] = (u8)(v>>16);
1088 p[2] = (u8)(v>>8);
1089 p[3] = (u8)v;
1090}
1091
drh9296c182014-07-23 13:40:49 +00001092
1093
1094/*
1095** Translate a single byte of Hex into an integer.
1096** This routine only works if h really is a valid hexadecimal
1097** character: 0..9a..fA..F
1098*/
1099u8 sqlite3HexToInt(int h){
1100 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
1101#ifdef SQLITE_ASCII
1102 h += 9*(1&(h>>6));
1103#endif
1104#ifdef SQLITE_EBCDIC
1105 h += 9*(1&~(h>>4));
1106#endif
1107 return (u8)(h & 0xf);
1108}
1109
drhc81c11f2009-11-10 01:30:52 +00001110#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
1111/*
1112** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
1113** value. Return a pointer to its binary value. Space to hold the
1114** binary value has been obtained from malloc and must be freed by
1115** the calling routine.
1116*/
1117void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
1118 char *zBlob;
1119 int i;
1120
1121 zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
1122 n--;
1123 if( zBlob ){
1124 for(i=0; i<n; i+=2){
dancd74b612011-04-22 19:37:32 +00001125 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
drhc81c11f2009-11-10 01:30:52 +00001126 }
1127 zBlob[i/2] = 0;
1128 }
1129 return zBlob;
1130}
1131#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
1132
drh413c3d32010-02-23 20:11:56 +00001133/*
1134** Log an error that is an API call on a connection pointer that should
1135** not have been used. The "type" of connection pointer is given as the
1136** argument. The zType is a word like "NULL" or "closed" or "invalid".
1137*/
1138static void logBadConnection(const char *zType){
1139 sqlite3_log(SQLITE_MISUSE,
1140 "API call with %s database connection pointer",
1141 zType
1142 );
1143}
drhc81c11f2009-11-10 01:30:52 +00001144
1145/*
drhc81c11f2009-11-10 01:30:52 +00001146** Check to make sure we have a valid db pointer. This test is not
1147** foolproof but it does provide some measure of protection against
1148** misuse of the interface such as passing in db pointers that are
1149** NULL or which have been previously closed. If this routine returns
1150** 1 it means that the db pointer is valid and 0 if it should not be
1151** dereferenced for any reason. The calling function should invoke
1152** SQLITE_MISUSE immediately.
1153**
1154** sqlite3SafetyCheckOk() requires that the db pointer be valid for
1155** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
1156** open properly and is not fit for general use but which can be
1157** used as an argument to sqlite3_errmsg() or sqlite3_close().
1158*/
1159int sqlite3SafetyCheckOk(sqlite3 *db){
1160 u32 magic;
drh413c3d32010-02-23 20:11:56 +00001161 if( db==0 ){
1162 logBadConnection("NULL");
1163 return 0;
1164 }
drhc81c11f2009-11-10 01:30:52 +00001165 magic = db->magic;
drh9978c972010-02-23 17:36:32 +00001166 if( magic!=SQLITE_MAGIC_OPEN ){
drhe294da02010-02-25 23:44:15 +00001167 if( sqlite3SafetyCheckSickOrOk(db) ){
1168 testcase( sqlite3GlobalConfig.xLog!=0 );
drh413c3d32010-02-23 20:11:56 +00001169 logBadConnection("unopened");
1170 }
drhc81c11f2009-11-10 01:30:52 +00001171 return 0;
1172 }else{
1173 return 1;
1174 }
1175}
1176int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
1177 u32 magic;
1178 magic = db->magic;
1179 if( magic!=SQLITE_MAGIC_SICK &&
1180 magic!=SQLITE_MAGIC_OPEN &&
drh413c3d32010-02-23 20:11:56 +00001181 magic!=SQLITE_MAGIC_BUSY ){
drhe294da02010-02-25 23:44:15 +00001182 testcase( sqlite3GlobalConfig.xLog!=0 );
drhaf46dc12010-02-24 21:44:07 +00001183 logBadConnection("invalid");
drh413c3d32010-02-23 20:11:56 +00001184 return 0;
1185 }else{
1186 return 1;
1187 }
drhc81c11f2009-11-10 01:30:52 +00001188}
drh158b9cb2011-03-05 20:59:46 +00001189
1190/*
1191** Attempt to add, substract, or multiply the 64-bit signed value iB against
1192** the other 64-bit signed integer at *pA and store the result in *pA.
1193** Return 0 on success. Or if the operation would have resulted in an
1194** overflow, leave *pA unchanged and return 1.
1195*/
1196int sqlite3AddInt64(i64 *pA, i64 iB){
1197 i64 iA = *pA;
1198 testcase( iA==0 ); testcase( iA==1 );
1199 testcase( iB==-1 ); testcase( iB==0 );
1200 if( iB>=0 ){
1201 testcase( iA>0 && LARGEST_INT64 - iA == iB );
1202 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
1203 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001204 }else{
1205 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
1206 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
1207 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
drh158b9cb2011-03-05 20:59:46 +00001208 }
drh53a6eb32014-02-10 12:59:15 +00001209 *pA += iB;
drh158b9cb2011-03-05 20:59:46 +00001210 return 0;
1211}
1212int sqlite3SubInt64(i64 *pA, i64 iB){
1213 testcase( iB==SMALLEST_INT64+1 );
1214 if( iB==SMALLEST_INT64 ){
1215 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
1216 if( (*pA)>=0 ) return 1;
1217 *pA -= iB;
1218 return 0;
1219 }else{
1220 return sqlite3AddInt64(pA, -iB);
1221 }
1222}
1223#define TWOPOWER32 (((i64)1)<<32)
1224#define TWOPOWER31 (((i64)1)<<31)
1225int sqlite3MulInt64(i64 *pA, i64 iB){
1226 i64 iA = *pA;
1227 i64 iA1, iA0, iB1, iB0, r;
1228
drh158b9cb2011-03-05 20:59:46 +00001229 iA1 = iA/TWOPOWER32;
1230 iA0 = iA % TWOPOWER32;
1231 iB1 = iB/TWOPOWER32;
1232 iB0 = iB % TWOPOWER32;
drh53a6eb32014-02-10 12:59:15 +00001233 if( iA1==0 ){
1234 if( iB1==0 ){
1235 *pA *= iB;
1236 return 0;
1237 }
1238 r = iA0*iB1;
1239 }else if( iB1==0 ){
1240 r = iA1*iB0;
1241 }else{
1242 /* If both iA1 and iB1 are non-zero, overflow will result */
1243 return 1;
1244 }
drh158b9cb2011-03-05 20:59:46 +00001245 testcase( r==(-TWOPOWER31)-1 );
1246 testcase( r==(-TWOPOWER31) );
1247 testcase( r==TWOPOWER31 );
1248 testcase( r==TWOPOWER31-1 );
1249 if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
1250 r *= TWOPOWER32;
1251 if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
1252 *pA = r;
1253 return 0;
1254}
drhd50ffc42011-03-08 02:38:28 +00001255
1256/*
1257** Compute the absolute value of a 32-bit signed integer, of possible. Or
1258** if the integer has a value of -2147483648, return +2147483647
1259*/
1260int sqlite3AbsInt32(int x){
1261 if( x>=0 ) return x;
drh87e79ae2011-03-08 13:06:41 +00001262 if( x==(int)0x80000000 ) return 0x7fffffff;
drhd50ffc42011-03-08 02:38:28 +00001263 return -x;
1264}
drh81cc5162011-05-17 20:36:21 +00001265
1266#ifdef SQLITE_ENABLE_8_3_NAMES
1267/*
drhb51bf432011-07-21 21:29:35 +00001268** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
drh81cc5162011-05-17 20:36:21 +00001269** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
1270** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
1271** three characters, then shorten the suffix on z[] to be the last three
1272** characters of the original suffix.
1273**
drhb51bf432011-07-21 21:29:35 +00001274** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
1275** do the suffix shortening regardless of URI parameter.
1276**
drh81cc5162011-05-17 20:36:21 +00001277** Examples:
1278**
1279** test.db-journal => test.nal
1280** test.db-wal => test.wal
1281** test.db-shm => test.shm
drhf5808602011-12-16 00:33:04 +00001282** test.db-mj7f3319fa => test.9fa
drh81cc5162011-05-17 20:36:21 +00001283*/
1284void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
drhb51bf432011-07-21 21:29:35 +00001285#if SQLITE_ENABLE_8_3_NAMES<2
drh7d39e172012-01-02 12:41:53 +00001286 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
drhb51bf432011-07-21 21:29:35 +00001287#endif
1288 {
drh81cc5162011-05-17 20:36:21 +00001289 int i, sz;
1290 sz = sqlite3Strlen30(z);
drhc83f2d42011-05-18 02:41:10 +00001291 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
drhc02a43a2012-01-10 23:18:38 +00001292 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
drh81cc5162011-05-17 20:36:21 +00001293 }
1294}
1295#endif
drhbf539c42013-10-05 18:16:02 +00001296
1297/*
1298** Find (an approximate) sum of two LogEst values. This computation is
1299** not a simple "+" operator because LogEst is stored as a logarithmic
1300** value.
1301**
1302*/
1303LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
1304 static const unsigned char x[] = {
1305 10, 10, /* 0,1 */
1306 9, 9, /* 2,3 */
1307 8, 8, /* 4,5 */
1308 7, 7, 7, /* 6,7,8 */
1309 6, 6, 6, /* 9,10,11 */
1310 5, 5, 5, /* 12-14 */
1311 4, 4, 4, 4, /* 15-18 */
1312 3, 3, 3, 3, 3, 3, /* 19-24 */
1313 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
1314 };
1315 if( a>=b ){
1316 if( a>b+49 ) return a;
1317 if( a>b+31 ) return a+1;
1318 return a+x[a-b];
1319 }else{
1320 if( b>a+49 ) return b;
1321 if( b>a+31 ) return b+1;
1322 return b+x[b-a];
1323 }
1324}
1325
1326/*
drh224155d2014-04-30 13:19:09 +00001327** Convert an integer into a LogEst. In other words, compute an
1328** approximation for 10*log2(x).
drhbf539c42013-10-05 18:16:02 +00001329*/
1330LogEst sqlite3LogEst(u64 x){
1331 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1332 LogEst y = 40;
1333 if( x<8 ){
1334 if( x<2 ) return 0;
1335 while( x<8 ){ y -= 10; x <<= 1; }
1336 }else{
1337 while( x>255 ){ y += 40; x >>= 4; }
1338 while( x>15 ){ y += 10; x >>= 1; }
1339 }
1340 return a[x&7] + y - 10;
1341}
1342
1343#ifndef SQLITE_OMIT_VIRTUALTABLE
1344/*
1345** Convert a double into a LogEst
1346** In other words, compute an approximation for 10*log2(x).
1347*/
1348LogEst sqlite3LogEstFromDouble(double x){
1349 u64 a;
1350 LogEst e;
1351 assert( sizeof(x)==8 && sizeof(a)==8 );
1352 if( x<=1 ) return 0;
1353 if( x<=2000000000 ) return sqlite3LogEst((u64)x);
1354 memcpy(&a, &x, 8);
1355 e = (a>>52) - 1022;
1356 return e*10;
1357}
1358#endif /* SQLITE_OMIT_VIRTUALTABLE */
1359
1360/*
1361** Convert a LogEst into an integer.
1362*/
1363u64 sqlite3LogEstToInt(LogEst x){
1364 u64 n;
1365 if( x<10 ) return 1;
1366 n = x%10;
1367 x /= 10;
1368 if( n>=5 ) n -= 2;
1369 else if( n>=1 ) n -= 1;
drh47676fe2013-12-05 16:41:55 +00001370 if( x>=3 ){
1371 return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
1372 }
drhbf539c42013-10-05 18:16:02 +00001373 return (n+8)>>(3-x);
1374}