AryaWu/sqlite
0
1/*2** 2001 September 153**4** The author disclaims copyright to this source code. In place of5** 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, comparing15** strings, and stuff like that.16**17*/18#include "sqliteInt.h"19#include <stdarg.h>20#ifndef SQLITE_OMIT_FLOATING_POINT21#include <math.h>22#endif23 24/*25** Calls to sqlite3FaultSim() are used to simulate a failure during testing,26** or to bypass normal error detection during testing in order to let27** execute proceed further downstream.28**29** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0). The30** sqlite3FaultSim() function only returns non-zero during testing.31**32** During testing, if the test harness has set a fault-sim callback using33** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then34** each call to sqlite3FaultSim() is relayed to that application-supplied35** callback and the integer return value form the application-supplied36** callback is returned by sqlite3FaultSim().37**38** The integer argument to sqlite3FaultSim() is a code to identify which39** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()40** should have a unique code. To prevent legacy testing applications from41** breaking, the codes should not be changed or reused.42*/43#ifndef SQLITE_UNTESTABLE44int sqlite3FaultSim(int iTest){45 int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;46 return xCallback ? xCallback(iTest) : SQLITE_OK;47}48#endif49 50#ifndef SQLITE_OMIT_FLOATING_POINT51/*52** Return true if the floating point value is Not a Number (NaN).53**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.56*/57int sqlite3IsNaN(double x){58 int rc; /* The value return */59#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN60 u64 y;61 memcpy(&y,&x,sizeof(y));62 rc = IsNaN(y);63#else64 rc = isnan(x);65#endif /* HAVE_ISNAN */66 testcase( rc );67 return rc;68}69#endif /* SQLITE_OMIT_FLOATING_POINT */70 71#ifndef SQLITE_OMIT_FLOATING_POINT72/*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 84/*85** Compute a string length that is limited to what can be stored in86** lower 30 bits of a 32-bit signed integer.87**88** The value returned will never be negative. Nor will it ever be greater89** than the actual length of the string. For very long strings (greater90** than 1GiB) the value returned might be less than the true string length.91*/92int sqlite3Strlen30(const char *z){93 if( z==0 ) return 0;94 return 0x3fffffff & (int)strlen(z);95}96 97/*98** Return the declared type of a column. Or return zDflt if the column99** has no declared type.100**101** The column type is an extra string stored after the zero-terminator on102** the column name if and only if the COLFLAG_HASTYPE flag is set.103*/104char *sqlite3ColumnType(Column *pCol, char *zDflt){105 if( pCol->colFlags & COLFLAG_HASTYPE ){106 return pCol->zCnName + strlen(pCol->zCnName) + 1;107 }else if( pCol->eCType ){108 assert( pCol->eCType<=SQLITE_N_STDTYPE );109 return (char*)sqlite3StdType[pCol->eCType-1];110 }else{111 return zDflt;112 }113}114 115/*116** Helper function for sqlite3Error() - called rarely. Broken out into117** a separate routine to avoid unnecessary register saves on entry to118** sqlite3Error().119*/120static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){121 if( db->pErr ) sqlite3ValueSetNull(db->pErr);122 sqlite3SystemError(db, err_code);123}124 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 indicates128** that would be appropriate.129*/130void sqlite3Error(sqlite3 *db, int err_code){131 assert( db!=0 );132 db->errCode = err_code;133 if( err_code || db->pErr ){134 sqlite3ErrorFinish(db, err_code);135 }else{136 db->errByteOffset = -1;137 }138}139 140/*141** The equivalent of sqlite3Error(db, SQLITE_OK). Clear the error state142** and error message.143*/144void sqlite3ErrorClear(sqlite3 *db){145 assert( db!=0 );146 db->errCode = SQLITE_OK;147 db->errByteOffset = -1;148 if( db->pErr ) sqlite3ValueSetNull(db->pErr);149}150 151/*152** Load the sqlite3.iSysErrno field if that is an appropriate thing153** to do based on the SQLite error code in rc.154*/155void sqlite3SystemError(sqlite3 *db, int rc){156 if( rc==SQLITE_IOERR_NOMEM ) return;157#if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL)158 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#endif174 rc &= 0xff;175 if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){176 db->iSysErrno = sqlite3OsGetLastError(db->pVfs);177 }178}179 180/*181** Set the most recent error code and error string for the sqlite182** handle "db". The error code is set to "err_code".183**184** If it is not NULL, string zFormat specifies the format of the185** error string. zFormat and any string tokens that follow it are186** assumed to be encoded in UTF-8.187**188** To clear the most recent error for sqlite handle "db", sqlite3Error189** should be called with err_code set to SQLITE_OK and zFormat set190** to NULL.191*/192void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){193 assert( db!=0 );194 db->errCode = err_code;195 sqlite3SystemError(db, err_code);196 if( zFormat==0 ){197 sqlite3Error(db, err_code);198 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){199 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);205 }206}207 208/*209** 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_CALLBACK218 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;227 }228 }229#endif230}231 232/*233** Add an error message to pParse->zErrMsg and increment pParse->nErr.234**235** This function should be used to report any error that occurs while236** compiling an SQL statement (i.e. within sqlite3_prepare()). The237** last thing the sqlite3_prepare() function does is copy the error238** stored by this function into the database handle using sqlite3Error().239** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used240** during statement execution (sqlite3_step() etc.).241*/242void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){243 char *zMsg;244 va_list ap;245 sqlite3 *db = pParse->db;246 assert( db!=0 );247 assert( db->pParse==pParse || db->pParse->pToplevel==pParse );248 db->errByteOffset = -2;249 va_start(ap, zFormat);250 zMsg = sqlite3VMPrintf(db, zFormat, ap);251 va_end(ap);252 if( db->errByteOffset<-1 ) db->errByteOffset = -1;253 if( db->suppressErr ){254 sqlite3DbFree(db, zMsg);255 if( db->mallocFailed ){256 pParse->nErr++;257 pParse->rc = SQLITE_NOMEM;258 }259 }else{260 pParse->nErr++;261 sqlite3DbFree(db, pParse->zErrMsg);262 pParse->zErrMsg = zMsg;263 pParse->rc = SQLITE_ERROR;264 pParse->pWith = 0;265 }266}267 268/*269** If database connection db is currently parsing SQL, then transfer270** error code errCode to that parser if the parser has not already271** 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/*282** Convert an SQL-style quoted string into a normal string by removing283** the quote characters. The conversion is done in-place. If the284** input does not begin with a quote character, then this routine285** is a no-op.286**287** The input string must be zero-terminated. A new zero-terminator288** is added to the dequoted string.289**290** The return value is -1 if no dequoting occurs or the length of the291** dequoted string, exclusive of the zero terminator, if dequoting does292** occur.293**294** 2002-02-14: This routine is extended to remove MS-Access style295** brackets from around identifiers. For example: "[a-b-c]" becomes296** "a-b-c".297*/298void sqlite3Dequote(char *z){299 char quote;300 int i, j;301 if( z==0 ) return;302 quote = z[0];303 if( !sqlite3Isquote(quote) ) return;304 if( quote=='[' ) quote = ']';305 for(i=1, j=0;; i++){306 assert( z[i] );307 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;319}320void sqlite3DequoteExpr(Expr *p){321 assert( !ExprHasProperty(p, EP_IntValue) );322 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}326 327/*328** Expression p is a QNUMBER (quoted number). Dequote the value in p->u.zToken329** and set the type to INTEGER or FLOAT. "Quoted" integers or floats are those330** that contain '_' characters that must be removed before further processing.331*/332void sqlite3DequoteNumber(Parse *pParse, Expr *p){333 assert( p!=0 || pParse->db->mallocFailed );334 if( p ){335 const char *pIn = p->u.zToken;336 char *pOut = p->u.zToken;337 int bHex = (pIn[0]=='0' && (pIn[1]=='x' || pIn[1]=='X'));338 int iValue;339 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;345 }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 }351 }352 }while( *pIn++ );353 if( bHex ) p->op = TK_INTEGER;354 355 /* tag-20240227-a: If after dequoting, the number is an integer that356 ** fits in 32 bits, then it must be converted into EP_IntValue. Other357 ** 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 }362 }363}364 365/*366** If the input token p is quoted, try to adjust the token to remove367** the quotes. This is not always possible:368**369** "abc" -> abc370** "ab""cd" -> (not possible because of the interior "")371**372** Remove the quotes if possible. This is a optimization. The overall373** system should still return the correct answer even if this routine374** is always a no-op.375*/376void sqlite3DequoteToken(Token *p){377 unsigned int i;378 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/*388** Generate a Token object from a string389*/390void sqlite3TokenInit(Token *p, char *z){391 p->z = z;392 p->n = sqlite3Strlen30(z);393}394 395/* Convenient short-hand */396#define UpperToLower sqlite3UpperToLower397 398/*399** Some systems have stricmp(). Others have strcasecmp(). Because400** there is no consistency, we will define our own.401**402** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and403** sqlite3_strnicmp() APIs allow applications and extensions to compare404** the contents of two buffers containing UTF-8 strings in a405** case-independent fashion, using the same definition of "case406** independence" that SQLite uses internally when comparing identifiers.407*/408int sqlite3_stricmp(const char *zLeft, const char *zRight){409 if( zLeft==0 ){410 return zRight ? -1 : 0;411 }else if( zRight==0 ){412 return 1;413 }414 return sqlite3StrICmp(zLeft, zRight);415}416int sqlite3StrICmp(const char *zLeft, const char *zRight){417 unsigned char *a, *b;418 int c, x;419 a = (unsigned char *)zLeft;420 b = (unsigned char *)zRight;421 for(;;){422 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 }430 a++;431 b++;432 }433 return c;434}435int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){436 register unsigned char *a, *b;437 if( zLeft==0 ){438 return zRight ? -1 : 0;439 }else if( zRight==0 ){440 return 1;441 }442 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/*449** Compute an 8-bit hash on a string that is insensitive to case differences450*/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 461/* Double-Double multiplication. (x[0],x[1]) *= (y,yy)462**463** Reference:464** T. J. Dekker, "A Floating-Point Technique for Extending the465** Available Precision". 1971-07-26.466*/467static void dekkerMul2(volatile double *x, double y, double yy){468 /*469 ** The "volatile" keywords on parameter x[] and on local variables470 ** below are needed force intermediate results to be truncated to471 ** binary64 rather than be carried around in an extended-precision472 ** format. The truncation is necessary for the Dekker algorithm to473 ** work. Intel x86 floating point might omit the truncation without474 ** the use of volatile. 475 */476 volatile double tx, ty, p, q, c, cc;477 double hx, hy;478 u64 m;479 memcpy(&m, (void*)&x[0], 8);480 m &= 0xfffffffffc000000LL;481 memcpy(&hx, &m, 8);482 tx = x[0] - hx;483 memcpy(&m, &y, 8);484 m &= 0xfffffffffc000000LL;485 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;491 cc = x[0]*yy + x[1]*y + cc;492 x[0] = c + cc;493 x[1] = c - x[0];494 x[1] += cc;495}496 497/*498** The string z[] is an text representation of a real number.499** Convert this string to a double and write it into *pResult.500**501** The string z[] is length bytes in length (bytes, not characters) and502** uses the encoding enc. The string is not necessarily zero-terminated.503**504** Return TRUE if the result is a valid real number (or integer) and FALSE505** if the string is empty or contains extraneous text. More specifically506** return507** 1 => The input string is a pure integer508** 2 or more => The input has a decimal point or eNNN clause509** 0 or less => The input string is not a valid number510** -1 => Not a valid number, but has a valid prefix which511** includes a decimal point and/or an eNNN clause512**513** Valid numbers are in one of these formats:514**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 determining520** validity.521**522** If some prefix of the input string is a valid number, this routine523** returns FALSE but it still converts the prefix and writes the result524** into *pResult.525*/526#if defined(_MSC_VER)527#pragma warning(disable : 4756)528#endif529int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){530#ifndef SQLITE_OMIT_FLOATING_POINT531 int incr;532 const char *zEnd;533 /* sign * significand * (10 ^ (esign * exponent)) */534 int sign = 1; /* sign of significand */535 u64 s = 0; /* significand */536 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 */540 int nDigit = 0; /* Number of digits processed */541 int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */542 u64 s2; /* round-tripped significand */543 double rr[2];544 545 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );546 *pResult = 0.0; /* Default return value, in case of an error */547 if( length==0 ) return 0;548 549 if( enc==SQLITE_UTF8 ){550 incr = 1;551 zEnd = z + length;552 }else{553 int i;554 incr = 2;555 length &= ~1;556 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );557 testcase( enc==SQLITE_UTF16LE );558 testcase( enc==SQLITE_UTF16BE );559 for(i=3-enc; i<length && z[i]==0; i+=2){}560 if( i<length ) eType = -100;561 zEnd = &z[i^1];562 z += (enc&1);563 }564 565 /* skip leading spaces */566 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;567 if( z>=zEnd ) return 0;568 569 /* get sign of significand */570 if( *z=='-' ){571 sign = -1;572 z+=incr;573 }else if( *z=='+' ){574 z+=incr;575 }576 577 /* copy max significant digits to significand */578 while( z<zEnd && sqlite3Isdigit(*z) ){579 s = s*10 + (*z - '0');580 z+=incr; nDigit++;581 if( s>=((LARGEST_UINT64-9)/10) ){582 /* skip non-significant significand digits583 ** (increase exponent by d to shift decimal left) */584 while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; }585 }586 }587 if( z>=zEnd ) goto do_atof_calc;588 589 /* if decimal point is present */590 if( *z=='.' ){591 z+=incr;592 eType++;593 /* copy digits from after decimal to significand594 ** (decrease exponent by d to shift decimal right) */595 while( z<zEnd && sqlite3Isdigit(*z) ){596 if( s<((LARGEST_UINT64-9)/10) ){597 s = s*10 + (*z - '0');598 d--;599 nDigit++;600 }601 z+=incr;602 }603 }604 if( z>=zEnd ) goto do_atof_calc;605 606 /* if exponent is present */607 if( *z=='e' || *z=='E' ){608 z+=incr;609 eValid = 0;610 eType++;611 612 /* This branch is needed to avoid a (harmless) buffer overread. The613 ** special comment alerts the mutation tester that the correct answer614 ** is obtained even if the branch is omitted */615 if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/616 617 /* get sign of exponent */618 if( *z=='-' ){619 esign = -1;620 z+=incr;621 }else if( *z=='+' ){622 z+=incr;623 }624 /* copy digits to exponent */625 while( z<zEnd && sqlite3Isdigit(*z) ){626 e = e<10000 ? (e*10 + (*z - '0')) : 10000;627 z+=incr;628 eValid = 1;629 }630 }631 632 /* skip trailing spaces */633 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;634 635do_atof_calc:636 /* Zero is a special case */637 if( s==0 ){638 *pResult = sign<0 ? -0.0 : +0.0;639 goto atof_return;640 }641 642 /* adjust exponent by d, and update sign */643 e = (e*esign) + d;644 645 /* Try to adjust the exponent to make it smaller */646 while( e>0 && s<((LARGEST_UINT64-0x7ff)/10) ){647 s *= 10;648 e--;649 }650 while( e<0 && (s%10)==0 ){651 s /= 10;652 e++;653 }654 655 rr[0] = (double)s;656 assert( sizeof(s2)==sizeof(rr[0]) );657#ifdef SQLITE_DEBUG658 rr[1] = 18446744073709549568.0;659 memcpy(&s2, &rr[1], sizeof(s2));660 assert( s2==0x43efffffffffffffLL );661#endif662 /* Largest double that can be safely converted to u64663 ** vvvvvvvvvvvvvvvvvvvvvv */664 if( rr[0]<=18446744073709549568.0 ){665 s2 = (u64)rr[0];666 rr[1] = s>=s2 ? (double)(s - s2) : -(double)(s2 - s);667 }else{668 rr[1] = 0.0;669 }670 assert( rr[1]<=1.0e-10*rr[0] ); /* Equal only when rr[0]==0.0 */671 672 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);684 }685 }else{686 while( e<=-100 ){687 e += 100;688 dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117);689 }690 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 }698 }699 *pResult = rr[0]+rr[1];700 if( sqlite3IsNaN(*pResult) ) *pResult = 1e300*1e300;701 if( sign<0 ) *pResult = -*pResult;702 assert( !sqlite3IsNaN(*pResult) );703 704atof_return:705 /* return true if number and no extra non-whitespace characters after */706 if( z==zEnd && nDigit>0 && eValid && eType>0 ){707 return eType;708 }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){709 return -1;710 }else{711 return 0;712 }713#else714 return !sqlite3Atoi64(z, pResult, length, enc);715#endif /* SQLITE_OMIT_FLOATING_POINT */716}717#if defined(_MSC_VER)718#pragma warning(default : 4756)719#endif720 721/*722** Render an signed 64-bit integer as text. Store the result in zOut[] and723** return the length of the string that was stored, in bytes. The value724** returned does not include the zero terminator at the end of the output725** string.726**727** The caller must ensure that zOut[] is at least 21 bytes in size.728*/729int sqlite3Int64ToText(i64 v, char *zOut){730 int i;731 u64 x;732 char zTemp[22];733 if( v<0 ){734 x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v;735 }else{736 x = v;737 }738 i = sizeof(zTemp)-2;739 zTemp[sizeof(zTemp)-1] = 0;740 while( 1 /*exit-by-break*/ ){741 zTemp[i] = (x%10) + '0';742 x = x/10;743 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;749}750 751/*752** Compare the 19-character string zNum against the text representation753** value 2^63: 9223372036854775808. Return negative, zero, or positive754** if zNum is less than, equal to, or greater than the string.755** Note that zNum must contain exactly 19 characters.756**757** Unlike memcmp() this routine is guaranteed to return the difference758** in the values of the last digit if the only difference is in the759** last digit. So, for example,760**761** compare2pow63("9223372036854775800", 1)762**763** will return -8.764*/765static 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 }773 if( c==0 ){774 c = zNum[18*incr] - '8';775 testcase( c==(-1) );776 testcase( c==0 );777 testcase( c==(+1) );778 }779 return c;780}781 782/*783** Convert zNum to a 64-bit signed integer. zNum must be decimal. This784** routine does *not* accept hexadecimal notation.785**786** Returns:787**788** -1 Not even a prefix of the input text looks like an integer789** 0 Successful transformation. Fits in a 64-bit signed integer.790** 1 Excess non-space text after the integer value791** 2 Integer too large for a 64-bit signed integer or is malformed792** 3 Special case of 9223372036854775808793**794** length is the number of bytes in the string (bytes, not characters).795** The string is not necessarily zero-terminated. The encoding is796** given by enc.797*/798int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){799 int incr;800 u64 u = 0;801 int neg = 0; /* assume positive */802 int i;803 int c = 0;804 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */805 int rc; /* Baseline return code */806 const char *zStart;807 const char *zEnd = zNum + length;808 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );809 if( enc==SQLITE_UTF8 ){810 incr = 1;811 }else{812 incr = 2;813 length &= ~1;814 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );815 for(i=3-enc; i<length && zNum[i]==0; i+=2){}816 nonNum = i<length;817 zEnd = &zNum[i^1];818 zNum += (enc&1);819 }820 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;821 if( zNum<zEnd ){822 if( *zNum=='-' ){823 neg = 1;824 zNum+=incr;825 }else if( *zNum=='+' ){826 zNum+=incr;827 }828 }829 zStart = zNum;830 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){832 u = u*10 + c - '0';833 }834 testcase( i==18*incr );835 testcase( i==19*incr );836 testcase( i==20*incr );837 if( u>LARGEST_INT64 ){838 /* This test and assignment is needed only to suppress UB warnings839 ** from clang and -fsanitize=undefined. This test and assignment make840 ** the code a little larger and slower, and no harm comes from omitting841 ** them, but we must appease the undefined-behavior pharisees. */842 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;843 }else if( neg ){844 *pNum = -(i64)u;845 }else{846 *pNum = (i64)u;847 }848 rc = 0;849 if( i==0 && zStart==zNum ){ /* No digits */850 rc = -1;851 }else if( nonNum ){ /* UTF16 with high-order bytes non-zero */852 rc = 1;853 }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 );862 }863 if( i<19*incr ){864 /* Less than 19 digits, so we know that it fits in 64 bits */865 assert( u<=LARGEST_INT64 );866 return rc;867 }else{868 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */869 c = i>19*incr ? 1 : compare2pow63(zNum, incr);870 if( c<0 ){871 /* zNum is less than 9223372036854775808 so it fits */872 assert( u<=LARGEST_INT64 );873 return rc;874 }else{875 *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. The881 ** special case 2 overflow if positive */882 assert( u-1==LARGEST_INT64 );883 return neg ? rc : 3;884 }885 }886 }887}888 889/*890** 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.897** 1 Excess text after the integer value898** 2 Integer too large for a 64-bit signed integer or is malformed899** 3 Special case of 9223372036854775808900*/901int sqlite3DecOrHexToI64(const char *z, i64 *pOut){902#ifndef SQLITE_OMIT_HEX_INTEGER903 if( z[0]=='0'904 && (z[1]=='x' || z[1]=='X')905 ){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);913 if( k-i>16 ) return 2;914 if( z[k]!=0 ) return 1;915 return 0;916 }else917#endif /* SQLITE_OMIT_HEX_INTEGER */918 {919 int n = (int)(0x3fffffff&strspn(z,"+- \n\t0123456789"));920 if( z[n] ) n++;921 return sqlite3Atoi64(z, pOut, n, SQLITE_UTF8);922 }923}924 925/*926** If zNum represents an integer that will fit in 32-bits, then set927** *pValue to that integer and return true. Otherwise return false.928**929** This routine accepts both decimal and hexadecimal notation for integers.930**931** Any non-numeric characters that following zNum are ignored.932** This is different from sqlite3Atoi64() which requires the933** 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 }945#ifndef SQLITE_OMIT_HEX_INTEGER946 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++;953 for(i=0; i<8 && sqlite3Isxdigit(zNum[i]); i++){954 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#endif964 if( !sqlite3Isdigit(zNum[0]) ) return 0;965 while( zNum[0]=='0' ) zNum++;966 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 ** 1234567890973 ** 2^31 -> 2147483648974 */975 testcase( i==10 );976 if( i>10 ){977 return 0;978 }979 testcase( v-neg==2147483647 );980 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/*991** Return a 32-bit integer value extracted from a string. If the992** string is not an integer, just return 0.993*/994int sqlite3Atoi(const char *z){995 int x = 0;996 sqlite3GetInt32(z, &x);997 return x;998}999 1000/*1001** Decode a floating-point value into an approximate decimal1002** representation.1003**1004** If iRound<=0 then round to -iRound significant digits to the1005** the left of the decimal point, or to a maximum of mxRound total1006** significant digits.1007**1008** If iRound>0 round to min(iRound,mxRound) significant digits total.1009**1010** mxRound must be positive.1011**1012** The significant digits of the decimal representation are1013** stored in p->z[] which is a often (but not always) a pointer1014** into the middle of p->zBuf[]. There are p->n significant digits.1015** The p->z[] array is *not* zero-terminated.1016*/1017void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRound){1018 int i;1019 u64 v;1020 int e, exp = 0;1021 double rr[2];1022 1023 p->isSpecial = 0;1024 p->z = p->zBuf;1025 assert( mxRound>0 );1026 1027 /* Convert negative numbers to positive. Deal with Infinity, 0.0, and1028 ** NaN. */1029 if( r<0.0 ){1030 p->sign = '-';1031 r = -r;1032 }else if( r==0.0 ){1033 p->sign = '+';1034 p->n = 1;1035 p->iDP = 1;1036 p->z = "0";1037 return;1038 }else{1039 p->sign = '+';1040 }1041 memcpy(&v,&r,8);1042 e = v>>52;1043 if( (e&0x7ff)==0x7ff ){1044 p->isSpecial = 1 + (v!=0x7ff0000000000000LL);1045 p->n = 0;1046 p->iDP = 0;1047 return;1048 }1049 1050 /* Multiply r by powers of ten until it lands somewhere in between1051 ** 1.0e+19 and 1.0e+17.1052 **1053 ** Use Dekker-style double-double computation to increase the1054 ** precision.1055 **1056 ** The error terms on constants like 1.0e+100 computed using the1057 ** decimal extension, for example as follows:1058 **1059 ** SELECT decimal_exp(decimal_sub('1.0e+100',decimal(1.0e+100)));1060 */1061 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);1067 }1068 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 }1076 }else{1077 while( rr[0]<9.223372036854774784e-83 ){1078 exp -= 100;1079 dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83);1080 }1081 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 }1089 }1090 v = rr[1]<0.0 ? (u64)rr[0]-(u64)(-rr[1]) : (u64)rr[0]+(u64)rr[1];1091 1092 /* Extract significant digits. */1093 i = sizeof(p->zBuf)-1;1094 assert( v>0 );1095 while( v ){ p->zBuf[i--] = (v%10) + '0'; v /= 10; }1096 assert( i>=0 && i<sizeof(p->zBuf)-1 );1097 p->n = sizeof(p->zBuf) - 1 - i;1098 assert( p->n>0 );1099 assert( p->n<sizeof(p->zBuf) );1100 p->iDP = p->n + exp;1101 if( iRound<=0 ){1102 iRound = p->iDP - iRound;1103 if( iRound==0 && p->zBuf[i+1]>='5' ){1104 iRound = 1;1105 p->zBuf[i--] = '0';1106 p->n++;1107 p->iDP++;1108 }1109 }1110 if( iRound>0 && (iRound<p->n || p->n>mxRound) ){1111 char *z = &p->zBuf[i+1];1112 if( iRound>mxRound ) iRound = mxRound;1113 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 }1131 p->z = &p->zBuf[i+1];1132 assert( i+p->n < sizeof(p->zBuf) );1133 assert( p->n>0 );1134 while( p->z[p->n-1]=='0' ){1135 p->n--;1136 assert( p->n>0 );1137 }1138}1139 1140/*1141** Try to convert z into an unsigned 32-bit integer. Return true on1142** 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';1151 if( v>4294967296LL ){ *pI = 0; return 0; }1152 }1153 if( i==0 || z[i]!=0 ){ *pI = 0; return 0; }1154 *pI = (u32)v;1155 return 1;1156}1157 1158/*1159** The variable-length integer encoding is as follows:1160**1161** KEY:1162** A = 0xxxxxxx 7 bits of data and one flag bit1163** B = 1xxxxxxx 7 bits of data and one flag bit1164** C = xxxxxxxx 8 bits of data1165**1166** 7 bits - A1167** 14 bits - BA1168** 21 bits - BBA1169** 28 bits - BBBA1170** 35 bits - BBBBA1171** 42 bits - BBBBBA1172** 49 bits - BBBBBBA1173** 56 bits - BBBBBBBA1174** 64 bits - BBBBBBBBC1175*/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 number1180** of bytes written is returned.1181**1182** A variable-length integer consists of the lower 7 bits of each byte1183** for all bytes that have the 8th bit set and one byte with the 8th1184** bit clear. Except, if we get to the 9th byte, it stores the full1185** 8 bits and is the last byte.1186*/1187static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){1188 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;1198 } 1199 n = 0;1200 do{