Thanks to visit codestin.com
Credit goes to chromium.googlesource.com

blob: 8e4fd516efb01aaa33a72272f4aa435077ac276d [file] [log] [blame]
drhc81c11f2009-11-10 01:30:521/*
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>
drhef9f7192020-01-17 19:14:0820#ifndef SQLITE_OMIT_FLOATING_POINT
drh7e6dc5d2019-05-10 12:14:5121#include <math.h>
drhef9f7192020-01-17 19:14:0822#endif
drhc81c11f2009-11-10 01:30:5223
24/*
drhce059e52019-04-05 17:22:5025** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
larrybrbc917382023-06-07 08:40:3126** or to bypass normal error detection during testing in order to let
27** execute proceed further downstream.
drhc007f612014-05-16 14:17:0128**
drhce059e52019-04-05 17:22:5029** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0). The
30** sqlite3FaultSim() function only returns non-zero during testing.
drhc007f612014-05-16 14:17:0131**
drhce059e52019-04-05 17:22:5032** During testing, if the test harness has set a fault-sim callback using
33** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
34** each call to sqlite3FaultSim() is relayed to that application-supplied
35** callback and the integer return value form the application-supplied
36** callback is returned by sqlite3FaultSim().
37**
38** The integer argument to sqlite3FaultSim() is a code to identify which
39** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
40** should have a unique code. To prevent legacy testing applications from
41** breaking, the codes should not be changed or reused.
drhc007f612014-05-16 14:17:0142*/
drhd12602a2016-12-07 15:49:0243#ifndef SQLITE_UNTESTABLE
drhc007f612014-05-16 14:17:0144int sqlite3FaultSim(int iTest){
45 int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
46 return xCallback ? xCallback(iTest) : SQLITE_OK;
47}
48#endif
49
drh85c8f292010-01-13 17:39:5350#ifndef SQLITE_OMIT_FLOATING_POINT
drhc81c11f2009-11-10 01:30:5251/*
52** Return true if the floating point value is Not a Number (NaN).
drhe534c7b2021-09-06 11:44:1953**
54** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
55** Otherwise, we have our own implementation that works on most systems.
drhc81c11f2009-11-10 01:30:5256*/
57int sqlite3IsNaN(double x){
drhe534c7b2021-09-06 11:44:1958 int rc; /* The value return */
59#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
drh05921222019-05-30 00:46:3760 u64 y;
61 memcpy(&y,&x,sizeof(y));
drhe534c7b2021-09-06 11:44:1962 rc = IsNaN(y);
63#else
64 rc = isnan(x);
65#endif /* HAVE_ISNAN */
66 testcase( rc );
67 return rc;
drhc81c11f2009-11-10 01:30:5268}
drh85c8f292010-01-13 17:39:5369#endif /* SQLITE_OMIT_FLOATING_POINT */
drhc81c11f2009-11-10 01:30:5270
drh5ed044e2024-03-19 10:16:1771#ifndef SQLITE_OMIT_FLOATING_POINT
72/*
73** Return true if the floating point value is NaN or +Inf or -Inf.
74*/
75int sqlite3IsOverflow(double x){
76 int rc; /* The value return */
77 u64 y;
78 memcpy(&y,&x,sizeof(y));
79 rc = IsOvfl(y);
80 return rc;
81}
82#endif /* SQLITE_OMIT_FLOATING_POINT */
83
drhc81c11f2009-11-10 01:30:5284/*
85** Compute a string length that is limited to what can be stored in
86** lower 30 bits of a 32-bit signed integer.
87**
88** The value returned will never be negative. Nor will it ever be greater
89** than the actual length of the string. For very long strings (greater
90** than 1GiB) the value returned might be less than the true string length.
91*/
92int sqlite3Strlen30(const char *z){
drhc81c11f2009-11-10 01:30:5293 if( z==0 ) return 0;
drh1116bf12015-06-30 03:18:3394 return 0x3fffffff & (int)strlen(z);
drhc81c11f2009-11-10 01:30:5295}
96
97/*
larrybrbc917382023-06-07 08:40:3198** Return the declared type of a column. Or return zDflt if the column
drhd7564862016-03-22 20:05:0999** has no declared type.
100**
101** The column type is an extra string stored after the zero-terminator on
102** the column name if and only if the COLFLAG_HASTYPE flag is set.
drh94eaafa2016-02-29 15:53:11103*/
drhd7564862016-03-22 20:05:09104char *sqlite3ColumnType(Column *pCol, char *zDflt){
drh77441fa2021-07-30 18:39:59105 if( pCol->colFlags & COLFLAG_HASTYPE ){
drhcf9d36d2021-08-02 18:03:43106 return pCol->zCnName + strlen(pCol->zCnName) + 1;
drhb70f2ea2021-08-18 12:05:22107 }else if( pCol->eCType ){
108 assert( pCol->eCType<=SQLITE_N_STDTYPE );
109 return (char*)sqlite3StdType[pCol->eCType-1];
drh77441fa2021-07-30 18:39:59110 }else{
111 return zDflt;
112 }
drh94eaafa2016-02-29 15:53:11113}
114
115/*
drh80fbee02016-03-21 11:57:13116** Helper function for sqlite3Error() - called rarely. Broken out into
117** a separate routine to avoid unnecessary register saves on entry to
118** sqlite3Error().
drh13f40da2014-08-22 18:00:11119*/
drh8d2f41c2016-03-21 11:38:01120static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
121 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
122 sqlite3SystemError(db, err_code);
123}
drh80fbee02016-03-21 11:57:13124
125/*
126** Set the current error code to err_code and clear any prior error message.
127** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
128** that would be appropriate.
129*/
drh13f40da2014-08-22 18:00:11130void sqlite3Error(sqlite3 *db, int err_code){
131 assert( db!=0 );
132 db->errCode = err_code;
drhf62641e2021-12-24 20:22:13133 if( err_code || db->pErr ){
134 sqlite3ErrorFinish(db, err_code);
135 }else{
136 db->errByteOffset = -1;
137 }
drh13f40da2014-08-22 18:00:11138}
139
140/*
drh88efc792021-01-01 18:23:56141** The equivalent of sqlite3Error(db, SQLITE_OK). Clear the error state
142** and error message.
143*/
144void sqlite3ErrorClear(sqlite3 *db){
145 assert( db!=0 );
146 db->errCode = SQLITE_OK;
drhf62641e2021-12-24 20:22:13147 db->errByteOffset = -1;
drh88efc792021-01-01 18:23:56148 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
149}
150
151/*
drh1b9f2142016-03-17 16:01:23152** Load the sqlite3.iSysErrno field if that is an appropriate thing
153** to do based on the SQLite error code in rc.
154*/
155void sqlite3SystemError(sqlite3 *db, int rc){
156 if( rc==SQLITE_IOERR_NOMEM ) return;
stephan09e6c822023-12-22 15:41:13157#if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL)
dan90234442021-09-10 21:28:56158 if( rc==SQLITE_IOERR_IN_PAGE ){
159 int ii;
160 int iErr;
161 sqlite3BtreeEnterAll(db);
162 for(ii=0; ii<db->nDb; ii++){
163 if( db->aDb[ii].pBt ){
164 iErr = sqlite3PagerWalSystemErrno(sqlite3BtreePager(db->aDb[ii].pBt));
165 if( iErr ){
166 db->iSysErrno = iErr;
167 }
168 }
169 }
170 sqlite3BtreeLeaveAll(db);
171 return;
172 }
173#endif
drh1b9f2142016-03-17 16:01:23174 rc &= 0xff;
175 if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
176 db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
177 }
178}
179
180/*
drhc81c11f2009-11-10 01:30:52181** Set the most recent error code and error string for the sqlite
182** handle "db". The error code is set to "err_code".
183**
184** If it is not NULL, string zFormat specifies the format of the
drhf62641e2021-12-24 20:22:13185** error string. zFormat and any string tokens that follow it are
186** assumed to be encoded in UTF-8.
drhc81c11f2009-11-10 01:30:52187**
188** To clear the most recent error for sqlite handle "db", sqlite3Error
189** should be called with err_code set to SQLITE_OK and zFormat set
190** to NULL.
191*/
drh13f40da2014-08-22 18:00:11192void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
drha3cc0072013-12-13 16:23:55193 assert( db!=0 );
194 db->errCode = err_code;
drh8d2f41c2016-03-21 11:38:01195 sqlite3SystemError(db, err_code);
drh13f40da2014-08-22 18:00:11196 if( zFormat==0 ){
197 sqlite3Error(db, err_code);
198 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
drha3cc0072013-12-13 16:23:55199 char *z;
200 va_list ap;
201 va_start(ap, zFormat);
202 z = sqlite3VMPrintf(db, zFormat, ap);
203 va_end(ap);
204 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
drhc81c11f2009-11-10 01:30:52205 }
206}
207
208/*
drhf84cbd12023-01-12 13:25:48209** Check for interrupts and invoke progress callback.
210*/
211void sqlite3ProgressCheck(Parse *p){
212 sqlite3 *db = p->db;
213 if( AtomicLoad(&db->u1.isInterrupted) ){
214 p->nErr++;
215 p->rc = SQLITE_INTERRUPT;
216 }
217#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
stephan0d066bc2023-08-28 12:06:38218 if( db->xProgress ){
219 if( p->rc==SQLITE_INTERRUPT ){
220 p->nProgressSteps = 0;
221 }else if( (++p->nProgressSteps)>=db->nProgressOps ){
222 if( db->xProgress(db->pProgressArg) ){
223 p->nErr++;
224 p->rc = SQLITE_INTERRUPT;
225 }
226 p->nProgressSteps = 0;
drh2fc9dc92023-01-12 19:51:49227 }
drhf84cbd12023-01-12 13:25:48228 }
229#endif
230}
231
232/*
drhc81c11f2009-11-10 01:30:52233** Add an error message to pParse->zErrMsg and increment pParse->nErr.
drhc81c11f2009-11-10 01:30:52234**
drh13f40da2014-08-22 18:00:11235** This function should be used to report any error that occurs while
drhc81c11f2009-11-10 01:30:52236** compiling an SQL statement (i.e. within sqlite3_prepare()). The
237** last thing the sqlite3_prepare() function does is copy the error
238** stored by this function into the database handle using sqlite3Error().
drh13f40da2014-08-22 18:00:11239** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
240** during statement execution (sqlite3_step() etc.).
drhc81c11f2009-11-10 01:30:52241*/
242void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
drha7564662010-02-22 19:32:31243 char *zMsg;
drhc81c11f2009-11-10 01:30:52244 va_list ap;
245 sqlite3 *db = pParse->db;
drhc692df22022-01-24 15:34:55246 assert( db!=0 );
drh173b4182022-09-02 17:25:25247 assert( db->pParse==pParse || db->pParse->pToplevel==pParse );
drhf62641e2021-12-24 20:22:13248 db->errByteOffset = -2;
drhc81c11f2009-11-10 01:30:52249 va_start(ap, zFormat);
drha7564662010-02-22 19:32:31250 zMsg = sqlite3VMPrintf(db, zFormat, ap);
drhc81c11f2009-11-10 01:30:52251 va_end(ap);
drhf62641e2021-12-24 20:22:13252 if( db->errByteOffset<-1 ) db->errByteOffset = -1;
drha7564662010-02-22 19:32:31253 if( db->suppressErr ){
254 sqlite3DbFree(db, zMsg);
drh0c7d3d32022-01-24 16:47:12255 if( db->mallocFailed ){
256 pParse->nErr++;
257 pParse->rc = SQLITE_NOMEM;
258 }
drha7564662010-02-22 19:32:31259 }else{
260 pParse->nErr++;
261 sqlite3DbFree(db, pParse->zErrMsg);
262 pParse->zErrMsg = zMsg;
263 pParse->rc = SQLITE_ERROR;
drh46a31cd2019-11-09 14:38:58264 pParse->pWith = 0;
drha7564662010-02-22 19:32:31265 }
drhc81c11f2009-11-10 01:30:52266}
267
268/*
drhc3dcdba2019-04-09 21:32:46269** If database connection db is currently parsing SQL, then transfer
270** error code errCode to that parser if the parser has not already
271** encountered some other kind of error.
272*/
273int sqlite3ErrorToParser(sqlite3 *db, int errCode){
274 Parse *pParse;
275 if( db==0 || (pParse = db->pParse)==0 ) return errCode;
276 pParse->rc = errCode;
277 pParse->nErr++;
278 return errCode;
279}
280
281/*
drhc81c11f2009-11-10 01:30:52282** Convert an SQL-style quoted string into a normal string by removing
283** the quote characters. The conversion is done in-place. If the
284** input does not begin with a quote character, then this routine
285** is a no-op.
286**
287** The input string must be zero-terminated. A new zero-terminator
288** is added to the dequoted string.
289**
290** The return value is -1 if no dequoting occurs or the length of the
291** dequoted string, exclusive of the zero terminator, if dequoting does
292** occur.
293**
drh51d35b02019-01-11 13:32:23294** 2002-02-14: This routine is extended to remove MS-Access style
peter.d.reid60ec9142014-09-06 16:39:46295** brackets from around identifiers. For example: "[a-b-c]" becomes
drhc81c11f2009-11-10 01:30:52296** "a-b-c".
297*/
drh244b9d62016-04-11 19:01:08298void sqlite3Dequote(char *z){
drhc81c11f2009-11-10 01:30:52299 char quote;
300 int i, j;
drh244b9d62016-04-11 19:01:08301 if( z==0 ) return;
drhc81c11f2009-11-10 01:30:52302 quote = z[0];
drh244b9d62016-04-11 19:01:08303 if( !sqlite3Isquote(quote) ) return;
304 if( quote=='[' ) quote = ']';
drh9ccd8652013-09-13 16:36:46305 for(i=1, j=0;; i++){
306 assert( z[i] );
drhc81c11f2009-11-10 01:30:52307 if( z[i]==quote ){
308 if( z[i+1]==quote ){
309 z[j++] = quote;
310 i++;
311 }else{
312 break;
313 }
314 }else{
315 z[j++] = z[i];
316 }
317 }
318 z[j] = 0;
drhc81c11f2009-11-10 01:30:52319}
drh51d35b02019-01-11 13:32:23320void sqlite3DequoteExpr(Expr *p){
drhf9751072021-10-07 13:40:29321 assert( !ExprHasProperty(p, EP_IntValue) );
drh51d35b02019-01-11 13:32:23322 assert( sqlite3Isquote(p->u.zToken[0]) );
323 p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
324 sqlite3Dequote(p->u.zToken);
325}
drhc81c11f2009-11-10 01:30:52326
drh40aced52016-01-22 17:48:09327/*
dan8374f7d2024-01-22 19:38:55328** Expression p is a QNUMBER (quoted number). Dequote the value in p->u.zToken
329** and set the type to INTEGER or FLOAT. "Quoted" integers or floats are those
330** that contain '_' characters that must be removed before further processing.
dan3eae6662024-01-20 16:18:04331*/
dan406eb5a2024-01-23 11:20:58332void sqlite3DequoteNumber(Parse *pParse, Expr *p){
drh8597eee2024-02-28 01:12:21333 assert( p!=0 || pParse->db->mallocFailed );
dan3eae6662024-01-20 16:18:04334 if( p ){
335 const char *pIn = p->u.zToken;
336 char *pOut = p->u.zToken;
dan406eb5a2024-01-23 11:20:58337 int bHex = (pIn[0]=='0' && (pIn[1]=='x' || pIn[1]=='X'));
drh8597eee2024-02-28 01:12:21338 int iValue;
dan3eae6662024-01-20 16:18:04339 assert( p->op==TK_QNUMBER );
340 p->op = TK_INTEGER;
341 do {
342 if( *pIn!=SQLITE_DIGIT_SEPARATOR ){
343 *pOut++ = *pIn;
344 if( *pIn=='e' || *pIn=='E' || *pIn=='.' ) p->op = TK_FLOAT;
dan406eb5a2024-01-23 11:20:58345 }else{
346 if( (bHex==0 && (!sqlite3Isdigit(pIn[-1]) || !sqlite3Isdigit(pIn[1])))
347 || (bHex==1 && (!sqlite3Isxdigit(pIn[-1]) || !sqlite3Isxdigit(pIn[1])))
348 ){
349 sqlite3ErrorMsg(pParse, "unrecognized token: \"%s\"", p->u.zToken);
350 }
dan3eae6662024-01-20 16:18:04351 }
352 }while( *pIn++ );
dan406eb5a2024-01-23 11:20:58353 if( bHex ) p->op = TK_INTEGER;
drh8597eee2024-02-28 01:12:21354
355 /* tag-20240227-a: If after dequoting, the number is an integer that
356 ** fits in 32 bits, then it must be converted into EP_IntValue. Other
357 ** parts of the code expect this. See also tag-20240227-b. */
358 if( p->op==TK_INTEGER && sqlite3GetInt32(p->u.zToken, &iValue) ){
359 p->u.iValue = iValue;
360 p->flags |= EP_IntValue;
361 }
dan3eae6662024-01-20 16:18:04362 }
363}
364
365/*
drh77441fa2021-07-30 18:39:59366** If the input token p is quoted, try to adjust the token to remove
367** the quotes. This is not always possible:
368**
369** "abc" -> abc
370** "ab""cd" -> (not possible because of the interior "")
371**
372** Remove the quotes if possible. This is a optimization. The overall
373** system should still return the correct answer even if this routine
374** is always a no-op.
375*/
376void sqlite3DequoteToken(Token *p){
drh15482bc2021-08-06 15:26:01377 unsigned int i;
drh77441fa2021-07-30 18:39:59378 if( p->n<2 ) return;
379 if( !sqlite3Isquote(p->z[0]) ) return;
380 for(i=1; i<p->n-1; i++){
381 if( sqlite3Isquote(p->z[i]) ) return;
382 }
383 p->n -= 2;
384 p->z++;
385}
386
387/*
drh40aced52016-01-22 17:48:09388** Generate a Token object from a string
389*/
390void sqlite3TokenInit(Token *p, char *z){
391 p->z = z;
392 p->n = sqlite3Strlen30(z);
393}
394
drhc81c11f2009-11-10 01:30:52395/* Convenient short-hand */
396#define UpperToLower sqlite3UpperToLower
397
398/*
399** Some systems have stricmp(). Others have strcasecmp(). Because
400** there is no consistency, we will define our own.
drh9f129f42010-08-31 15:27:32401**
drh0299b402012-03-19 17:42:46402** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
403** sqlite3_strnicmp() APIs allow applications and extensions to compare
404** the contents of two buffers containing UTF-8 strings in a
405** case-independent fashion, using the same definition of "case
406** independence" that SQLite uses internally when comparing identifiers.
drhc81c11f2009-11-10 01:30:52407*/
drh3fa97302012-02-22 16:58:36408int sqlite3_stricmp(const char *zLeft, const char *zRight){
drh9ca95732014-10-24 00:35:58409 if( zLeft==0 ){
410 return zRight ? -1 : 0;
411 }else if( zRight==0 ){
412 return 1;
413 }
drh80738d92016-02-15 00:34:16414 return sqlite3StrICmp(zLeft, zRight);
415}
416int sqlite3StrICmp(const char *zLeft, const char *zRight){
417 unsigned char *a, *b;
drh7e427332019-04-17 11:34:44418 int c, x;
drhc81c11f2009-11-10 01:30:52419 a = (unsigned char *)zLeft;
420 b = (unsigned char *)zRight;
drh80738d92016-02-15 00:34:16421 for(;;){
drh7e427332019-04-17 11:34:44422 c = *a;
423 x = *b;
424 if( c==x ){
425 if( c==0 ) break;
426 }else{
427 c = (int)UpperToLower[c] - (int)UpperToLower[x];
428 if( c ) break;
429 }
drh80738d92016-02-15 00:34:16430 a++;
431 b++;
432 }
433 return c;
drhc81c11f2009-11-10 01:30:52434}
435int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
436 register unsigned char *a, *b;
drh9ca95732014-10-24 00:35:58437 if( zLeft==0 ){
438 return zRight ? -1 : 0;
439 }else if( zRight==0 ){
440 return 1;
441 }
drhc81c11f2009-11-10 01:30:52442 a = (unsigned char *)zLeft;
443 b = (unsigned char *)zRight;
444 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
445 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
446}
447
448/*
drhd44390c2020-04-06 18:16:31449** Compute an 8-bit hash on a string that is insensitive to case differences
450*/
451u8 sqlite3StrIHash(const char *z){
452 u8 h = 0;
453 if( z==0 ) return 0;
454 while( z[0] ){
455 h += UpperToLower[(unsigned char)z[0]];
456 z++;
457 }
458 return h;
459}
460
drh1790ccb2023-07-05 14:42:50461/* Double-Double multiplication. (x[0],x[1]) *= (y,yy)
drh02a43f62017-12-26 14:46:20462**
drhaa4356d2023-07-03 18:18:35463** Reference:
464** T. J. Dekker, "A Floating-Point Technique for Extending the
465** Available Precision". 1971-07-26.
drh02a43f62017-12-26 14:46:20466*/
drhefd0cf82023-07-05 22:05:18467static void dekkerMul2(volatile double *x, double y, double yy){
468 /*
469 ** The "volatile" keywords on parameter x[] and on local variables
470 ** below are needed force intermediate results to be truncated to
471 ** binary64 rather than be carried around in an extended-precision
472 ** format. The truncation is necessary for the Dekker algorithm to
473 ** work. Intel x86 floating point might omit the truncation without
474 ** the use of volatile.
475 */
476 volatile double tx, ty, p, q, c, cc;
477 double hx, hy;
drhaa4356d2023-07-03 18:18:35478 u64 m;
drhefd0cf82023-07-05 22:05:18479 memcpy(&m, (void*)&x[0], 8);
drh4c40b7b2023-07-08 17:42:24480 m &= 0xfffffffffc000000LL;
drhaa4356d2023-07-03 18:18:35481 memcpy(&hx, &m, 8);
drh1790ccb2023-07-05 14:42:50482 tx = x[0] - hx;
drhaa4356d2023-07-03 18:18:35483 memcpy(&m, &y, 8);
drh4c40b7b2023-07-08 17:42:24484 m &= 0xfffffffffc000000LL;
drhaa4356d2023-07-03 18:18:35485 memcpy(&hy, &m, 8);
486 ty = y - hy;
487 p = hx*hy;
488 q = hx*ty + tx*hy;
489 c = p+q;
490 cc = p - c + q + tx*ty;
drh1790ccb2023-07-05 14:42:50491 cc = x[0]*yy + x[1]*y + cc;
492 x[0] = c + cc;
drh85ca6d72023-07-05 15:34:30493 x[1] = c - x[0];
494 x[1] += cc;
drh02a43f62017-12-26 14:46:20495}
496
497/*
drh9339da12010-09-30 00:50:49498** The string z[] is an text representation of a real number.
drh025586a2010-09-30 17:33:11499** Convert this string to a double and write it into *pResult.
drhc81c11f2009-11-10 01:30:52500**
drh9339da12010-09-30 00:50:49501** The string z[] is length bytes in length (bytes, not characters) and
502** uses the encoding enc. The string is not necessarily zero-terminated.
drhc81c11f2009-11-10 01:30:52503**
drh9339da12010-09-30 00:50:49504** Return TRUE if the result is a valid real number (or integer) and FALSE
drh8a3884e2019-05-29 21:18:27505** if the string is empty or contains extraneous text. More specifically
506** return
507** 1 => The input string is a pure integer
508** 2 or more => The input has a decimal point or eNNN clause
drh9a278222019-06-07 22:26:08509** 0 or less => The input string is not a valid number
larrybrbc917382023-06-07 08:40:31510** -1 => Not a valid number, but has a valid prefix which
drh9a278222019-06-07 22:26:08511** includes a decimal point and/or an eNNN clause
drh8a3884e2019-05-29 21:18:27512**
513** Valid numbers are in one of these formats:
drh025586a2010-09-30 17:33:11514**
515** [+-]digits[E[+-]digits]
516** [+-]digits.[digits][E[+-]digits]
517** [+-].digits[E[+-]digits]
518**
519** Leading and trailing whitespace is ignored for the purpose of determining
520** validity.
521**
522** If some prefix of the input string is a valid number, this routine
523** returns FALSE but it still converts the prefix and writes the result
524** into *pResult.
drhc81c11f2009-11-10 01:30:52525*/
mistachkin6dcf9a42019-10-10 23:58:16526#if defined(_MSC_VER)
527#pragma warning(disable : 4756)
528#endif
drh9339da12010-09-30 00:50:49529int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
drhc81c11f2009-11-10 01:30:52530#ifndef SQLITE_OMIT_FLOATING_POINT
drh0e5fba72013-03-20 12:04:29531 int incr;
drhe3a4f2c2019-12-13 23:38:57532 const char *zEnd;
drhc81c11f2009-11-10 01:30:52533 /* sign * significand * (10 ^ (esign * exponent)) */
drh025586a2010-09-30 17:33:11534 int sign = 1; /* sign of significand */
drhaa4356d2023-07-03 18:18:35535 u64 s = 0; /* significand */
drh025586a2010-09-30 17:33:11536 int d = 0; /* adjust exponent for shifting decimal point */
537 int esign = 1; /* sign of exponent */
538 int e = 0; /* exponent */
539 int eValid = 1; /* True exponent is either not used or is well-formed */
drhc2b893a2019-05-25 18:17:53540 int nDigit = 0; /* Number of digits processed */
drh8a3884e2019-05-29 21:18:27541 int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */
drh87036422024-12-07 19:06:25542 u64 s2; /* round-tripped significand */
drhe8b2c922024-10-01 20:29:43543 double rr[2];
drhc81c11f2009-11-10 01:30:52544
drh0e5fba72013-03-20 12:04:29545 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
drh025586a2010-09-30 17:33:11546 *pResult = 0.0; /* Default return value, in case of an error */
drhe3a4f2c2019-12-13 23:38:57547 if( length==0 ) return 0;
drh025586a2010-09-30 17:33:11548
drh0e5fba72013-03-20 12:04:29549 if( enc==SQLITE_UTF8 ){
550 incr = 1;
drhe3a4f2c2019-12-13 23:38:57551 zEnd = z + length;
drh0e5fba72013-03-20 12:04:29552 }else{
553 int i;
554 incr = 2;
drh87969b22020-01-08 12:17:46555 length &= ~1;
drh0e5fba72013-03-20 12:04:29556 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
drh84422db2019-05-30 13:47:10557 testcase( enc==SQLITE_UTF16LE );
558 testcase( enc==SQLITE_UTF16BE );
drh0e5fba72013-03-20 12:04:29559 for(i=3-enc; i<length && z[i]==0; i+=2){}
drh8a3884e2019-05-29 21:18:27560 if( i<length ) eType = -100;
drhad975d52016-04-27 15:24:13561 zEnd = &z[i^1];
drh0e5fba72013-03-20 12:04:29562 z += (enc&1);
563 }
drh9339da12010-09-30 00:50:49564
drhc81c11f2009-11-10 01:30:52565 /* skip leading spaces */
drh9339da12010-09-30 00:50:49566 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
drh025586a2010-09-30 17:33:11567 if( z>=zEnd ) return 0;
drh9339da12010-09-30 00:50:49568
drhc81c11f2009-11-10 01:30:52569 /* get sign of significand */
570 if( *z=='-' ){
571 sign = -1;
drh9339da12010-09-30 00:50:49572 z+=incr;
drhc81c11f2009-11-10 01:30:52573 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49574 z+=incr;
drhc81c11f2009-11-10 01:30:52575 }
drh9339da12010-09-30 00:50:49576
drhc81c11f2009-11-10 01:30:52577 /* copy max significant digits to significand */
drhc2b893a2019-05-25 18:17:53578 while( z<zEnd && sqlite3Isdigit(*z) ){
drhc81c11f2009-11-10 01:30:52579 s = s*10 + (*z - '0');
drhc2b893a2019-05-25 18:17:53580 z+=incr; nDigit++;
drhaa4356d2023-07-03 18:18:35581 if( s>=((LARGEST_UINT64-9)/10) ){
drhc2b893a2019-05-25 18:17:53582 /* skip non-significant significand digits
583 ** (increase exponent by d to shift decimal left) */
584 while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; }
585 }
drhc81c11f2009-11-10 01:30:52586 }
drh9339da12010-09-30 00:50:49587 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52588
589 /* if decimal point is present */
590 if( *z=='.' ){
drh9339da12010-09-30 00:50:49591 z+=incr;
drh8a3884e2019-05-29 21:18:27592 eType++;
drhc81c11f2009-11-10 01:30:52593 /* copy digits from after decimal to significand
594 ** (decrease exponent by d to shift decimal right) */
drh15af62a2016-04-26 23:14:45595 while( z<zEnd && sqlite3Isdigit(*z) ){
drhaa4356d2023-07-03 18:18:35596 if( s<((LARGEST_UINT64-9)/10) ){
drh15af62a2016-04-26 23:14:45597 s = s*10 + (*z - '0');
598 d--;
drhc2b893a2019-05-25 18:17:53599 nDigit++;
drh15af62a2016-04-26 23:14:45600 }
drhc2b893a2019-05-25 18:17:53601 z+=incr;
drhc81c11f2009-11-10 01:30:52602 }
drhc81c11f2009-11-10 01:30:52603 }
drh9339da12010-09-30 00:50:49604 if( z>=zEnd ) goto do_atof_calc;
drhc81c11f2009-11-10 01:30:52605
606 /* if exponent is present */
607 if( *z=='e' || *z=='E' ){
drh9339da12010-09-30 00:50:49608 z+=incr;
drh025586a2010-09-30 17:33:11609 eValid = 0;
drh8a3884e2019-05-29 21:18:27610 eType++;
drhad975d52016-04-27 15:24:13611
larrybrbc917382023-06-07 08:40:31612 /* This branch is needed to avoid a (harmless) buffer overread. The
drhad975d52016-04-27 15:24:13613 ** special comment alerts the mutation tester that the correct answer
614 ** is obtained even if the branch is omitted */
615 if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
616
drhc81c11f2009-11-10 01:30:52617 /* get sign of exponent */
618 if( *z=='-' ){
619 esign = -1;
drh9339da12010-09-30 00:50:49620 z+=incr;
drhc81c11f2009-11-10 01:30:52621 }else if( *z=='+' ){
drh9339da12010-09-30 00:50:49622 z+=incr;
drhc81c11f2009-11-10 01:30:52623 }
624 /* copy digits to exponent */
drh9339da12010-09-30 00:50:49625 while( z<zEnd && sqlite3Isdigit(*z) ){
drh57db4a72011-10-17 20:41:46626 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
drh9339da12010-09-30 00:50:49627 z+=incr;
drh025586a2010-09-30 17:33:11628 eValid = 1;
drhc81c11f2009-11-10 01:30:52629 }
630 }
631
drh025586a2010-09-30 17:33:11632 /* skip trailing spaces */
drhc6daa012016-04-27 02:35:03633 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
drh025586a2010-09-30 17:33:11634
drh9339da12010-09-30 00:50:49635do_atof_calc:
drhaa4356d2023-07-03 18:18:35636 /* Zero is a special case */
637 if( s==0 ){
638 *pResult = sign<0 ? -0.0 : +0.0;
639 goto atof_return;
640 }
641
drhc81c11f2009-11-10 01:30:52642 /* adjust exponent by d, and update sign */
643 e = (e*esign) + d;
drhaa4356d2023-07-03 18:18:35644
645 /* Try to adjust the exponent to make it smaller */
drh1a4b2112024-12-07 14:48:55646 while( e>0 && s<((LARGEST_UINT64-0x7ff)/10) ){
drhaa4356d2023-07-03 18:18:35647 s *= 10;
648 e--;
649 }
650 while( e<0 && (s%10)==0 ){
651 s /= 10;
652 e++;
drhc81c11f2009-11-10 01:30:52653 }
654
drhe8b2c922024-10-01 20:29:43655 rr[0] = (double)s;
drh9f53d0c2024-12-07 19:57:30656 assert( sizeof(s2)==sizeof(rr[0]) );
drh54f96dc2024-12-09 11:47:28657#ifdef SQLITE_DEBUG
658 rr[1] = 18446744073709549568.0;
659 memcpy(&s2, &rr[1], sizeof(s2));
660 assert( s2==0x43efffffffffffffLL );
661#endif
662 /* Largest double that can be safely converted to u64
663 ** vvvvvvvvvvvvvvvvvvvvvv */
664 if( rr[0]<=18446744073709549568.0 ){
drh9f53d0c2024-12-07 19:57:30665 s2 = (u64)rr[0];
666 rr[1] = s>=s2 ? (double)(s - s2) : -(double)(s2 - s);
667 }else{
drh1a4b2112024-12-07 14:48:55668 rr[1] = 0.0;
669 }
drh9f53d0c2024-12-07 19:57:30670 assert( rr[1]<=1.0e-10*rr[0] ); /* Equal only when rr[0]==0.0 */
drh87036422024-12-07 19:06:25671
drhe8b2c922024-10-01 20:29:43672 if( e>0 ){
673 while( e>=100 ){
674 e -= 100;
675 dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83);
676 }
677 while( e>=10 ){
678 e -= 10;
679 dekkerMul2(rr, 1.0e+10, 0.0);
680 }
681 while( e>=1 ){
682 e -= 1;
683 dekkerMul2(rr, 1.0e+01, 0.0);
drhcbaef882023-08-01 19:10:30684 }
drhaa4356d2023-07-03 18:18:35685 }else{
drhe8b2c922024-10-01 20:29:43686 while( e<=-100 ){
687 e += 100;
688 dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117);
drhc81c11f2009-11-10 01:30:52689 }
drhe8b2c922024-10-01 20:29:43690 while( e<=-10 ){
691 e += 10;
692 dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27);
693 }
694 while( e<=-1 ){
695 e += 1;
696 dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18);
697 }
drhc81c11f2009-11-10 01:30:52698 }
drhe8b2c922024-10-01 20:29:43699 *pResult = rr[0]+rr[1];
700 if( sqlite3IsNaN(*pResult) ) *pResult = 1e300*1e300;
drhaa4356d2023-07-03 18:18:35701 if( sign<0 ) *pResult = -*pResult;
702 assert( !sqlite3IsNaN(*pResult) );
drhc81c11f2009-11-10 01:30:52703
drhaa4356d2023-07-03 18:18:35704atof_return:
larrybrbc917382023-06-07 08:40:31705 /* return true if number and no extra non-whitespace characters after */
drh9a278222019-06-07 22:26:08706 if( z==zEnd && nDigit>0 && eValid && eType>0 ){
707 return eType;
drh378a7d32019-06-10 23:45:10708 }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){
drh9a278222019-06-07 22:26:08709 return -1;
710 }else{
711 return 0;
712 }
drhc81c11f2009-11-10 01:30:52713#else
shaneh5f1d6b62010-09-30 16:51:25714 return !sqlite3Atoi64(z, pResult, length, enc);
drhc81c11f2009-11-10 01:30:52715#endif /* SQLITE_OMIT_FLOATING_POINT */
716}
mistachkin6dcf9a42019-10-10 23:58:16717#if defined(_MSC_VER)
718#pragma warning(default : 4756)
719#endif
drhc81c11f2009-11-10 01:30:52720
721/*
drhfbde3f52023-01-03 18:51:18722** Render an signed 64-bit integer as text. Store the result in zOut[] and
723** return the length of the string that was stored, in bytes. The value
724** returned does not include the zero terminator at the end of the output
725** string.
drh82b0f102020-07-21 18:25:19726**
727** The caller must ensure that zOut[] is at least 21 bytes in size.
728*/
drhfbde3f52023-01-03 18:51:18729int sqlite3Int64ToText(i64 v, char *zOut){
drh82b0f102020-07-21 18:25:19730 int i;
731 u64 x;
732 char zTemp[22];
733 if( v<0 ){
drh8deae5a2020-07-29 12:23:20734 x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v;
drh82b0f102020-07-21 18:25:19735 }else{
736 x = v;
737 }
738 i = sizeof(zTemp)-2;
739 zTemp[sizeof(zTemp)-1] = 0;
drh6b507422023-04-12 18:57:50740 while( 1 /*exit-by-break*/ ){
741 zTemp[i] = (x%10) + '0';
drh82b0f102020-07-21 18:25:19742 x = x/10;
drh6b507422023-04-12 18:57:50743 if( x==0 ) break;
744 i--;
745 };
746 if( v<0 ) zTemp[--i] = '-';
747 memcpy(zOut, &zTemp[i], sizeof(zTemp)-i);
748 return sizeof(zTemp)-1-i;
drh82b0f102020-07-21 18:25:19749}
750
751/*
drhc81c11f2009-11-10 01:30:52752** Compare the 19-character string zNum against the text representation
753** value 2^63: 9223372036854775808. Return negative, zero, or positive
754** if zNum is less than, equal to, or greater than the string.
shaneh5f1d6b62010-09-30 16:51:25755** Note that zNum must contain exactly 19 characters.
drhc81c11f2009-11-10 01:30:52756**
757** Unlike memcmp() this routine is guaranteed to return the difference
758** in the values of the last digit if the only difference is in the
759** last digit. So, for example,
760**
drh9339da12010-09-30 00:50:49761** compare2pow63("9223372036854775800", 1)
drhc81c11f2009-11-10 01:30:52762**
763** will return -8.
764*/
drh9339da12010-09-30 00:50:49765static int compare2pow63(const char *zNum, int incr){
766 int c = 0;
767 int i;
768 /* 012345678901234567 */
769 const char *pow63 = "922337203685477580";
770 for(i=0; c==0 && i<18; i++){
771 c = (zNum[i*incr]-pow63[i])*10;
772 }
drhc81c11f2009-11-10 01:30:52773 if( c==0 ){
drh9339da12010-09-30 00:50:49774 c = zNum[18*incr] - '8';
drh44dbca82010-01-13 04:22:20775 testcase( c==(-1) );
776 testcase( c==0 );
777 testcase( c==(+1) );
drhc81c11f2009-11-10 01:30:52778 }
779 return c;
780}
781
drhc81c11f2009-11-10 01:30:52782/*
drh9296c182014-07-23 13:40:49783** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
784** routine does *not* accept hexadecimal notation.
drh158b9cb2011-03-05 20:59:46785**
drh84d4f1a2017-09-20 10:47:10786** Returns:
drh158b9cb2011-03-05 20:59:46787**
drh9a278222019-06-07 22:26:08788** -1 Not even a prefix of the input text looks like an integer
drh84d4f1a2017-09-20 10:47:10789** 0 Successful transformation. Fits in a 64-bit signed integer.
drh4eb57ce2018-01-26 18:37:34790** 1 Excess non-space text after the integer value
drh84d4f1a2017-09-20 10:47:10791** 2 Integer too large for a 64-bit signed integer or is malformed
792** 3 Special case of 9223372036854775808
drhc81c11f2009-11-10 01:30:52793**
drh9339da12010-09-30 00:50:49794** length is the number of bytes in the string (bytes, not characters).
795** The string is not necessarily zero-terminated. The encoding is
796** given by enc.
drhc81c11f2009-11-10 01:30:52797*/
drh9339da12010-09-30 00:50:49798int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
drh0e5fba72013-03-20 12:04:29799 int incr;
drh158b9cb2011-03-05 20:59:46800 u64 u = 0;
shaneh5f1d6b62010-09-30 16:51:25801 int neg = 0; /* assume positive */
drh9339da12010-09-30 00:50:49802 int i;
803 int c = 0;
drh609d5842016-04-28 00:32:16804 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
drh84d4f1a2017-09-20 10:47:10805 int rc; /* Baseline return code */
drhc81c11f2009-11-10 01:30:52806 const char *zStart;
drh9339da12010-09-30 00:50:49807 const char *zEnd = zNum + length;
drh0e5fba72013-03-20 12:04:29808 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
809 if( enc==SQLITE_UTF8 ){
810 incr = 1;
811 }else{
812 incr = 2;
drh359941b2020-08-27 16:28:30813 length &= ~1;
drh0e5fba72013-03-20 12:04:29814 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
815 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
816 nonNum = i<length;
drh609d5842016-04-28 00:32:16817 zEnd = &zNum[i^1];
drh0e5fba72013-03-20 12:04:29818 zNum += (enc&1);
819 }
drh9339da12010-09-30 00:50:49820 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
drh158b9cb2011-03-05 20:59:46821 if( zNum<zEnd ){
822 if( *zNum=='-' ){
823 neg = 1;
824 zNum+=incr;
825 }else if( *zNum=='+' ){
826 zNum+=incr;
827 }
drhc81c11f2009-11-10 01:30:52828 }
829 zStart = zNum;
drh9339da12010-09-30 00:50:49830 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
831 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
drh158b9cb2011-03-05 20:59:46832 u = u*10 + c - '0';
drhc81c11f2009-11-10 01:30:52833 }
drh4eb57ce2018-01-26 18:37:34834 testcase( i==18*incr );
835 testcase( i==19*incr );
836 testcase( i==20*incr );
drh1822ebf2018-01-27 14:25:27837 if( u>LARGEST_INT64 ){
838 /* This test and assignment is needed only to suppress UB warnings
839 ** from clang and -fsanitize=undefined. This test and assignment make
840 ** the code a little larger and slower, and no harm comes from omitting
larrybrbc917382023-06-07 08:40:31841 ** them, but we must appease the undefined-behavior pharisees. */
drh1822ebf2018-01-27 14:25:27842 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
843 }else if( neg ){
drh158b9cb2011-03-05 20:59:46844 *pNum = -(i64)u;
845 }else{
846 *pNum = (i64)u;
847 }
drh4eb57ce2018-01-26 18:37:34848 rc = 0;
drh9a278222019-06-07 22:26:08849 if( i==0 && zStart==zNum ){ /* No digits */
850 rc = -1;
851 }else if( nonNum ){ /* UTF16 with high-order bytes non-zero */
drh84d4f1a2017-09-20 10:47:10852 rc = 1;
drh4eb57ce2018-01-26 18:37:34853 }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */
854 int jj = i;
855 do{
856 if( !sqlite3Isspace(zNum[jj]) ){
857 rc = 1; /* Extra non-space text after the integer */
858 break;
859 }
860 jj += incr;
861 }while( &zNum[jj]<zEnd );
drh84d4f1a2017-09-20 10:47:10862 }
drh4eb57ce2018-01-26 18:37:34863 if( i<19*incr ){
drhc81c11f2009-11-10 01:30:52864 /* Less than 19 digits, so we know that it fits in 64 bits */
drh158b9cb2011-03-05 20:59:46865 assert( u<=LARGEST_INT64 );
drh84d4f1a2017-09-20 10:47:10866 return rc;
drhc81c11f2009-11-10 01:30:52867 }else{
drh158b9cb2011-03-05 20:59:46868 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
drh4eb57ce2018-01-26 18:37:34869 c = i>19*incr ? 1 : compare2pow63(zNum, incr);
drh158b9cb2011-03-05 20:59:46870 if( c<0 ){
871 /* zNum is less than 9223372036854775808 so it fits */
872 assert( u<=LARGEST_INT64 );
drh84d4f1a2017-09-20 10:47:10873 return rc;
drh158b9cb2011-03-05 20:59:46874 }else{
drh4eb57ce2018-01-26 18:37:34875 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
876 if( c>0 ){
877 /* zNum is greater than 9223372036854775808 so it overflows */
878 return 2;
879 }else{
880 /* zNum is exactly 9223372036854775808. Fits if negative. The
881 ** special case 2 overflow if positive */
882 assert( u-1==LARGEST_INT64 );
883 return neg ? rc : 3;
884 }
drh158b9cb2011-03-05 20:59:46885 }
drhc81c11f2009-11-10 01:30:52886 }
887}
888
889/*
drh9296c182014-07-23 13:40:49890** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
891** into a 64-bit signed integer. This routine accepts hexadecimal literals,
892** whereas sqlite3Atoi64() does not.
893**
894** Returns:
895**
896** 0 Successful transformation. Fits in a 64-bit signed integer.
drh84d4f1a2017-09-20 10:47:10897** 1 Excess text after the integer value
898** 2 Integer too large for a 64-bit signed integer or is malformed
899** 3 Special case of 9223372036854775808
drh9296c182014-07-23 13:40:49900*/
901int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
902#ifndef SQLITE_OMIT_HEX_INTEGER
903 if( z[0]=='0'
904 && (z[1]=='x' || z[1]=='X')
drh9296c182014-07-23 13:40:49905 ){
906 u64 u = 0;
907 int i, k;
908 for(i=2; z[i]=='0'; i++){}
909 for(k=i; sqlite3Isxdigit(z[k]); k++){
910 u = u*16 + sqlite3HexToInt(z[k]);
911 }
912 memcpy(pOut, &u, 8);
drh49d8e0e2023-04-27 18:28:10913 if( k-i>16 ) return 2;
914 if( z[k]!=0 ) return 1;
915 return 0;
drh9296c182014-07-23 13:40:49916 }else
917#endif /* SQLITE_OMIT_HEX_INTEGER */
918 {
drh028acd92023-07-21 18:38:59919 int n = (int)(0x3fffffff&strspn(z,"+- \n\t0123456789"));
920 if( z[n] ) n++;
921 return sqlite3Atoi64(z, pOut, n, SQLITE_UTF8);
drh9296c182014-07-23 13:40:49922 }
923}
924
925/*
drhc81c11f2009-11-10 01:30:52926** If zNum represents an integer that will fit in 32-bits, then set
927** *pValue to that integer and return true. Otherwise return false.
928**
drh9296c182014-07-23 13:40:49929** This routine accepts both decimal and hexadecimal notation for integers.
930**
drhc81c11f2009-11-10 01:30:52931** Any non-numeric characters that following zNum are ignored.
932** This is different from sqlite3Atoi64() which requires the
933** input number to be zero-terminated.
934*/
935int sqlite3GetInt32(const char *zNum, int *pValue){
936 sqlite_int64 v = 0;
937 int i, c;
938 int neg = 0;
939 if( zNum[0]=='-' ){
940 neg = 1;
941 zNum++;
942 }else if( zNum[0]=='+' ){
943 zNum++;
944 }
drh28e048c2014-07-23 01:26:51945#ifndef SQLITE_OMIT_HEX_INTEGER
946 else if( zNum[0]=='0'
947 && (zNum[1]=='x' || zNum[1]=='X')
948 && sqlite3Isxdigit(zNum[2])
949 ){
950 u32 u = 0;
951 zNum += 2;
952 while( zNum[0]=='0' ) zNum++;
drhe61aa232023-04-19 12:08:46953 for(i=0; i<8 && sqlite3Isxdigit(zNum[i]); i++){
drh28e048c2014-07-23 01:26:51954 u = u*16 + sqlite3HexToInt(zNum[i]);
955 }
956 if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
957 memcpy(pValue, &u, 4);
958 return 1;
959 }else{
960 return 0;
961 }
962 }
963#endif
drh313e6fd2017-05-03 17:44:28964 if( !sqlite3Isdigit(zNum[0]) ) return 0;
drh935f2e72015-04-18 04:45:00965 while( zNum[0]=='0' ) zNum++;
drhc81c11f2009-11-10 01:30:52966 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
967 v = v*10 + c;
968 }
969
970 /* The longest decimal representation of a 32 bit integer is 10 digits:
971 **
972 ** 1234567890
973 ** 2^31 -> 2147483648
974 */
drh44dbca82010-01-13 04:22:20975 testcase( i==10 );
drhc81c11f2009-11-10 01:30:52976 if( i>10 ){
977 return 0;
978 }
drh44dbca82010-01-13 04:22:20979 testcase( v-neg==2147483647 );
drhc81c11f2009-11-10 01:30:52980 if( v-neg>2147483647 ){
981 return 0;
982 }
983 if( neg ){
984 v = -v;
985 }
986 *pValue = (int)v;
987 return 1;
988}
989
990/*
drh60ac3f42010-11-23 18:59:27991** Return a 32-bit integer value extracted from a string. If the
992** string is not an integer, just return 0.
993*/
994int sqlite3Atoi(const char *z){
995 int x = 0;
drh48bf2d72020-07-30 17:14:55996 sqlite3GetInt32(z, &x);
drh60ac3f42010-11-23 18:59:27997 return x;
998}
999
1000/*
drha1b0ff12023-06-30 18:35:431001** Decode a floating-point value into an approximate decimal
1002** representation.
drh002330d2023-06-30 19:41:571003**
drh34e4c6f2024-06-10 12:43:031004** If iRound<=0 then round to -iRound significant digits to the
1005** the left of the decimal point, or to a maximum of mxRound total
1006** significant digits.
1007**
1008** If iRound>0 round to min(iRound,mxRound) significant digits total.
1009**
1010** mxRound must be positive.
drhbc532ae2023-07-08 14:27:551011**
1012** The significant digits of the decimal representation are
1013** stored in p->z[] which is a often (but not always) a pointer
1014** into the middle of p->zBuf[]. There are p->n significant digits.
1015** The p->z[] array is *not* zero-terminated.
drha1b0ff12023-06-30 18:35:431016*/
drhc27bda02023-07-03 00:40:371017void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRound){
drha1b0ff12023-06-30 18:35:431018 int i;
1019 u64 v;
1020 int e, exp = 0;
drhe8b2c922024-10-01 20:29:431021 double rr[2];
1022
drh9ee94442023-07-01 15:23:241023 p->isSpecial = 0;
drh50ba4e32023-07-07 18:49:081024 p->z = p->zBuf;
drh34e4c6f2024-06-10 12:43:031025 assert( mxRound>0 );
1026
drhc27bda02023-07-03 00:40:371027 /* Convert negative numbers to positive. Deal with Infinity, 0.0, and
1028 ** NaN. */
1029 if( r<0.0 ){
drha1b0ff12023-06-30 18:35:431030 p->sign = '-';
drhc27bda02023-07-03 00:40:371031 r = -r;
1032 }else if( r==0.0 ){
drha1b0ff12023-06-30 18:35:431033 p->sign = '+';
1034 p->n = 1;
1035 p->iDP = 1;
drh50ba4e32023-07-07 18:49:081036 p->z = "0";
drha1b0ff12023-06-30 18:35:431037 return;
1038 }else{
1039 p->sign = '+';
1040 }
drhc27bda02023-07-03 00:40:371041 memcpy(&v,&r,8);
drha1b0ff12023-06-30 18:35:431042 e = v>>52;
drh42d042e2023-07-01 14:03:501043 if( (e&0x7ff)==0x7ff ){
drh4c40b7b2023-07-08 17:42:241044 p->isSpecial = 1 + (v!=0x7ff0000000000000LL);
drh9ee94442023-07-01 15:23:241045 p->n = 0;
1046 p->iDP = 0;
drha1b0ff12023-06-30 18:35:431047 return;
1048 }
drhaebeaba2023-06-30 23:18:441049
drhc27bda02023-07-03 00:40:371050 /* Multiply r by powers of ten until it lands somewhere in between
1051 ** 1.0e+19 and 1.0e+17.
drhe8b2c922024-10-01 20:29:431052 **
1053 ** Use Dekker-style double-double computation to increase the
1054 ** precision.
1055 **
1056 ** The error terms on constants like 1.0e+100 computed using the
1057 ** decimal extension, for example as follows:
1058 **
1059 ** SELECT decimal_exp(decimal_sub('1.0e+100',decimal(1.0e+100)));
drha1b0ff12023-06-30 18:35:431060 */
drhe8b2c922024-10-01 20:29:431061 rr[0] = r;
1062 rr[1] = 0.0;
1063 if( rr[0]>9.223372036854774784e+18 ){
1064 while( rr[0]>9.223372036854774784e+118 ){
1065 exp += 100;
1066 dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117);
drhc27bda02023-07-03 00:40:371067 }
drhe8b2c922024-10-01 20:29:431068 while( rr[0]>9.223372036854774784e+28 ){
1069 exp += 10;
1070 dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27);
1071 }
1072 while( rr[0]>9.223372036854774784e+18 ){
1073 exp += 1;
1074 dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18);
1075 }
drh17c20bb2023-07-01 17:56:001076 }else{
drhe8b2c922024-10-01 20:29:431077 while( rr[0]<9.223372036854774784e-83 ){
1078 exp -= 100;
1079 dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83);
drhc27bda02023-07-03 00:40:371080 }
drhe8b2c922024-10-01 20:29:431081 while( rr[0]<9.223372036854774784e+07 ){
1082 exp -= 10;
1083 dekkerMul2(rr, 1.0e+10, 0.0);
1084 }
1085 while( rr[0]<9.22337203685477478e+17 ){
1086 exp -= 1;
1087 dekkerMul2(rr, 1.0e+01, 0.0);
1088 }
drha1b0ff12023-06-30 18:35:431089 }
drhe8b2c922024-10-01 20:29:431090 v = rr[1]<0.0 ? (u64)rr[0]-(u64)(-rr[1]) : (u64)rr[0]+(u64)rr[1];
drhc27bda02023-07-03 00:40:371091
1092 /* Extract significant digits. */
drh50ba4e32023-07-07 18:49:081093 i = sizeof(p->zBuf)-1;
drhbc532ae2023-07-08 14:27:551094 assert( v>0 );
drh50ba4e32023-07-07 18:49:081095 while( v ){ p->zBuf[i--] = (v%10) + '0'; v /= 10; }
drhbc532ae2023-07-08 14:27:551096 assert( i>=0 && i<sizeof(p->zBuf)-1 );
drh50ba4e32023-07-07 18:49:081097 p->n = sizeof(p->zBuf) - 1 - i;
drhbc532ae2023-07-08 14:27:551098 assert( p->n>0 );
drh50ba4e32023-07-07 18:49:081099 assert( p->n<sizeof(p->zBuf) );
drha1b0ff12023-06-30 18:35:431100 p->iDP = p->n + exp;
drh6161cdd2024-02-17 03:32:311101 if( iRound<=0 ){
drh42d042e2023-07-01 14:03:501102 iRound = p->iDP - iRound;
drhbc532ae2023-07-08 14:27:551103 if( iRound==0 && p->zBuf[i+1]>='5' ){
drh42d042e2023-07-01 14:03:501104 iRound = 1;
drh50ba4e32023-07-07 18:49:081105 p->zBuf[i--] = '0';
drh42d042e2023-07-01 14:03:501106 p->n++;
1107 p->iDP++;
1108 }
1109 }
drh17c20bb2023-07-01 17:56:001110 if( iRound>0 && (iRound<p->n || p->n>mxRound) ){
drh50ba4e32023-07-07 18:49:081111 char *z = &p->zBuf[i+1];
drh17c20bb2023-07-01 17:56:001112 if( iRound>mxRound ) iRound = mxRound;
drh002330d2023-06-30 19:41:571113 p->n = iRound;
1114 if( z[iRound]>='5' ){
1115 int j = iRound-1;
1116 while( 1 /*exit-by-break*/ ){
1117 z[j]++;
1118 if( z[j]<='9' ) break;
1119 z[j] = '0';
1120 if( j==0 ){
1121 p->z[i--] = '1';
1122 p->n++;
1123 p->iDP++;
1124 break;
1125 }else{
1126 j--;
1127 }
1128 }
1129 }
1130 }
drh50ba4e32023-07-07 18:49:081131 p->z = &p->zBuf[i+1];
drhbc532ae2023-07-08 14:27:551132 assert( i+p->n < sizeof(p->zBuf) );
drha0d35d42025-02-10 11:16:371133 assert( p->n>0 );
1134 while( p->z[p->n-1]=='0' ){
1135 p->n--;
1136 assert( p->n>0 );
1137 }
drha1b0ff12023-06-30 18:35:431138}
1139
1140/*
drhabc38152020-07-22 13:38:041141** Try to convert z into an unsigned 32-bit integer. Return true on
1142** success and false if there is an error.
1143**
1144** Only decimal notation is accepted.
1145*/
1146int sqlite3GetUInt32(const char *z, u32 *pI){
1147 u64 v = 0;
1148 int i;
1149 for(i=0; sqlite3Isdigit(z[i]); i++){
1150 v = v*10 + z[i] - '0';
drh69306bf2020-07-22 20:12:101151 if( v>4294967296LL ){ *pI = 0; return 0; }
drhabc38152020-07-22 13:38:041152 }
drh69306bf2020-07-22 20:12:101153 if( i==0 || z[i]!=0 ){ *pI = 0; return 0; }
drhabc38152020-07-22 13:38:041154 *pI = (u32)v;
1155 return 1;
1156}
1157
1158/*
drhc81c11f2009-11-10 01:30:521159** The variable-length integer encoding is as follows:
1160**
1161** KEY:
1162** A = 0xxxxxxx 7 bits of data and one flag bit
1163** B = 1xxxxxxx 7 bits of data and one flag bit
1164** C = xxxxxxxx 8 bits of data
1165**
1166** 7 bits - A
1167** 14 bits - BA
1168** 21 bits - BBA
1169** 28 bits - BBBA
1170** 35 bits - BBBBA
1171** 42 bits - BBBBBA
1172** 49 bits - BBBBBBA
1173** 56 bits - BBBBBBBA
1174** 64 bits - BBBBBBBBC
1175*/
1176
1177/*
1178** Write a 64-bit variable-length integer to memory starting at p[0].
1179** The length of data write will be between 1 and 9 bytes. The number
1180** of bytes written is returned.
1181**
1182** A variable-length integer consists of the lower 7 bits of each byte
1183** for all bytes that have the 8th bit set and one byte with the 8th
1184** bit clear. Except, if we get to the 9th byte, it stores the full
1185** 8 bits and is the last byte.
1186*/
drh2f2b2b82014-08-22 18:48:251187static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
drhc81c11f2009-11-10 01:30:521188 int i, j, n;
1189 u8 buf[10];
1190 if( v & (((u64)0xff000000)<<32) ){
1191 p[8] = (u8)v;
1192 v >>= 8;
1193 for(i=7; i>=0; i--){
1194 p[i] = (u8)((v & 0x7f) | 0x80);
1195 v >>= 7;
1196 }
1197 return 9;
larrybrbc917382023-06-07 08:40:311198 }
drhc81c11f2009-11-10 01:30:521199 n = 0;
1200 do{
1201 buf[n++] = (u8)((v & 0x7f) | 0x80);
1202 v >>= 7;
1203 }while( v!=0 );
1204 buf[0] &= 0x7f;
1205 assert( n<=9 );
1206 for(i=0, j=n-1; j>=0; j--, i++){
1207 p[i] = buf[j];
1208 }
1209 return n;
1210}
drh2f2b2b82014-08-22 18:48:251211int sqlite3PutVarint(unsigned char *p, u64 v){
1212 if( v<=0x7f ){
1213 p[0] = v&0x7f;
drhc81c11f2009-11-10 01:30:521214 return 1;
1215 }
drh2f2b2b82014-08-22 18:48:251216 if( v<=0x3fff ){
1217 p[0] = ((v>>7)&0x7f)|0x80;
1218 p[1] = v&0x7f;
drhc81c11f2009-11-10 01:30:521219 return 2;
1220 }
drh2f2b2b82014-08-22 18:48:251221 return putVarint64(p,v);
drhc81c11f2009-11-10 01:30:521222}
1223
1224/*
drh0b2864c2010-03-03 15:18:381225** Bitmasks used by sqlite3GetVarint(). These precomputed constants
1226** are defined here rather than simply putting the constant expressions
1227** inline in order to work around bugs in the RVT compiler.
1228**
1229** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
1230**
1231** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
1232*/
1233#define SLOT_2_0 0x001fc07f
1234#define SLOT_4_2_0 0xf01fc07f
1235
1236
1237/*
drhc81c11f2009-11-10 01:30:521238** Read a 64-bit variable-length integer from memory starting at p[0].
1239** Return the number of bytes read. The value is stored in *v.
1240*/
1241u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
1242 u32 a,b,s;
1243
drh698c86f2019-04-17 12:07:081244 if( ((signed char*)p)[0]>=0 ){
1245 *v = *p;
drhc81c11f2009-11-10 01:30:521246 return 1;
1247 }
drh698c86f2019-04-17 12:07:081248 if( ((signed char*)p)[1]>=0 ){
1249 *v = ((u32)(p[0]&0x7f)<<7) | p[1];
drhc81c11f2009-11-10 01:30:521250 return 2;
1251 }
1252
drh0b2864c2010-03-03 15:18:381253 /* Verify that constants are precomputed correctly */
1254 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
shaneh1da207e2010-03-09 14:41:121255 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
drh0b2864c2010-03-03 15:18:381256
drh698c86f2019-04-17 12:07:081257 a = ((u32)p[0])<<14;
1258 b = p[1];
1259 p += 2;
drhc81c11f2009-11-10 01:30:521260 a |= *p;
1261 /* a: p0<<14 | p2 (unmasked) */
1262 if (!(a&0x80))
1263 {
drh0b2864c2010-03-03 15:18:381264 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:521265 b &= 0x7f;
1266 b = b<<7;
1267 a |= b;
1268 *v = a;
1269 return 3;
1270 }
1271
1272 /* CSE1 from below */
drh0b2864c2010-03-03 15:18:381273 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:521274 p++;
1275 b = b<<14;
1276 b |= *p;
1277 /* b: p1<<14 | p3 (unmasked) */
1278 if (!(b&0x80))
1279 {
drh0b2864c2010-03-03 15:18:381280 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:521281 /* moved CSE1 up */
1282 /* a &= (0x7f<<14)|(0x7f); */
1283 a = a<<7;
1284 a |= b;
1285 *v = a;
1286 return 4;
1287 }
1288
1289 /* a: p0<<14 | p2 (masked) */
1290 /* b: p1<<14 | p3 (unmasked) */
1291 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
1292 /* moved CSE1 up */
1293 /* a &= (0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:381294 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:521295 s = a;
1296 /* s: p0<<14 | p2 (masked) */
1297
1298 p++;
1299 a = a<<14;
1300 a |= *p;
1301 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1302 if (!(a&0x80))
1303 {
drh62aaa6c2015-11-21 17:27:421304 /* we can skip these cause they were (effectively) done above
1305 ** while calculating s */
drhc81c11f2009-11-10 01:30:521306 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
1307 /* b &= (0x7f<<14)|(0x7f); */
1308 b = b<<7;
1309 a |= b;
1310 s = s>>18;
1311 *v = ((u64)s)<<32 | a;
1312 return 5;
1313 }
1314
1315 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
1316 s = s<<7;
1317 s |= b;
1318 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
1319
1320 p++;
1321 b = b<<14;
1322 b |= *p;
1323 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
1324 if (!(b&0x80))
1325 {
1326 /* we can skip this cause it was (effectively) done above in calc'ing s */
1327 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
drh0b2864c2010-03-03 15:18:381328 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:521329 a = a<<7;
1330 a |= b;
1331 s = s>>18;
1332 *v = ((u64)s)<<32 | a;
1333 return 6;
1334 }
1335
1336 p++;
1337 a = a<<14;
1338 a |= *p;
1339 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
1340 if (!(a&0x80))
1341 {
drh0b2864c2010-03-03 15:18:381342 a &= SLOT_4_2_0;
1343 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:521344 b = b<<7;
1345 a |= b;
1346 s = s>>11;
1347 *v = ((u64)s)<<32 | a;
1348 return 7;
1349 }
1350
1351 /* CSE2 from below */
drh0b2864c2010-03-03 15:18:381352 a &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:521353 p++;
1354 b = b<<14;
1355 b |= *p;
1356 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
1357 if (!(b&0x80))
1358 {
drh0b2864c2010-03-03 15:18:381359 b &= SLOT_4_2_0;
drhc81c11f2009-11-10 01:30:521360 /* moved CSE2 up */
1361 /* a &= (0x7f<<14)|(0x7f); */
1362 a = a<<7;
1363 a |= b;
1364 s = s>>4;
1365 *v = ((u64)s)<<32 | a;
1366 return 8;
1367 }
1368
1369 p++;
1370 a = a<<15;
1371 a |= *p;
1372 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
1373
1374 /* moved CSE2 up */
1375 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
drh0b2864c2010-03-03 15:18:381376 b &= SLOT_2_0;
drhc81c11f2009-11-10 01:30:521377 b = b<<8;
1378 a |= b;
1379
1380 s = s<<4;
1381 b = p[-4];
1382 b &= 0x7f;
1383 b = b>>3;
1384 s |= b;
1385
1386 *v = ((u64)s)<<32 | a;
1387
1388 return 9;
1389}
1390
1391/*
1392** Read a 32-bit variable-length integer from memory starting at p[0].
1393** Return the number of bytes read. The value is stored in *v.
1394**
1395** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
1396** integer, then set *v to 0xffffffff.
1397**
larrybrbc917382023-06-07 08:40:311398** A MACRO version, getVarint32, is provided which inlines the
1399** single-byte case. All code should use the MACRO version as
drhc81c11f2009-11-10 01:30:521400** this function assumes the single-byte case has already been handled.
1401*/
1402u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
drh05883852023-10-19 13:35:221403 u64 v64;
1404 u8 n;
drhc81c11f2009-11-10 01:30:521405
drh05883852023-10-19 13:35:221406 /* Assume that the single-byte case has already been handled by
1407 ** the getVarint32() macro */
1408 assert( (p[0] & 0x80)!=0 );
drhc81c11f2009-11-10 01:30:521409
drh05883852023-10-19 13:35:221410 if( (p[1] & 0x80)==0 ){
1411 /* This is the two-byte case */
1412 *v = ((p[0]&0x7f)<<7) | p[1];
drhc81c11f2009-11-10 01:30:521413 return 2;
1414 }
drh05883852023-10-19 13:35:221415 if( (p[2] & 0x80)==0 ){
1416 /* This is the three-byte case */
1417 *v = ((p[0]&0x7f)<<14) | ((p[1]&0x7f)<<7) | p[2];
drhc81c11f2009-11-10 01:30:521418 return 3;
1419 }
drh05883852023-10-19 13:35:221420 /* four or more bytes */
1421 n = sqlite3GetVarint(p, &v64);
1422 assert( n>3 && n<=9 );
1423 if( (v64 & SQLITE_MAX_U32)!=v64 ){
1424 *v = 0xffffffff;
1425 }else{
drhc81c11f2009-11-10 01:30:521426 *v = (u32)v64;
drhc81c11f2009-11-10 01:30:521427 }
drh05883852023-10-19 13:35:221428 return n;
drhc81c11f2009-11-10 01:30:521429}
1430
1431/*
1432** Return the number of bytes that will be needed to store the given
1433** 64-bit integer.
1434*/
1435int sqlite3VarintLen(u64 v){
drh59a53642015-09-01 22:29:071436 int i;
drh6f17c092016-03-04 21:18:091437 for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
drhc81c11f2009-11-10 01:30:521438 return i;
1439}
1440
1441
1442/*
1443** Read or write a four-byte big-endian integer value.
1444*/
1445u32 sqlite3Get4byte(const u8 *p){
drh5372e4d2015-06-30 12:47:091446#if SQLITE_BYTEORDER==4321
1447 u32 x;
1448 memcpy(&x,p,4);
1449 return x;
drhdc5ece82017-02-15 15:09:091450#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:091451 u32 x;
1452 memcpy(&x,p,4);
1453 return __builtin_bswap32(x);
drha39284b2017-02-09 17:12:221454#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
mistachkin647ca462015-06-30 17:28:401455 u32 x;
1456 memcpy(&x,p,4);
1457 return _byteswap_ulong(x);
drh5372e4d2015-06-30 12:47:091458#else
drh693e6712014-01-24 22:58:001459 testcase( p[0]&0x80 );
1460 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
drh5372e4d2015-06-30 12:47:091461#endif
drhc81c11f2009-11-10 01:30:521462}
1463void sqlite3Put4byte(unsigned char *p, u32 v){
drh5372e4d2015-06-30 12:47:091464#if SQLITE_BYTEORDER==4321
1465 memcpy(p,&v,4);
drhdc5ece82017-02-15 15:09:091466#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
drh5372e4d2015-06-30 12:47:091467 u32 x = __builtin_bswap32(v);
1468 memcpy(p,&x,4);
drha39284b2017-02-09 17:12:221469#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
mistachkin647ca462015-06-30 17:28:401470 u32 x = _byteswap_ulong(v);
1471 memcpy(p,&x,4);
drh5372e4d2015-06-30 12:47:091472#else
drhc81c11f2009-11-10 01:30:521473 p[0] = (u8)(v>>24);
1474 p[1] = (u8)(v>>16);
1475 p[2] = (u8)(v>>8);
1476 p[3] = (u8)v;
drh5372e4d2015-06-30 12:47:091477#endif
drhc81c11f2009-11-10 01:30:521478}
1479
drh9296c182014-07-23 13:40:491480
1481
1482/*
1483** Translate a single byte of Hex into an integer.
1484** This routine only works if h really is a valid hexadecimal
1485** character: 0..9a..fA..F
1486*/
1487u8 sqlite3HexToInt(int h){
1488 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
1489#ifdef SQLITE_ASCII
1490 h += 9*(1&(h>>6));
1491#endif
1492#ifdef SQLITE_EBCDIC
1493 h += 9*(1&~(h>>4));
1494#endif
1495 return (u8)(h & 0xf);
1496}
1497
drhb48c0d52020-02-07 01:12:531498#if !defined(SQLITE_OMIT_BLOB_LITERAL)
drhc81c11f2009-11-10 01:30:521499/*
1500** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
1501** value. Return a pointer to its binary value. Space to hold the
1502** binary value has been obtained from malloc and must be freed by
1503** the calling routine.
1504*/
1505void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
1506 char *zBlob;
1507 int i;
1508
drh575fad62016-02-05 13:38:361509 zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
drhc81c11f2009-11-10 01:30:521510 n--;
1511 if( zBlob ){
1512 for(i=0; i<n; i+=2){
dancd74b612011-04-22 19:37:321513 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
drhc81c11f2009-11-10 01:30:521514 }
1515 zBlob[i/2] = 0;
1516 }
1517 return zBlob;
1518}
drhb48c0d52020-02-07 01:12:531519#endif /* !SQLITE_OMIT_BLOB_LITERAL */
drhc81c11f2009-11-10 01:30:521520
drh413c3d32010-02-23 20:11:561521/*
1522** Log an error that is an API call on a connection pointer that should
1523** not have been used. The "type" of connection pointer is given as the
1524** argument. The zType is a word like "NULL" or "closed" or "invalid".
1525*/
1526static void logBadConnection(const char *zType){
larrybrbc917382023-06-07 08:40:311527 sqlite3_log(SQLITE_MISUSE,
drh413c3d32010-02-23 20:11:561528 "API call with %s database connection pointer",
1529 zType
1530 );
1531}
drhc81c11f2009-11-10 01:30:521532
1533/*
drhc81c11f2009-11-10 01:30:521534** Check to make sure we have a valid db pointer. This test is not
1535** foolproof but it does provide some measure of protection against
1536** misuse of the interface such as passing in db pointers that are
1537** NULL or which have been previously closed. If this routine returns
1538** 1 it means that the db pointer is valid and 0 if it should not be
1539** dereferenced for any reason. The calling function should invoke
1540** SQLITE_MISUSE immediately.
1541**
1542** sqlite3SafetyCheckOk() requires that the db pointer be valid for
1543** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
1544** open properly and is not fit for general use but which can be
1545** used as an argument to sqlite3_errmsg() or sqlite3_close().
1546*/
1547int sqlite3SafetyCheckOk(sqlite3 *db){
drh5f9de6e2021-08-07 23:16:521548 u8 eOpenState;
drh413c3d32010-02-23 20:11:561549 if( db==0 ){
1550 logBadConnection("NULL");
1551 return 0;
1552 }
drh5f9de6e2021-08-07 23:16:521553 eOpenState = db->eOpenState;
1554 if( eOpenState!=SQLITE_STATE_OPEN ){
drhe294da02010-02-25 23:44:151555 if( sqlite3SafetyCheckSickOrOk(db) ){
1556 testcase( sqlite3GlobalConfig.xLog!=0 );
drh413c3d32010-02-23 20:11:561557 logBadConnection("unopened");
1558 }
drhc81c11f2009-11-10 01:30:521559 return 0;
1560 }else{
1561 return 1;
1562 }
1563}
1564int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
drh5f9de6e2021-08-07 23:16:521565 u8 eOpenState;
1566 eOpenState = db->eOpenState;
1567 if( eOpenState!=SQLITE_STATE_SICK &&
1568 eOpenState!=SQLITE_STATE_OPEN &&
1569 eOpenState!=SQLITE_STATE_BUSY ){
drhe294da02010-02-25 23:44:151570 testcase( sqlite3GlobalConfig.xLog!=0 );
drhaf46dc12010-02-24 21:44:071571 logBadConnection("invalid");
drh413c3d32010-02-23 20:11:561572 return 0;
1573 }else{
1574 return 1;
1575 }
drhc81c11f2009-11-10 01:30:521576}
drh158b9cb2011-03-05 20:59:461577
1578/*
larrybrbc917382023-06-07 08:40:311579** Attempt to add, subtract, or multiply the 64-bit signed value iB against
drh158b9cb2011-03-05 20:59:461580** the other 64-bit signed integer at *pA and store the result in *pA.
1581** Return 0 on success. Or if the operation would have resulted in an
1582** overflow, leave *pA unchanged and return 1.
1583*/
1584int sqlite3AddInt64(i64 *pA, i64 iB){
drhb9772e72017-09-12 13:27:431585#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
drh4a477612017-01-03 17:33:431586 return __builtin_add_overflow(*pA, iB, pA);
1587#else
drh158b9cb2011-03-05 20:59:461588 i64 iA = *pA;
1589 testcase( iA==0 ); testcase( iA==1 );
1590 testcase( iB==-1 ); testcase( iB==0 );
1591 if( iB>=0 ){
1592 testcase( iA>0 && LARGEST_INT64 - iA == iB );
1593 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
1594 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
drh158b9cb2011-03-05 20:59:461595 }else{
1596 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
1597 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
1598 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
drh158b9cb2011-03-05 20:59:461599 }
drh53a6eb32014-02-10 12:59:151600 *pA += iB;
larrybrbc917382023-06-07 08:40:311601 return 0;
drh4a477612017-01-03 17:33:431602#endif
drh158b9cb2011-03-05 20:59:461603}
1604int sqlite3SubInt64(i64 *pA, i64 iB){
drhb9772e72017-09-12 13:27:431605#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
drh4a477612017-01-03 17:33:431606 return __builtin_sub_overflow(*pA, iB, pA);
1607#else
drh158b9cb2011-03-05 20:59:461608 testcase( iB==SMALLEST_INT64+1 );
1609 if( iB==SMALLEST_INT64 ){
1610 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
1611 if( (*pA)>=0 ) return 1;
1612 *pA -= iB;
1613 return 0;
1614 }else{
1615 return sqlite3AddInt64(pA, -iB);
1616 }
drh4a477612017-01-03 17:33:431617#endif
drh158b9cb2011-03-05 20:59:461618}
drh158b9cb2011-03-05 20:59:461619int sqlite3MulInt64(i64 *pA, i64 iB){
drhb9772e72017-09-12 13:27:431620#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
drh4a477612017-01-03 17:33:431621 return __builtin_mul_overflow(*pA, iB, pA);
1622#else
drh158b9cb2011-03-05 20:59:461623 i64 iA = *pA;
drh09952c62016-09-20 22:04:051624 if( iB>0 ){
1625 if( iA>LARGEST_INT64/iB ) return 1;
1626 if( iA<SMALLEST_INT64/iB ) return 1;
1627 }else if( iB<0 ){
1628 if( iA>0 ){
1629 if( iB<SMALLEST_INT64/iA ) return 1;
1630 }else if( iA<0 ){
1631 if( iB==SMALLEST_INT64 ) return 1;
1632 if( iA==SMALLEST_INT64 ) return 1;
1633 if( -iA>LARGEST_INT64/-iB ) return 1;
drh53a6eb32014-02-10 12:59:151634 }
drh53a6eb32014-02-10 12:59:151635 }
drh09952c62016-09-20 22:04:051636 *pA = iA*iB;
drh158b9cb2011-03-05 20:59:461637 return 0;
drh4a477612017-01-03 17:33:431638#endif
drh158b9cb2011-03-05 20:59:461639}
drhd50ffc42011-03-08 02:38:281640
1641/*
stephan129203b2025-02-27 03:23:331642** Compute the absolute value of a 32-bit signed integer, if possible. Or
drhd50ffc42011-03-08 02:38:281643** if the integer has a value of -2147483648, return +2147483647
1644*/
1645int sqlite3AbsInt32(int x){
1646 if( x>=0 ) return x;
drh87e79ae2011-03-08 13:06:411647 if( x==(int)0x80000000 ) return 0x7fffffff;
drhd50ffc42011-03-08 02:38:281648 return -x;
1649}
drh81cc5162011-05-17 20:36:211650
1651#ifdef SQLITE_ENABLE_8_3_NAMES
1652/*
drhb51bf432011-07-21 21:29:351653** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
drh81cc5162011-05-17 20:36:211654** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
1655** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
1656** three characters, then shorten the suffix on z[] to be the last three
1657** characters of the original suffix.
1658**
drhb51bf432011-07-21 21:29:351659** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
1660** do the suffix shortening regardless of URI parameter.
1661**
drh81cc5162011-05-17 20:36:211662** Examples:
1663**
1664** test.db-journal => test.nal
1665** test.db-wal => test.wal
1666** test.db-shm => test.shm
drhf5808602011-12-16 00:33:041667** test.db-mj7f3319fa => test.9fa
drh81cc5162011-05-17 20:36:211668*/
1669void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
drhb51bf432011-07-21 21:29:351670#if SQLITE_ENABLE_8_3_NAMES<2
drh7d39e172012-01-02 12:41:531671 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
drhb51bf432011-07-21 21:29:351672#endif
1673 {
drh81cc5162011-05-17 20:36:211674 int i, sz;
1675 sz = sqlite3Strlen30(z);
drhc83f2d42011-05-18 02:41:101676 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
drhc02a43a2012-01-10 23:18:381677 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
drh81cc5162011-05-17 20:36:211678 }
1679}
1680#endif
drhbf539c42013-10-05 18:16:021681
larrybrbc917382023-06-07 08:40:311682/*
drhbf539c42013-10-05 18:16:021683** Find (an approximate) sum of two LogEst values. This computation is
1684** not a simple "+" operator because LogEst is stored as a logarithmic
1685** value.
larrybrbc917382023-06-07 08:40:311686**
drhbf539c42013-10-05 18:16:021687*/
1688LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
1689 static const unsigned char x[] = {
1690 10, 10, /* 0,1 */
1691 9, 9, /* 2,3 */
1692 8, 8, /* 4,5 */
1693 7, 7, 7, /* 6,7,8 */
1694 6, 6, 6, /* 9,10,11 */
1695 5, 5, 5, /* 12-14 */
1696 4, 4, 4, 4, /* 15-18 */
1697 3, 3, 3, 3, 3, 3, /* 19-24 */
1698 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
1699 };
1700 if( a>=b ){
1701 if( a>b+49 ) return a;
1702 if( a>b+31 ) return a+1;
1703 return a+x[a-b];
1704 }else{
1705 if( b>a+49 ) return b;
1706 if( b>a+31 ) return b+1;
1707 return b+x[b-a];
1708 }
1709}
1710
1711/*
drh224155d2014-04-30 13:19:091712** Convert an integer into a LogEst. In other words, compute an
1713** approximation for 10*log2(x).
drhbf539c42013-10-05 18:16:021714*/
1715LogEst sqlite3LogEst(u64 x){
1716 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1717 LogEst y = 40;
1718 if( x<8 ){
1719 if( x<2 ) return 0;
1720 while( x<8 ){ y -= 10; x <<= 1; }
1721 }else{
drhceb4b1d2017-08-17 20:53:071722#if GCC_VERSION>=5004000
1723 int i = 60 - __builtin_clzll(x);
1724 y += i*10;
1725 x >>= i;
1726#else
drh75ab50c2016-04-28 14:15:121727 while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
drhbf539c42013-10-05 18:16:021728 while( x>15 ){ y += 10; x >>= 1; }
drhceb4b1d2017-08-17 20:53:071729#endif
drhbf539c42013-10-05 18:16:021730 }
1731 return a[x&7] + y - 10;
1732}
1733
drhbf539c42013-10-05 18:16:021734/*
1735** Convert a double into a LogEst
1736** In other words, compute an approximation for 10*log2(x).
1737*/
1738LogEst sqlite3LogEstFromDouble(double x){
1739 u64 a;
1740 LogEst e;
1741 assert( sizeof(x)==8 && sizeof(a)==8 );
1742 if( x<=1 ) return 0;
1743 if( x<=2000000000 ) return sqlite3LogEst((u64)x);
1744 memcpy(&a, &x, 8);
1745 e = (a>>52) - 1022;
1746 return e*10;
1747}
drhbf539c42013-10-05 18:16:021748
1749/*
1750** Convert a LogEst into an integer.
1751*/
1752u64 sqlite3LogEstToInt(LogEst x){
1753 u64 n;
drhbf539c42013-10-05 18:16:021754 n = x%10;
1755 x /= 10;
1756 if( n>=5 ) n -= 2;
1757 else if( n>=1 ) n -= 1;
drhecdf20d2016-03-10 14:28:241758 if( x>60 ) return (u64)LARGEST_INT64;
drhecdf20d2016-03-10 14:28:241759 return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
drhbf539c42013-10-05 18:16:021760}
drh9bf755c2016-12-23 03:59:311761
1762/*
1763** Add a new name/number pair to a VList. This might require that the
1764** VList object be reallocated, so return the new VList. If an OOM
drhce1bbe52016-12-23 13:52:451765** error occurs, the original VList returned and the
drh9bf755c2016-12-23 03:59:311766** db->mallocFailed flag is set.
1767**
1768** A VList is really just an array of integers. To destroy a VList,
1769** simply pass it to sqlite3DbFree().
1770**
1771** The first integer is the number of integers allocated for the whole
1772** VList. The second integer is the number of integers actually used.
1773** Each name/number pair is encoded by subsequent groups of 3 or more
1774** integers.
1775**
drhce1bbe52016-12-23 13:52:451776** Each name/number pair starts with two integers which are the numeric
drh9bf755c2016-12-23 03:59:311777** value for the pair and the size of the name/number pair, respectively.
1778** The text name overlays one or more following integers. The text name
1779** is always zero-terminated.
drhce1bbe52016-12-23 13:52:451780**
1781** Conceptually:
1782**
1783** struct VList {
larrybrbc917382023-06-07 08:40:311784** int nAlloc; // Number of allocated slots
1785** int nUsed; // Number of used slots
drhce1bbe52016-12-23 13:52:451786** struct VListEntry {
1787** int iValue; // Value for this entry
1788** int nSlot; // Slots used by this entry
1789** // ... variable name goes here
1790** } a[0];
1791** }
1792**
1793** During code generation, pointers to the variable names within the
larrybrbc917382023-06-07 08:40:311794** VList are taken. When that happens, nAlloc is set to zero as an
drhce1bbe52016-12-23 13:52:451795** indication that the VList may never again be enlarged, since the
1796** accompanying realloc() would invalidate the pointers.
drh9bf755c2016-12-23 03:59:311797*/
1798VList *sqlite3VListAdd(
1799 sqlite3 *db, /* The database connection used for malloc() */
1800 VList *pIn, /* The input VList. Might be NULL */
1801 const char *zName, /* Name of symbol to add */
1802 int nName, /* Bytes of text in zName */
1803 int iVal /* Value to associate with zName */
1804){
1805 int nInt; /* number of sizeof(int) objects needed for zName */
drhce1bbe52016-12-23 13:52:451806 char *z; /* Pointer to where zName will be stored */
1807 int i; /* Index in pIn[] where zName is stored */
drh9bf755c2016-12-23 03:59:311808
1809 nInt = nName/4 + 3;
drhce1bbe52016-12-23 13:52:451810 assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
drh9bf755c2016-12-23 03:59:311811 if( pIn==0 || pIn[1]+nInt > pIn[0] ){
1812 /* Enlarge the allocation */
drh0aa32312019-04-13 04:01:121813 sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
drh9bf755c2016-12-23 03:59:311814 VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
drhce1bbe52016-12-23 13:52:451815 if( pOut==0 ) return pIn;
drh9bf755c2016-12-23 03:59:311816 if( pIn==0 ) pOut[1] = 2;
1817 pIn = pOut;
1818 pIn[0] = nAlloc;
1819 }
1820 i = pIn[1];
1821 pIn[i] = iVal;
1822 pIn[i+1] = nInt;
1823 z = (char*)&pIn[i+2];
1824 pIn[1] = i+nInt;
1825 assert( pIn[1]<=pIn[0] );
1826 memcpy(z, zName, nName);
1827 z[nName] = 0;
1828 return pIn;
1829}
1830
1831/*
1832** Return a pointer to the name of a variable in the given VList that
1833** has the value iVal. Or return a NULL if there is no such variable in
1834** the list
1835*/
1836const char *sqlite3VListNumToName(VList *pIn, int iVal){
1837 int i, mx;
1838 if( pIn==0 ) return 0;
1839 mx = pIn[1];
1840 i = 2;
1841 do{
1842 if( pIn[i]==iVal ) return (char*)&pIn[i+2];
1843 i += pIn[i+1];
1844 }while( i<mx );
1845 return 0;
1846}
1847
1848/*
1849** Return the number of the variable named zName, if it is in VList.
1850** or return 0 if there is no such variable.
1851*/
1852int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
1853 int i, mx;
1854 if( pIn==0 ) return 0;
1855 mx = pIn[1];
1856 i = 2;
1857 do{
1858 const char *z = (const char*)&pIn[i+2];
1859 if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
1860 i += pIn[i+1];
1861 }while( i<mx );
1862 return 0;
1863}