Add tests to bestindexC.test. No changes to code.
[sqlite.git] / src / printf.c
blobc0dcc5d0fa1682b39f6727935a376d0a65142e8c
1 /*
2 ** The "printf" code that follows dates from the 1980's. It is in
3 ** the public domain.
4 **
5 **************************************************************************
6 **
7 ** This file contains code for a set of "printf"-like routines. These
8 ** routines format strings much like the printf() from the standard C
9 ** library, though the implementation here has enhancements to support
10 ** SQLite.
12 #include "sqliteInt.h"
15 ** Conversion types fall into various categories as defined by the
16 ** following enumeration.
18 #define etRADIX 0 /* non-decimal integer types. %x %o */
19 #define etFLOAT 1 /* Floating point. %f */
20 #define etEXP 2 /* Exponentional notation. %e and %E */
21 #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
22 #define etSIZE 4 /* Return number of characters processed so far. %n */
23 #define etSTRING 5 /* Strings. %s */
24 #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
25 #define etPERCENT 7 /* Percent symbol. %% */
26 #define etCHARX 8 /* Characters. %c */
27 /* The rest are extensions, not normally found in printf() */
28 #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
29 #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
30 NULL pointers replaced by SQL NULL. %Q */
31 #define etTOKEN 11 /* a pointer to a Token structure */
32 #define etSRCITEM 12 /* a pointer to a SrcItem */
33 #define etPOINTER 13 /* The %p conversion */
34 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
35 #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
36 #define etDECIMAL 16 /* %d or %u, but not %x, %o */
38 #define etINVALID 17 /* Any unrecognized conversion type */
42 ** An "etByte" is an 8-bit unsigned value.
44 typedef unsigned char etByte;
47 ** Each builtin conversion character (ex: the 'd' in "%d") is described
48 ** by an instance of the following structure
50 typedef struct et_info { /* Information about each format field */
51 char fmttype; /* The format field code letter */
52 etByte base; /* The base for radix conversion */
53 etByte flags; /* One or more of FLAG_ constants below */
54 etByte type; /* Conversion paradigm */
55 etByte charset; /* Offset into aDigits[] of the digits string */
56 etByte prefix; /* Offset into aPrefix[] of the prefix string */
57 } et_info;
60 ** Allowed values for et_info.flags
62 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
63 #define FLAG_STRING 4 /* Allow infinite precision */
67 ** The following table is searched linearly, so it is good to put the
68 ** most frequently used conversion types first.
70 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
71 static const char aPrefix[] = "-x0\000X0";
72 static const et_info fmtinfo[] = {
73 { 'd', 10, 1, etDECIMAL, 0, 0 },
74 { 's', 0, 4, etSTRING, 0, 0 },
75 { 'g', 0, 1, etGENERIC, 30, 0 },
76 { 'z', 0, 4, etDYNSTRING, 0, 0 },
77 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
78 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
79 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
80 { 'c', 0, 0, etCHARX, 0, 0 },
81 { 'o', 8, 0, etRADIX, 0, 2 },
82 { 'u', 10, 0, etDECIMAL, 0, 0 },
83 { 'x', 16, 0, etRADIX, 16, 1 },
84 { 'X', 16, 0, etRADIX, 0, 4 },
85 #ifndef SQLITE_OMIT_FLOATING_POINT
86 { 'f', 0, 1, etFLOAT, 0, 0 },
87 { 'e', 0, 1, etEXP, 30, 0 },
88 { 'E', 0, 1, etEXP, 14, 0 },
89 { 'G', 0, 1, etGENERIC, 14, 0 },
90 #endif
91 { 'i', 10, 1, etDECIMAL, 0, 0 },
92 { 'n', 0, 0, etSIZE, 0, 0 },
93 { '%', 0, 0, etPERCENT, 0, 0 },
94 { 'p', 16, 0, etPOINTER, 0, 1 },
96 /* All the rest are undocumented and are for internal use only */
97 { 'T', 0, 0, etTOKEN, 0, 0 },
98 { 'S', 0, 0, etSRCITEM, 0, 0 },
99 { 'r', 10, 1, etORDINAL, 0, 0 },
102 /* Notes:
104 ** %S Takes a pointer to SrcItem. Shows name or database.name
105 ** %!S Like %S but prefer the zName over the zAlias
109 ** Set the StrAccum object to an error mode.
111 void sqlite3StrAccumSetError(StrAccum *p, u8 eError){
112 assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
113 p->accError = eError;
114 if( p->mxAlloc ) sqlite3_str_reset(p);
115 if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
119 ** Extra argument values from a PrintfArguments object
121 static sqlite3_int64 getIntArg(PrintfArguments *p){
122 if( p->nArg<=p->nUsed ) return 0;
123 return sqlite3_value_int64(p->apArg[p->nUsed++]);
125 static double getDoubleArg(PrintfArguments *p){
126 if( p->nArg<=p->nUsed ) return 0.0;
127 return sqlite3_value_double(p->apArg[p->nUsed++]);
129 static char *getTextArg(PrintfArguments *p){
130 if( p->nArg<=p->nUsed ) return 0;
131 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
135 ** Allocate memory for a temporary buffer needed for printf rendering.
137 ** If the requested size of the temp buffer is larger than the size
138 ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
139 ** Do the size check before the memory allocation to prevent rogue
140 ** SQL from requesting large allocations using the precision or width
141 ** field of the printf() function.
143 static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
144 char *z;
145 if( pAccum->accError ) return 0;
146 if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
147 sqlite3StrAccumSetError(pAccum, SQLITE_TOOBIG);
148 return 0;
150 z = sqlite3DbMallocRaw(pAccum->db, n);
151 if( z==0 ){
152 sqlite3StrAccumSetError(pAccum, SQLITE_NOMEM);
154 return z;
158 ** On machines with a small stack size, you can redefine the
159 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
161 #ifndef SQLITE_PRINT_BUF_SIZE
162 # define SQLITE_PRINT_BUF_SIZE 70
163 #endif
164 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
167 ** Hard limit on the precision of floating-point conversions.
169 #ifndef SQLITE_PRINTF_PRECISION_LIMIT
170 # define SQLITE_FP_PRECISION_LIMIT 100000000
171 #endif
174 ** Render a string given by "fmt" into the StrAccum object.
176 void sqlite3_str_vappendf(
177 sqlite3_str *pAccum, /* Accumulate results here */
178 const char *fmt, /* Format string */
179 va_list ap /* arguments */
181 int c; /* Next character in the format string */
182 char *bufpt; /* Pointer to the conversion buffer */
183 int precision; /* Precision of the current field */
184 int length; /* Length of the field */
185 int idx; /* A general purpose loop counter */
186 int width; /* Width of the current field */
187 etByte flag_leftjustify; /* True if "-" flag is present */
188 etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
189 etByte flag_alternateform; /* True if "#" flag is present */
190 etByte flag_altform2; /* True if "!" flag is present */
191 etByte flag_zeropad; /* True if field width constant starts with zero */
192 etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
193 etByte done; /* Loop termination flag */
194 etByte cThousand; /* Thousands separator for %d and %u */
195 etByte xtype = etINVALID; /* Conversion paradigm */
196 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
197 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
198 sqlite_uint64 longvalue; /* Value for integer types */
199 double realvalue; /* Value for real types */
200 const et_info *infop; /* Pointer to the appropriate info structure */
201 char *zOut; /* Rendering buffer */
202 int nOut; /* Size of the rendering buffer */
203 char *zExtra = 0; /* Malloced memory used by some conversion */
204 int exp, e2; /* exponent of real numbers */
205 etByte flag_dp; /* True if decimal point should be shown */
206 etByte flag_rtz; /* True if trailing zeros should be removed */
208 PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
209 char buf[etBUFSIZE]; /* Conversion buffer */
211 /* pAccum never starts out with an empty buffer that was obtained from
212 ** malloc(). This precondition is required by the mprintf("%z...")
213 ** optimization. */
214 assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
216 bufpt = 0;
217 if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
218 pArgList = va_arg(ap, PrintfArguments*);
219 bArgList = 1;
220 }else{
221 bArgList = 0;
223 for(; (c=(*fmt))!=0; ++fmt){
224 if( c!='%' ){
225 bufpt = (char *)fmt;
226 #if HAVE_STRCHRNUL
227 fmt = strchrnul(fmt, '%');
228 #else
229 do{ fmt++; }while( *fmt && *fmt != '%' );
230 #endif
231 sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
232 if( *fmt==0 ) break;
234 if( (c=(*++fmt))==0 ){
235 sqlite3_str_append(pAccum, "%", 1);
236 break;
238 /* Find out what flags are present */
239 flag_leftjustify = flag_prefix = cThousand =
240 flag_alternateform = flag_altform2 = flag_zeropad = 0;
241 done = 0;
242 width = 0;
243 flag_long = 0;
244 precision = -1;
246 switch( c ){
247 case '-': flag_leftjustify = 1; break;
248 case '+': flag_prefix = '+'; break;
249 case ' ': flag_prefix = ' '; break;
250 case '#': flag_alternateform = 1; break;
251 case '!': flag_altform2 = 1; break;
252 case '0': flag_zeropad = 1; break;
253 case ',': cThousand = ','; break;
254 default: done = 1; break;
255 case 'l': {
256 flag_long = 1;
257 c = *++fmt;
258 if( c=='l' ){
259 c = *++fmt;
260 flag_long = 2;
262 done = 1;
263 break;
265 case '1': case '2': case '3': case '4': case '5':
266 case '6': case '7': case '8': case '9': {
267 unsigned wx = c - '0';
268 while( (c = *++fmt)>='0' && c<='9' ){
269 wx = wx*10 + c - '0';
271 testcase( wx>0x7fffffff );
272 width = wx & 0x7fffffff;
273 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
274 if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
275 width = SQLITE_PRINTF_PRECISION_LIMIT;
277 #endif
278 if( c!='.' && c!='l' ){
279 done = 1;
280 }else{
281 fmt--;
283 break;
285 case '*': {
286 if( bArgList ){
287 width = (int)getIntArg(pArgList);
288 }else{
289 width = va_arg(ap,int);
291 if( width<0 ){
292 flag_leftjustify = 1;
293 width = width >= -2147483647 ? -width : 0;
295 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
296 if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
297 width = SQLITE_PRINTF_PRECISION_LIMIT;
299 #endif
300 if( (c = fmt[1])!='.' && c!='l' ){
301 c = *++fmt;
302 done = 1;
304 break;
306 case '.': {
307 c = *++fmt;
308 if( c=='*' ){
309 if( bArgList ){
310 precision = (int)getIntArg(pArgList);
311 }else{
312 precision = va_arg(ap,int);
314 if( precision<0 ){
315 precision = precision >= -2147483647 ? -precision : -1;
317 c = *++fmt;
318 }else{
319 unsigned px = 0;
320 while( c>='0' && c<='9' ){
321 px = px*10 + c - '0';
322 c = *++fmt;
324 testcase( px>0x7fffffff );
325 precision = px & 0x7fffffff;
327 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
328 if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
329 precision = SQLITE_PRINTF_PRECISION_LIMIT;
331 #endif
332 if( c=='l' ){
333 --fmt;
334 }else{
335 done = 1;
337 break;
340 }while( !done && (c=(*++fmt))!=0 );
342 /* Fetch the info entry for the field */
343 infop = &fmtinfo[0];
344 xtype = etINVALID;
345 for(idx=0; idx<ArraySize(fmtinfo); idx++){
346 if( c==fmtinfo[idx].fmttype ){
347 infop = &fmtinfo[idx];
348 xtype = infop->type;
349 break;
354 ** At this point, variables are initialized as follows:
356 ** flag_alternateform TRUE if a '#' is present.
357 ** flag_altform2 TRUE if a '!' is present.
358 ** flag_prefix '+' or ' ' or zero
359 ** flag_leftjustify TRUE if a '-' is present or if the
360 ** field width was negative.
361 ** flag_zeropad TRUE if the width began with 0.
362 ** flag_long 1 for "l", 2 for "ll"
363 ** width The specified field width. This is
364 ** always non-negative. Zero is the default.
365 ** precision The specified precision. The default
366 ** is -1.
367 ** xtype The class of the conversion.
368 ** infop Pointer to the appropriate info struct.
370 assert( width>=0 );
371 assert( precision>=(-1) );
372 switch( xtype ){
373 case etPOINTER:
374 flag_long = sizeof(char*)==sizeof(i64) ? 2 :
375 sizeof(char*)==sizeof(long int) ? 1 : 0;
376 /* no break */ deliberate_fall_through
377 case etORDINAL:
378 case etRADIX:
379 cThousand = 0;
380 /* no break */ deliberate_fall_through
381 case etDECIMAL:
382 if( infop->flags & FLAG_SIGNED ){
383 i64 v;
384 if( bArgList ){
385 v = getIntArg(pArgList);
386 }else if( flag_long ){
387 if( flag_long==2 ){
388 v = va_arg(ap,i64) ;
389 }else{
390 v = va_arg(ap,long int);
392 }else{
393 v = va_arg(ap,int);
395 if( v<0 ){
396 testcase( v==SMALLEST_INT64 );
397 testcase( v==(-1) );
398 longvalue = ~v;
399 longvalue++;
400 prefix = '-';
401 }else{
402 longvalue = v;
403 prefix = flag_prefix;
405 }else{
406 if( bArgList ){
407 longvalue = (u64)getIntArg(pArgList);
408 }else if( flag_long ){
409 if( flag_long==2 ){
410 longvalue = va_arg(ap,u64);
411 }else{
412 longvalue = va_arg(ap,unsigned long int);
414 }else{
415 longvalue = va_arg(ap,unsigned int);
417 prefix = 0;
419 if( longvalue==0 ) flag_alternateform = 0;
420 if( flag_zeropad && precision<width-(prefix!=0) ){
421 precision = width-(prefix!=0);
423 if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
424 nOut = etBUFSIZE;
425 zOut = buf;
426 }else{
427 u64 n;
428 n = (u64)precision + 10;
429 if( cThousand ) n += precision/3;
430 zOut = zExtra = printfTempBuf(pAccum, n);
431 if( zOut==0 ) return;
432 nOut = (int)n;
434 bufpt = &zOut[nOut-1];
435 if( xtype==etORDINAL ){
436 static const char zOrd[] = "thstndrd";
437 int x = (int)(longvalue % 10);
438 if( x>=4 || (longvalue/10)%10==1 ){
439 x = 0;
441 *(--bufpt) = zOrd[x*2+1];
442 *(--bufpt) = zOrd[x*2];
445 const char *cset = &aDigits[infop->charset];
446 u8 base = infop->base;
447 do{ /* Convert to ascii */
448 *(--bufpt) = cset[longvalue%base];
449 longvalue = longvalue/base;
450 }while( longvalue>0 );
452 length = (int)(&zOut[nOut-1]-bufpt);
453 while( precision>length ){
454 *(--bufpt) = '0'; /* Zero pad */
455 length++;
457 if( cThousand ){
458 int nn = (length - 1)/3; /* Number of "," to insert */
459 int ix = (length - 1)%3 + 1;
460 bufpt -= nn;
461 for(idx=0; nn>0; idx++){
462 bufpt[idx] = bufpt[idx+nn];
463 ix--;
464 if( ix==0 ){
465 bufpt[++idx] = cThousand;
466 nn--;
467 ix = 3;
471 if( prefix ) *(--bufpt) = prefix; /* Add sign */
472 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
473 const char *pre;
474 char x;
475 pre = &aPrefix[infop->prefix];
476 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
478 length = (int)(&zOut[nOut-1]-bufpt);
479 break;
480 case etFLOAT:
481 case etEXP:
482 case etGENERIC: {
483 FpDecode s;
484 int iRound;
485 int j;
487 if( bArgList ){
488 realvalue = getDoubleArg(pArgList);
489 }else{
490 realvalue = va_arg(ap,double);
492 if( precision<0 ) precision = 6; /* Set default precision */
493 #ifdef SQLITE_FP_PRECISION_LIMIT
494 if( precision>SQLITE_FP_PRECISION_LIMIT ){
495 precision = SQLITE_FP_PRECISION_LIMIT;
497 #endif
498 if( xtype==etFLOAT ){
499 iRound = -precision;
500 }else if( xtype==etGENERIC ){
501 if( precision==0 ) precision = 1;
502 iRound = precision;
503 }else{
504 iRound = precision+1;
506 sqlite3FpDecode(&s, realvalue, iRound, flag_altform2 ? 26 : 16);
507 if( s.isSpecial ){
508 if( s.isSpecial==2 ){
509 bufpt = flag_zeropad ? "null" : "NaN";
510 length = sqlite3Strlen30(bufpt);
511 break;
512 }else if( flag_zeropad ){
513 s.z[0] = '9';
514 s.iDP = 1000;
515 s.n = 1;
516 }else{
517 memcpy(buf, "-Inf", 5);
518 bufpt = buf;
519 if( s.sign=='-' ){
520 /* no-op */
521 }else if( flag_prefix ){
522 buf[0] = flag_prefix;
523 }else{
524 bufpt++;
526 length = sqlite3Strlen30(bufpt);
527 break;
530 if( s.sign=='-' ){
531 prefix = '-';
532 }else{
533 prefix = flag_prefix;
536 exp = s.iDP-1;
539 ** If the field type is etGENERIC, then convert to either etEXP
540 ** or etFLOAT, as appropriate.
542 if( xtype==etGENERIC ){
543 assert( precision>0 );
544 precision--;
545 flag_rtz = !flag_alternateform;
546 if( exp<-4 || exp>precision ){
547 xtype = etEXP;
548 }else{
549 precision = precision - exp;
550 xtype = etFLOAT;
552 }else{
553 flag_rtz = flag_altform2;
555 if( xtype==etEXP ){
556 e2 = 0;
557 }else{
558 e2 = s.iDP - 1;
560 bufpt = buf;
562 i64 szBufNeeded; /* Size of a temporary buffer needed */
563 szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
564 if( cThousand && e2>0 ) szBufNeeded += (e2+2)/3;
565 if( szBufNeeded > etBUFSIZE ){
566 bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
567 if( bufpt==0 ) return;
570 zOut = bufpt;
571 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
572 /* The sign in front of the number */
573 if( prefix ){
574 *(bufpt++) = prefix;
576 /* Digits prior to the decimal point */
577 j = 0;
578 if( e2<0 ){
579 *(bufpt++) = '0';
580 }else{
581 for(; e2>=0; e2--){
582 *(bufpt++) = j<s.n ? s.z[j++] : '0';
583 if( cThousand && (e2%3)==0 && e2>1 ) *(bufpt++) = ',';
586 /* The decimal point */
587 if( flag_dp ){
588 *(bufpt++) = '.';
590 /* "0" digits after the decimal point but before the first
591 ** significant digit of the number */
592 for(e2++; e2<0 && precision>0; precision--, e2++){
593 *(bufpt++) = '0';
595 /* Significant digits after the decimal point */
596 while( (precision--)>0 ){
597 *(bufpt++) = j<s.n ? s.z[j++] : '0';
599 /* Remove trailing zeros and the "." if no digits follow the "." */
600 if( flag_rtz && flag_dp ){
601 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
602 assert( bufpt>zOut );
603 if( bufpt[-1]=='.' ){
604 if( flag_altform2 ){
605 *(bufpt++) = '0';
606 }else{
607 *(--bufpt) = 0;
611 /* Add the "eNNN" suffix */
612 if( xtype==etEXP ){
613 exp = s.iDP - 1;
614 *(bufpt++) = aDigits[infop->charset];
615 if( exp<0 ){
616 *(bufpt++) = '-'; exp = -exp;
617 }else{
618 *(bufpt++) = '+';
620 if( exp>=100 ){
621 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
622 exp %= 100;
624 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
625 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
627 *bufpt = 0;
629 /* The converted number is in buf[] and zero terminated. Output it.
630 ** Note that the number is in the usual order, not reversed as with
631 ** integer conversions. */
632 length = (int)(bufpt-zOut);
633 bufpt = zOut;
635 /* Special case: Add leading zeros if the flag_zeropad flag is
636 ** set and we are not left justified */
637 if( flag_zeropad && !flag_leftjustify && length < width){
638 int i;
639 int nPad = width - length;
640 for(i=width; i>=nPad; i--){
641 bufpt[i] = bufpt[i-nPad];
643 i = prefix!=0;
644 while( nPad-- ) bufpt[i++] = '0';
645 length = width;
647 break;
649 case etSIZE:
650 if( !bArgList ){
651 *(va_arg(ap,int*)) = pAccum->nChar;
653 length = width = 0;
654 break;
655 case etPERCENT:
656 buf[0] = '%';
657 bufpt = buf;
658 length = 1;
659 break;
660 case etCHARX:
661 if( bArgList ){
662 bufpt = getTextArg(pArgList);
663 length = 1;
664 if( bufpt ){
665 buf[0] = c = *(bufpt++);
666 if( (c&0xc0)==0xc0 ){
667 while( length<4 && (bufpt[0]&0xc0)==0x80 ){
668 buf[length++] = *(bufpt++);
671 }else{
672 buf[0] = 0;
674 }else{
675 unsigned int ch = va_arg(ap,unsigned int);
676 if( ch<0x00080 ){
677 buf[0] = ch & 0xff;
678 length = 1;
679 }else if( ch<0x00800 ){
680 buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
681 buf[1] = 0x80 + (u8)(ch & 0x3f);
682 length = 2;
683 }else if( ch<0x10000 ){
684 buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
685 buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
686 buf[2] = 0x80 + (u8)(ch & 0x3f);
687 length = 3;
688 }else{
689 buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
690 buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
691 buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
692 buf[3] = 0x80 + (u8)(ch & 0x3f);
693 length = 4;
696 if( precision>1 ){
697 i64 nPrior = 1;
698 width -= precision-1;
699 if( width>1 && !flag_leftjustify ){
700 sqlite3_str_appendchar(pAccum, width-1, ' ');
701 width = 0;
703 sqlite3_str_append(pAccum, buf, length);
704 precision--;
705 while( precision > 1 ){
706 i64 nCopyBytes;
707 if( nPrior > precision-1 ) nPrior = precision - 1;
708 nCopyBytes = length*nPrior;
709 if( nCopyBytes + pAccum->nChar >= pAccum->nAlloc ){
710 sqlite3StrAccumEnlarge(pAccum, nCopyBytes);
712 if( pAccum->accError ) break;
713 sqlite3_str_append(pAccum,
714 &pAccum->zText[pAccum->nChar-nCopyBytes], nCopyBytes);
715 precision -= nPrior;
716 nPrior *= 2;
719 bufpt = buf;
720 flag_altform2 = 1;
721 goto adjust_width_for_utf8;
722 case etSTRING:
723 case etDYNSTRING:
724 if( bArgList ){
725 bufpt = getTextArg(pArgList);
726 xtype = etSTRING;
727 }else{
728 bufpt = va_arg(ap,char*);
730 if( bufpt==0 ){
731 bufpt = "";
732 }else if( xtype==etDYNSTRING ){
733 if( pAccum->nChar==0
734 && pAccum->mxAlloc
735 && width==0
736 && precision<0
737 && pAccum->accError==0
739 /* Special optimization for sqlite3_mprintf("%z..."):
740 ** Extend an existing memory allocation rather than creating
741 ** a new one. */
742 assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
743 pAccum->zText = bufpt;
744 pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
745 pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
746 pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
747 length = 0;
748 break;
750 zExtra = bufpt;
752 if( precision>=0 ){
753 if( flag_altform2 ){
754 /* Set length to the number of bytes needed in order to display
755 ** precision characters */
756 unsigned char *z = (unsigned char*)bufpt;
757 while( precision-- > 0 && z[0] ){
758 SQLITE_SKIP_UTF8(z);
760 length = (int)(z - (unsigned char*)bufpt);
761 }else{
762 for(length=0; length<precision && bufpt[length]; length++){}
764 }else{
765 length = 0x7fffffff & (int)strlen(bufpt);
767 adjust_width_for_utf8:
768 if( flag_altform2 && width>0 ){
769 /* Adjust width to account for extra bytes in UTF-8 characters */
770 int ii = length - 1;
771 while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
773 break;
774 case etSQLESCAPE: /* %q: Escape ' characters */
775 case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
776 case etSQLESCAPE3: { /* %w: Escape " characters */
777 i64 i, j, k, n;
778 int needQuote, isnull;
779 char ch;
780 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
781 char *escarg;
783 if( bArgList ){
784 escarg = getTextArg(pArgList);
785 }else{
786 escarg = va_arg(ap,char*);
788 isnull = escarg==0;
789 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
790 /* For %q, %Q, and %w, the precision is the number of bytes (or
791 ** characters if the ! flags is present) to use from the input.
792 ** Because of the extra quoting characters inserted, the number
793 ** of output characters may be larger than the precision.
795 k = precision;
796 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
797 if( ch==q ) n++;
798 if( flag_altform2 && (ch&0xc0)==0xc0 ){
799 while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
802 needQuote = !isnull && xtype==etSQLESCAPE2;
803 n += i + 3;
804 if( n>etBUFSIZE ){
805 bufpt = zExtra = printfTempBuf(pAccum, n);
806 if( bufpt==0 ) return;
807 }else{
808 bufpt = buf;
810 j = 0;
811 if( needQuote ) bufpt[j++] = q;
812 k = i;
813 for(i=0; i<k; i++){
814 bufpt[j++] = ch = escarg[i];
815 if( ch==q ) bufpt[j++] = ch;
817 if( needQuote ) bufpt[j++] = q;
818 bufpt[j] = 0;
819 length = j;
820 goto adjust_width_for_utf8;
822 case etTOKEN: {
823 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
824 if( flag_alternateform ){
825 /* %#T means an Expr pointer that uses Expr.u.zToken */
826 Expr *pExpr = va_arg(ap,Expr*);
827 if( ALWAYS(pExpr) && ALWAYS(!ExprHasProperty(pExpr,EP_IntValue)) ){
828 sqlite3_str_appendall(pAccum, (const char*)pExpr->u.zToken);
829 sqlite3RecordErrorOffsetOfExpr(pAccum->db, pExpr);
831 }else{
832 /* %T means a Token pointer */
833 Token *pToken = va_arg(ap, Token*);
834 assert( bArgList==0 );
835 if( pToken && pToken->n ){
836 sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
837 sqlite3RecordErrorByteOffset(pAccum->db, pToken->z);
840 length = width = 0;
841 break;
843 case etSRCITEM: {
844 SrcItem *pItem;
845 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
846 pItem = va_arg(ap, SrcItem*);
847 assert( bArgList==0 );
848 if( pItem->zAlias && !flag_altform2 ){
849 sqlite3_str_appendall(pAccum, pItem->zAlias);
850 }else if( pItem->zName ){
851 if( pItem->zDatabase ){
852 sqlite3_str_appendall(pAccum, pItem->zDatabase);
853 sqlite3_str_append(pAccum, ".", 1);
855 sqlite3_str_appendall(pAccum, pItem->zName);
856 }else if( pItem->zAlias ){
857 sqlite3_str_appendall(pAccum, pItem->zAlias);
858 }else{
859 Select *pSel = pItem->pSelect;
860 assert( pSel!=0 ); /* Because of tag-20240424-1 */
861 if( pSel->selFlags & SF_NestedFrom ){
862 sqlite3_str_appendf(pAccum, "(join-%u)", pSel->selId);
863 }else if( pSel->selFlags & SF_MultiValue ){
864 assert( !pItem->fg.isTabFunc && !pItem->fg.isIndexedBy );
865 sqlite3_str_appendf(pAccum, "%u-ROW VALUES CLAUSE",
866 pItem->u1.nRow);
867 }else{
868 sqlite3_str_appendf(pAccum, "(subquery-%u)", pSel->selId);
871 length = width = 0;
872 break;
874 default: {
875 assert( xtype==etINVALID );
876 return;
878 }/* End switch over the format type */
880 ** The text of the conversion is pointed to by "bufpt" and is
881 ** "length" characters long. The field width is "width". Do
882 ** the output. Both length and width are in bytes, not characters,
883 ** at this point. If the "!" flag was present on string conversions
884 ** indicating that width and precision should be expressed in characters,
885 ** then the values have been translated prior to reaching this point.
887 width -= length;
888 if( width>0 ){
889 if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
890 sqlite3_str_append(pAccum, bufpt, length);
891 if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
892 }else{
893 sqlite3_str_append(pAccum, bufpt, length);
896 if( zExtra ){
897 sqlite3DbFree(pAccum->db, zExtra);
898 zExtra = 0;
900 }/* End for loop over the format string */
901 } /* End of function */
905 ** The z string points to the first character of a token that is
906 ** associated with an error. If db does not already have an error
907 ** byte offset recorded, try to compute the error byte offset for
908 ** z and set the error byte offset in db.
910 void sqlite3RecordErrorByteOffset(sqlite3 *db, const char *z){
911 const Parse *pParse;
912 const char *zText;
913 const char *zEnd;
914 assert( z!=0 );
915 if( NEVER(db==0) ) return;
916 if( db->errByteOffset!=(-2) ) return;
917 pParse = db->pParse;
918 if( NEVER(pParse==0) ) return;
919 zText =pParse->zTail;
920 if( NEVER(zText==0) ) return;
921 zEnd = &zText[strlen(zText)];
922 if( SQLITE_WITHIN(z,zText,zEnd) ){
923 db->errByteOffset = (int)(z-zText);
928 ** If pExpr has a byte offset for the start of a token, record that as
929 ** as the error offset.
931 void sqlite3RecordErrorOffsetOfExpr(sqlite3 *db, const Expr *pExpr){
932 while( pExpr
933 && (ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) || pExpr->w.iOfst<=0)
935 pExpr = pExpr->pLeft;
937 if( pExpr==0 ) return;
938 db->errByteOffset = pExpr->w.iOfst;
942 ** Enlarge the memory allocation on a StrAccum object so that it is
943 ** able to accept at least N more bytes of text.
945 ** Return the number of bytes of text that StrAccum is able to accept
946 ** after the attempted enlargement. The value returned might be zero.
948 int sqlite3StrAccumEnlarge(StrAccum *p, i64 N){
949 char *zNew;
950 assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
951 if( p->accError ){
952 testcase(p->accError==SQLITE_TOOBIG);
953 testcase(p->accError==SQLITE_NOMEM);
954 return 0;
956 if( p->mxAlloc==0 ){
957 sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
958 return p->nAlloc - p->nChar - 1;
959 }else{
960 char *zOld = isMalloced(p) ? p->zText : 0;
961 i64 szNew = p->nChar + N + 1;
962 if( szNew+p->nChar<=p->mxAlloc ){
963 /* Force exponential buffer size growth as long as it does not overflow,
964 ** to avoid having to call this routine too often */
965 szNew += p->nChar;
967 if( szNew > p->mxAlloc ){
968 sqlite3_str_reset(p);
969 sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
970 return 0;
971 }else{
972 p->nAlloc = (int)szNew;
974 if( p->db ){
975 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
976 }else{
977 zNew = sqlite3Realloc(zOld, p->nAlloc);
979 if( zNew ){
980 assert( p->zText!=0 || p->nChar==0 );
981 if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
982 p->zText = zNew;
983 p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
984 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
985 }else{
986 sqlite3_str_reset(p);
987 sqlite3StrAccumSetError(p, SQLITE_NOMEM);
988 return 0;
991 assert( N>=0 && N<=0x7fffffff );
992 return (int)N;
996 ** Append N copies of character c to the given string buffer.
998 void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
999 testcase( p->nChar + (i64)N > 0x7fffffff );
1000 if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
1001 return;
1003 while( (N--)>0 ) p->zText[p->nChar++] = c;
1007 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
1008 ** So enlarge if first, then do the append.
1010 ** This is a helper routine to sqlite3_str_append() that does special-case
1011 ** work (enlarging the buffer) using tail recursion, so that the
1012 ** sqlite3_str_append() routine can use fast calling semantics.
1014 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
1015 N = sqlite3StrAccumEnlarge(p, N);
1016 if( N>0 ){
1017 memcpy(&p->zText[p->nChar], z, N);
1018 p->nChar += N;
1023 ** Append N bytes of text from z to the StrAccum object. Increase the
1024 ** size of the memory allocation for StrAccum if necessary.
1026 void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
1027 assert( z!=0 || N==0 );
1028 assert( p->zText!=0 || p->nChar==0 || p->accError );
1029 assert( N>=0 );
1030 assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
1031 if( p->nChar+N >= p->nAlloc ){
1032 enlargeAndAppend(p,z,N);
1033 }else if( N ){
1034 assert( p->zText );
1035 p->nChar += N;
1036 memcpy(&p->zText[p->nChar-N], z, N);
1041 ** Append the complete text of zero-terminated string z[] to the p string.
1043 void sqlite3_str_appendall(sqlite3_str *p, const char *z){
1044 sqlite3_str_append(p, z, sqlite3Strlen30(z));
1049 ** Finish off a string by making sure it is zero-terminated.
1050 ** Return a pointer to the resulting string. Return a NULL
1051 ** pointer if any kind of error was encountered.
1053 static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
1054 char *zText;
1055 assert( p->mxAlloc>0 && !isMalloced(p) );
1056 zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
1057 if( zText ){
1058 memcpy(zText, p->zText, p->nChar+1);
1059 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
1060 }else{
1061 sqlite3StrAccumSetError(p, SQLITE_NOMEM);
1063 p->zText = zText;
1064 return zText;
1066 char *sqlite3StrAccumFinish(StrAccum *p){
1067 if( p->zText ){
1068 p->zText[p->nChar] = 0;
1069 if( p->mxAlloc>0 && !isMalloced(p) ){
1070 return strAccumFinishRealloc(p);
1073 return p->zText;
1077 ** Use the content of the StrAccum passed as the second argument
1078 ** as the result of an SQL function.
1080 void sqlite3ResultStrAccum(sqlite3_context *pCtx, StrAccum *p){
1081 if( p->accError ){
1082 sqlite3_result_error_code(pCtx, p->accError);
1083 sqlite3_str_reset(p);
1084 }else if( isMalloced(p) ){
1085 sqlite3_result_text(pCtx, p->zText, p->nChar, SQLITE_DYNAMIC);
1086 }else{
1087 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
1088 sqlite3_str_reset(p);
1093 ** This singleton is an sqlite3_str object that is returned if
1094 ** sqlite3_malloc() fails to provide space for a real one. This
1095 ** sqlite3_str object accepts no new text and always returns
1096 ** an SQLITE_NOMEM error.
1098 static sqlite3_str sqlite3OomStr = {
1099 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
1102 /* Finalize a string created using sqlite3_str_new().
1104 char *sqlite3_str_finish(sqlite3_str *p){
1105 char *z;
1106 if( p!=0 && p!=&sqlite3OomStr ){
1107 z = sqlite3StrAccumFinish(p);
1108 sqlite3_free(p);
1109 }else{
1110 z = 0;
1112 return z;
1115 /* Return any error code associated with p */
1116 int sqlite3_str_errcode(sqlite3_str *p){
1117 return p ? p->accError : SQLITE_NOMEM;
1120 /* Return the current length of p in bytes */
1121 int sqlite3_str_length(sqlite3_str *p){
1122 return p ? p->nChar : 0;
1125 /* Return the current value for p */
1126 char *sqlite3_str_value(sqlite3_str *p){
1127 if( p==0 || p->nChar==0 ) return 0;
1128 p->zText[p->nChar] = 0;
1129 return p->zText;
1133 ** Reset an StrAccum string. Reclaim all malloced memory.
1135 void sqlite3_str_reset(StrAccum *p){
1136 if( isMalloced(p) ){
1137 sqlite3DbFree(p->db, p->zText);
1138 p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
1140 p->nAlloc = 0;
1141 p->nChar = 0;
1142 p->zText = 0;
1146 ** Initialize a string accumulator.
1148 ** p: The accumulator to be initialized.
1149 ** db: Pointer to a database connection. May be NULL. Lookaside
1150 ** memory is used if not NULL. db->mallocFailed is set appropriately
1151 ** when not NULL.
1152 ** zBase: An initial buffer. May be NULL in which case the initial buffer
1153 ** is malloced.
1154 ** n: Size of zBase in bytes. If total space requirements never exceed
1155 ** n then no memory allocations ever occur.
1156 ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
1157 ** allocations will ever occur.
1159 void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
1160 p->zText = zBase;
1161 p->db = db;
1162 p->nAlloc = n;
1163 p->mxAlloc = mx;
1164 p->nChar = 0;
1165 p->accError = 0;
1166 p->printfFlags = 0;
1169 /* Allocate and initialize a new dynamic string object */
1170 sqlite3_str *sqlite3_str_new(sqlite3 *db){
1171 sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
1172 if( p ){
1173 sqlite3StrAccumInit(p, 0, 0, 0,
1174 db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
1175 }else{
1176 p = &sqlite3OomStr;
1178 return p;
1182 ** Print into memory obtained from sqliteMalloc(). Use the internal
1183 ** %-conversion extensions.
1185 char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
1186 char *z;
1187 char zBase[SQLITE_PRINT_BUF_SIZE];
1188 StrAccum acc;
1189 assert( db!=0 );
1190 sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
1191 db->aLimit[SQLITE_LIMIT_LENGTH]);
1192 acc.printfFlags = SQLITE_PRINTF_INTERNAL;
1193 sqlite3_str_vappendf(&acc, zFormat, ap);
1194 z = sqlite3StrAccumFinish(&acc);
1195 if( acc.accError==SQLITE_NOMEM ){
1196 sqlite3OomFault(db);
1198 return z;
1202 ** Print into memory obtained from sqliteMalloc(). Use the internal
1203 ** %-conversion extensions.
1205 char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
1206 va_list ap;
1207 char *z;
1208 va_start(ap, zFormat);
1209 z = sqlite3VMPrintf(db, zFormat, ap);
1210 va_end(ap);
1211 return z;
1215 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
1216 ** %-conversion extensions.
1218 char *sqlite3_vmprintf(const char *zFormat, va_list ap){
1219 char *z;
1220 char zBase[SQLITE_PRINT_BUF_SIZE];
1221 StrAccum acc;
1223 #ifdef SQLITE_ENABLE_API_ARMOR
1224 if( zFormat==0 ){
1225 (void)SQLITE_MISUSE_BKPT;
1226 return 0;
1228 #endif
1229 #ifndef SQLITE_OMIT_AUTOINIT
1230 if( sqlite3_initialize() ) return 0;
1231 #endif
1232 sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
1233 sqlite3_str_vappendf(&acc, zFormat, ap);
1234 z = sqlite3StrAccumFinish(&acc);
1235 return z;
1239 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
1240 ** %-conversion extensions.
1242 char *sqlite3_mprintf(const char *zFormat, ...){
1243 va_list ap;
1244 char *z;
1245 #ifndef SQLITE_OMIT_AUTOINIT
1246 if( sqlite3_initialize() ) return 0;
1247 #endif
1248 va_start(ap, zFormat);
1249 z = sqlite3_vmprintf(zFormat, ap);
1250 va_end(ap);
1251 return z;
1255 ** sqlite3_snprintf() works like snprintf() except that it ignores the
1256 ** current locale settings. This is important for SQLite because we
1257 ** are not able to use a "," as the decimal point in place of "." as
1258 ** specified by some locales.
1260 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
1261 ** from the snprintf() standard. Unfortunately, it is too late to change
1262 ** this without breaking compatibility, so we just have to live with the
1263 ** mistake.
1265 ** sqlite3_vsnprintf() is the varargs version.
1267 char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
1268 StrAccum acc;
1269 if( n<=0 ) return zBuf;
1270 #ifdef SQLITE_ENABLE_API_ARMOR
1271 if( zBuf==0 || zFormat==0 ) {
1272 (void)SQLITE_MISUSE_BKPT;
1273 if( zBuf ) zBuf[0] = 0;
1274 return zBuf;
1276 #endif
1277 sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
1278 sqlite3_str_vappendf(&acc, zFormat, ap);
1279 zBuf[acc.nChar] = 0;
1280 return zBuf;
1282 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
1283 StrAccum acc;
1284 va_list ap;
1285 if( n<=0 ) return zBuf;
1286 #ifdef SQLITE_ENABLE_API_ARMOR
1287 if( zBuf==0 || zFormat==0 ) {
1288 (void)SQLITE_MISUSE_BKPT;
1289 if( zBuf ) zBuf[0] = 0;
1290 return zBuf;
1292 #endif
1293 sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
1294 va_start(ap,zFormat);
1295 sqlite3_str_vappendf(&acc, zFormat, ap);
1296 va_end(ap);
1297 zBuf[acc.nChar] = 0;
1298 return zBuf;
1302 ** This is the routine that actually formats the sqlite3_log() message.
1303 ** We house it in a separate routine from sqlite3_log() to avoid using
1304 ** stack space on small-stack systems when logging is disabled.
1306 ** sqlite3_log() must render into a static buffer. It cannot dynamically
1307 ** allocate memory because it might be called while the memory allocator
1308 ** mutex is held.
1310 ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
1311 ** certain format characters (%q) or for very large precisions or widths.
1312 ** Care must be taken that any sqlite3_log() calls that occur while the
1313 ** memory mutex is held do not use these mechanisms.
1315 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
1316 StrAccum acc; /* String accumulator */
1317 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
1319 sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
1320 sqlite3_str_vappendf(&acc, zFormat, ap);
1321 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
1322 sqlite3StrAccumFinish(&acc));
1326 ** Format and write a message to the log if logging is enabled.
1328 void sqlite3_log(int iErrCode, const char *zFormat, ...){
1329 va_list ap; /* Vararg list */
1330 if( sqlite3GlobalConfig.xLog ){
1331 va_start(ap, zFormat);
1332 renderLogMsg(iErrCode, zFormat, ap);
1333 va_end(ap);
1337 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
1339 ** A version of printf() that understands %lld. Used for debugging.
1340 ** The printf() built into some versions of windows does not understand %lld
1341 ** and segfaults if you give it a long long int.
1343 void sqlite3DebugPrintf(const char *zFormat, ...){
1344 va_list ap;
1345 StrAccum acc;
1346 char zBuf[SQLITE_PRINT_BUF_SIZE*10];
1347 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
1348 va_start(ap,zFormat);
1349 sqlite3_str_vappendf(&acc, zFormat, ap);
1350 va_end(ap);
1351 sqlite3StrAccumFinish(&acc);
1352 #ifdef SQLITE_OS_TRACE_PROC
1354 extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
1355 SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
1357 #else
1358 fprintf(stdout,"%s", zBuf);
1359 fflush(stdout);
1360 #endif
1362 #endif
1366 ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
1367 ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
1369 void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
1370 va_list ap;
1371 va_start(ap,zFormat);
1372 sqlite3_str_vappendf(p, zFormat, ap);
1373 va_end(ap);
1377 /*****************************************************************************
1378 ** Reference counted string/blob storage
1379 *****************************************************************************/
1382 ** Increase the reference count of the string by one.
1384 ** The input parameter is returned.
1386 char *sqlite3RCStrRef(char *z){
1387 RCStr *p = (RCStr*)z;
1388 assert( p!=0 );
1389 p--;
1390 p->nRCRef++;
1391 return z;
1395 ** Decrease the reference count by one. Free the string when the
1396 ** reference count reaches zero.
1398 void sqlite3RCStrUnref(void *z){
1399 RCStr *p = (RCStr*)z;
1400 assert( p!=0 );
1401 p--;
1402 assert( p->nRCRef>0 );
1403 if( p->nRCRef>=2 ){
1404 p->nRCRef--;
1405 }else{
1406 sqlite3_free(p);
1411 ** Create a new string that is capable of holding N bytes of text, not counting
1412 ** the zero byte at the end. The string is uninitialized.
1414 ** The reference count is initially 1. Call sqlite3RCStrUnref() to free the
1415 ** newly allocated string.
1417 ** This routine returns 0 on an OOM.
1419 char *sqlite3RCStrNew(u64 N){
1420 RCStr *p = sqlite3_malloc64( N + sizeof(*p) + 1 );
1421 if( p==0 ) return 0;
1422 p->nRCRef = 1;
1423 return (char*)&p[1];
1427 ** Change the size of the string so that it is able to hold N bytes.
1428 ** The string might be reallocated, so return the new allocation.
1430 char *sqlite3RCStrResize(char *z, u64 N){
1431 RCStr *p = (RCStr*)z;
1432 RCStr *pNew;
1433 assert( p!=0 );
1434 p--;
1435 assert( p->nRCRef==1 );
1436 pNew = sqlite3_realloc64(p, N+sizeof(RCStr)+1);
1437 if( pNew==0 ){
1438 sqlite3_free(p);
1439 return 0;
1440 }else{
1441 return (char*)&pNew[1];