Update mojo sdk to rev 1dc8a9a5db73d3718d99917fadf31f5fb2ebad4f
[chromium-blink-merge.git] / third_party / sqlite / sqlite-src-3080704 / src / printf.c
blob387b9e90c18e241a983095429b235d0b2d95f1ec
1 /*
2 ** The "printf" code that follows dates from the 1980's. It is in
3 ** the public domain. The original comments are included here for
4 ** completeness. They are very out-of-date but might be useful as
5 ** an historical reference. Most of the "enhancements" have been backed
6 ** out so that the functionality is now the same as standard printf().
7 **
8 **************************************************************************
9 **
10 ** This file contains code for a set of "printf"-like routines. These
11 ** routines format strings much like the printf() from the standard C
12 ** library, though the implementation here has enhancements to support
13 ** SQLlite.
15 #include "sqliteInt.h"
18 ** If the strchrnul() library function is available, then set
19 ** HAVE_STRCHRNUL. If that routine is not available, this module
20 ** will supply its own. The built-in version is slower than
21 ** the glibc version so the glibc version is definitely preferred.
23 #if !defined(HAVE_STRCHRNUL)
24 # define HAVE_STRCHRNUL 0
25 #endif
29 ** Conversion types fall into various categories as defined by the
30 ** following enumeration.
32 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
33 #define etFLOAT 2 /* Floating point. %f */
34 #define etEXP 3 /* Exponentional notation. %e and %E */
35 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
36 #define etSIZE 5 /* Return number of characters processed so far. %n */
37 #define etSTRING 6 /* Strings. %s */
38 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
39 #define etPERCENT 8 /* Percent symbol. %% */
40 #define etCHARX 9 /* Characters. %c */
41 /* The rest are extensions, not normally found in printf() */
42 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
43 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
44 NULL pointers replaced by SQL NULL. %Q */
45 #define etTOKEN 12 /* a pointer to a Token structure */
46 #define etSRCLIST 13 /* a pointer to a SrcList */
47 #define etPOINTER 14 /* The %p conversion */
48 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
49 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
51 #define etINVALID 0 /* Any unrecognized conversion type */
55 ** An "etByte" is an 8-bit unsigned value.
57 typedef unsigned char etByte;
60 ** Each builtin conversion character (ex: the 'd' in "%d") is described
61 ** by an instance of the following structure
63 typedef struct et_info { /* Information about each format field */
64 char fmttype; /* The format field code letter */
65 etByte base; /* The base for radix conversion */
66 etByte flags; /* One or more of FLAG_ constants below */
67 etByte type; /* Conversion paradigm */
68 etByte charset; /* Offset into aDigits[] of the digits string */
69 etByte prefix; /* Offset into aPrefix[] of the prefix string */
70 } et_info;
73 ** Allowed values for et_info.flags
75 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
76 #define FLAG_INTERN 2 /* True if for internal use only */
77 #define FLAG_STRING 4 /* Allow infinity precision */
81 ** The following table is searched linearly, so it is good to put the
82 ** most frequently used conversion types first.
84 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
85 static const char aPrefix[] = "-x0\000X0";
86 static const et_info fmtinfo[] = {
87 { 'd', 10, 1, etRADIX, 0, 0 },
88 { 's', 0, 4, etSTRING, 0, 0 },
89 { 'g', 0, 1, etGENERIC, 30, 0 },
90 { 'z', 0, 4, etDYNSTRING, 0, 0 },
91 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
92 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
93 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
94 { 'c', 0, 0, etCHARX, 0, 0 },
95 { 'o', 8, 0, etRADIX, 0, 2 },
96 { 'u', 10, 0, etRADIX, 0, 0 },
97 { 'x', 16, 0, etRADIX, 16, 1 },
98 { 'X', 16, 0, etRADIX, 0, 4 },
99 #ifndef SQLITE_OMIT_FLOATING_POINT
100 { 'f', 0, 1, etFLOAT, 0, 0 },
101 { 'e', 0, 1, etEXP, 30, 0 },
102 { 'E', 0, 1, etEXP, 14, 0 },
103 { 'G', 0, 1, etGENERIC, 14, 0 },
104 #endif
105 { 'i', 10, 1, etRADIX, 0, 0 },
106 { 'n', 0, 0, etSIZE, 0, 0 },
107 { '%', 0, 0, etPERCENT, 0, 0 },
108 { 'p', 16, 0, etPOINTER, 0, 1 },
110 /* All the rest have the FLAG_INTERN bit set and are thus for internal
111 ** use only */
112 { 'T', 0, 2, etTOKEN, 0, 0 },
113 { 'S', 0, 2, etSRCLIST, 0, 0 },
114 { 'r', 10, 3, etORDINAL, 0, 0 },
118 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
119 ** conversions will work.
121 #ifndef SQLITE_OMIT_FLOATING_POINT
123 ** "*val" is a double such that 0.1 <= *val < 10.0
124 ** Return the ascii code for the leading digit of *val, then
125 ** multiply "*val" by 10.0 to renormalize.
127 ** Example:
128 ** input: *val = 3.14159
129 ** output: *val = 1.4159 function return = '3'
131 ** The counter *cnt is incremented each time. After counter exceeds
132 ** 16 (the number of significant digits in a 64-bit float) '0' is
133 ** always returned.
135 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
136 int digit;
137 LONGDOUBLE_TYPE d;
138 if( (*cnt)<=0 ) return '0';
139 (*cnt)--;
140 digit = (int)*val;
141 d = digit;
142 digit += '0';
143 *val = (*val - d)*10.0;
144 return (char)digit;
146 #endif /* SQLITE_OMIT_FLOATING_POINT */
149 ** Set the StrAccum object to an error mode.
151 static void setStrAccumError(StrAccum *p, u8 eError){
152 p->accError = eError;
153 p->nAlloc = 0;
157 ** Extra argument values from a PrintfArguments object
159 static sqlite3_int64 getIntArg(PrintfArguments *p){
160 if( p->nArg<=p->nUsed ) return 0;
161 return sqlite3_value_int64(p->apArg[p->nUsed++]);
163 static double getDoubleArg(PrintfArguments *p){
164 if( p->nArg<=p->nUsed ) return 0.0;
165 return sqlite3_value_double(p->apArg[p->nUsed++]);
167 static char *getTextArg(PrintfArguments *p){
168 if( p->nArg<=p->nUsed ) return 0;
169 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
174 ** On machines with a small stack size, you can redefine the
175 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
177 #ifndef SQLITE_PRINT_BUF_SIZE
178 # define SQLITE_PRINT_BUF_SIZE 70
179 #endif
180 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
183 ** Render a string given by "fmt" into the StrAccum object.
185 void sqlite3VXPrintf(
186 StrAccum *pAccum, /* Accumulate results here */
187 u32 bFlags, /* SQLITE_PRINTF_* flags */
188 const char *fmt, /* Format string */
189 va_list ap /* arguments */
191 int c; /* Next character in the format string */
192 char *bufpt; /* Pointer to the conversion buffer */
193 int precision; /* Precision of the current field */
194 int length; /* Length of the field */
195 int idx; /* A general purpose loop counter */
196 int width; /* Width of the current field */
197 etByte flag_leftjustify; /* True if "-" flag is present */
198 etByte flag_plussign; /* True if "+" flag is present */
199 etByte flag_blanksign; /* True if " " flag is present */
200 etByte flag_alternateform; /* True if "#" flag is present */
201 etByte flag_altform2; /* True if "!" flag is present */
202 etByte flag_zeropad; /* True if field width constant starts with zero */
203 etByte flag_long; /* True if "l" flag is present */
204 etByte flag_longlong; /* True if the "ll" flag is present */
205 etByte done; /* Loop termination flag */
206 etByte xtype = 0; /* Conversion paradigm */
207 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
208 u8 useIntern; /* Ok to use internal conversions (ex: %T) */
209 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
210 sqlite_uint64 longvalue; /* Value for integer types */
211 LONGDOUBLE_TYPE realvalue; /* Value for real types */
212 const et_info *infop; /* Pointer to the appropriate info structure */
213 char *zOut; /* Rendering buffer */
214 int nOut; /* Size of the rendering buffer */
215 char *zExtra = 0; /* Malloced memory used by some conversion */
216 #ifndef SQLITE_OMIT_FLOATING_POINT
217 int exp, e2; /* exponent of real numbers */
218 int nsd; /* Number of significant digits returned */
219 double rounder; /* Used for rounding floating point values */
220 etByte flag_dp; /* True if decimal point should be shown */
221 etByte flag_rtz; /* True if trailing zeros should be removed */
222 #endif
223 PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
224 char buf[etBUFSIZE]; /* Conversion buffer */
226 bufpt = 0;
227 if( bFlags ){
228 if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
229 pArgList = va_arg(ap, PrintfArguments*);
231 useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
232 }else{
233 bArgList = useIntern = 0;
235 for(; (c=(*fmt))!=0; ++fmt){
236 if( c!='%' ){
237 bufpt = (char *)fmt;
238 #if HAVE_STRCHRNUL
239 fmt = strchrnul(fmt, '%');
240 #else
241 do{ fmt++; }while( *fmt && *fmt != '%' );
242 #endif
243 sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
244 if( *fmt==0 ) break;
246 if( (c=(*++fmt))==0 ){
247 sqlite3StrAccumAppend(pAccum, "%", 1);
248 break;
250 /* Find out what flags are present */
251 flag_leftjustify = flag_plussign = flag_blanksign =
252 flag_alternateform = flag_altform2 = flag_zeropad = 0;
253 done = 0;
255 switch( c ){
256 case '-': flag_leftjustify = 1; break;
257 case '+': flag_plussign = 1; break;
258 case ' ': flag_blanksign = 1; break;
259 case '#': flag_alternateform = 1; break;
260 case '!': flag_altform2 = 1; break;
261 case '0': flag_zeropad = 1; break;
262 default: done = 1; break;
264 }while( !done && (c=(*++fmt))!=0 );
265 /* Get the field width */
266 width = 0;
267 if( c=='*' ){
268 if( bArgList ){
269 width = (int)getIntArg(pArgList);
270 }else{
271 width = va_arg(ap,int);
273 if( width<0 ){
274 flag_leftjustify = 1;
275 width = -width;
277 c = *++fmt;
278 }else{
279 while( c>='0' && c<='9' ){
280 width = width*10 + c - '0';
281 c = *++fmt;
284 /* Get the precision */
285 if( c=='.' ){
286 precision = 0;
287 c = *++fmt;
288 if( c=='*' ){
289 if( bArgList ){
290 precision = (int)getIntArg(pArgList);
291 }else{
292 precision = va_arg(ap,int);
294 if( precision<0 ) precision = -precision;
295 c = *++fmt;
296 }else{
297 while( c>='0' && c<='9' ){
298 precision = precision*10 + c - '0';
299 c = *++fmt;
302 }else{
303 precision = -1;
305 /* Get the conversion type modifier */
306 if( c=='l' ){
307 flag_long = 1;
308 c = *++fmt;
309 if( c=='l' ){
310 flag_longlong = 1;
311 c = *++fmt;
312 }else{
313 flag_longlong = 0;
315 }else{
316 flag_long = flag_longlong = 0;
318 /* Fetch the info entry for the field */
319 infop = &fmtinfo[0];
320 xtype = etINVALID;
321 for(idx=0; idx<ArraySize(fmtinfo); idx++){
322 if( c==fmtinfo[idx].fmttype ){
323 infop = &fmtinfo[idx];
324 if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
325 xtype = infop->type;
326 }else{
327 return;
329 break;
334 ** At this point, variables are initialized as follows:
336 ** flag_alternateform TRUE if a '#' is present.
337 ** flag_altform2 TRUE if a '!' is present.
338 ** flag_plussign TRUE if a '+' is present.
339 ** flag_leftjustify TRUE if a '-' is present or if the
340 ** field width was negative.
341 ** flag_zeropad TRUE if the width began with 0.
342 ** flag_long TRUE if the letter 'l' (ell) prefixed
343 ** the conversion character.
344 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
345 ** the conversion character.
346 ** flag_blanksign TRUE if a ' ' is present.
347 ** width The specified field width. This is
348 ** always non-negative. Zero is the default.
349 ** precision The specified precision. The default
350 ** is -1.
351 ** xtype The class of the conversion.
352 ** infop Pointer to the appropriate info struct.
354 switch( xtype ){
355 case etPOINTER:
356 flag_longlong = sizeof(char*)==sizeof(i64);
357 flag_long = sizeof(char*)==sizeof(long int);
358 /* Fall through into the next case */
359 case etORDINAL:
360 case etRADIX:
361 if( infop->flags & FLAG_SIGNED ){
362 i64 v;
363 if( bArgList ){
364 v = getIntArg(pArgList);
365 }else if( flag_longlong ){
366 v = va_arg(ap,i64);
367 }else if( flag_long ){
368 v = va_arg(ap,long int);
369 }else{
370 v = va_arg(ap,int);
372 if( v<0 ){
373 if( v==SMALLEST_INT64 ){
374 longvalue = ((u64)1)<<63;
375 }else{
376 longvalue = -v;
378 prefix = '-';
379 }else{
380 longvalue = v;
381 if( flag_plussign ) prefix = '+';
382 else if( flag_blanksign ) prefix = ' ';
383 else prefix = 0;
385 }else{
386 if( bArgList ){
387 longvalue = (u64)getIntArg(pArgList);
388 }else if( flag_longlong ){
389 longvalue = va_arg(ap,u64);
390 }else if( flag_long ){
391 longvalue = va_arg(ap,unsigned long int);
392 }else{
393 longvalue = va_arg(ap,unsigned int);
395 prefix = 0;
397 if( longvalue==0 ) flag_alternateform = 0;
398 if( flag_zeropad && precision<width-(prefix!=0) ){
399 precision = width-(prefix!=0);
401 if( precision<etBUFSIZE-10 ){
402 nOut = etBUFSIZE;
403 zOut = buf;
404 }else{
405 nOut = precision + 10;
406 zOut = zExtra = sqlite3Malloc( nOut );
407 if( zOut==0 ){
408 setStrAccumError(pAccum, STRACCUM_NOMEM);
409 return;
412 bufpt = &zOut[nOut-1];
413 if( xtype==etORDINAL ){
414 static const char zOrd[] = "thstndrd";
415 int x = (int)(longvalue % 10);
416 if( x>=4 || (longvalue/10)%10==1 ){
417 x = 0;
419 *(--bufpt) = zOrd[x*2+1];
420 *(--bufpt) = zOrd[x*2];
423 const char *cset = &aDigits[infop->charset];
424 u8 base = infop->base;
425 do{ /* Convert to ascii */
426 *(--bufpt) = cset[longvalue%base];
427 longvalue = longvalue/base;
428 }while( longvalue>0 );
430 length = (int)(&zOut[nOut-1]-bufpt);
431 for(idx=precision-length; idx>0; idx--){
432 *(--bufpt) = '0'; /* Zero pad */
434 if( prefix ) *(--bufpt) = prefix; /* Add sign */
435 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
436 const char *pre;
437 char x;
438 pre = &aPrefix[infop->prefix];
439 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
441 length = (int)(&zOut[nOut-1]-bufpt);
442 break;
443 case etFLOAT:
444 case etEXP:
445 case etGENERIC:
446 if( bArgList ){
447 realvalue = getDoubleArg(pArgList);
448 }else{
449 realvalue = va_arg(ap,double);
451 #ifdef SQLITE_OMIT_FLOATING_POINT
452 length = 0;
453 #else
454 if( precision<0 ) precision = 6; /* Set default precision */
455 if( realvalue<0.0 ){
456 realvalue = -realvalue;
457 prefix = '-';
458 }else{
459 if( flag_plussign ) prefix = '+';
460 else if( flag_blanksign ) prefix = ' ';
461 else prefix = 0;
463 if( xtype==etGENERIC && precision>0 ) precision--;
464 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
465 if( xtype==etFLOAT ) realvalue += rounder;
466 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
467 exp = 0;
468 if( sqlite3IsNaN((double)realvalue) ){
469 bufpt = "NaN";
470 length = 3;
471 break;
473 if( realvalue>0.0 ){
474 LONGDOUBLE_TYPE scale = 1.0;
475 while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
476 while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
477 while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
478 while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
479 realvalue /= scale;
480 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
481 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
482 if( exp>350 ){
483 if( prefix=='-' ){
484 bufpt = "-Inf";
485 }else if( prefix=='+' ){
486 bufpt = "+Inf";
487 }else{
488 bufpt = "Inf";
490 length = sqlite3Strlen30(bufpt);
491 break;
494 bufpt = buf;
496 ** If the field type is etGENERIC, then convert to either etEXP
497 ** or etFLOAT, as appropriate.
499 if( xtype!=etFLOAT ){
500 realvalue += rounder;
501 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
503 if( xtype==etGENERIC ){
504 flag_rtz = !flag_alternateform;
505 if( exp<-4 || exp>precision ){
506 xtype = etEXP;
507 }else{
508 precision = precision - exp;
509 xtype = etFLOAT;
511 }else{
512 flag_rtz = flag_altform2;
514 if( xtype==etEXP ){
515 e2 = 0;
516 }else{
517 e2 = exp;
519 if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
520 bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
521 if( bufpt==0 ){
522 setStrAccumError(pAccum, STRACCUM_NOMEM);
523 return;
526 zOut = bufpt;
527 nsd = 16 + flag_altform2*10;
528 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
529 /* The sign in front of the number */
530 if( prefix ){
531 *(bufpt++) = prefix;
533 /* Digits prior to the decimal point */
534 if( e2<0 ){
535 *(bufpt++) = '0';
536 }else{
537 for(; e2>=0; e2--){
538 *(bufpt++) = et_getdigit(&realvalue,&nsd);
541 /* The decimal point */
542 if( flag_dp ){
543 *(bufpt++) = '.';
545 /* "0" digits after the decimal point but before the first
546 ** significant digit of the number */
547 for(e2++; e2<0; precision--, e2++){
548 assert( precision>0 );
549 *(bufpt++) = '0';
551 /* Significant digits after the decimal point */
552 while( (precision--)>0 ){
553 *(bufpt++) = et_getdigit(&realvalue,&nsd);
555 /* Remove trailing zeros and the "." if no digits follow the "." */
556 if( flag_rtz && flag_dp ){
557 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
558 assert( bufpt>zOut );
559 if( bufpt[-1]=='.' ){
560 if( flag_altform2 ){
561 *(bufpt++) = '0';
562 }else{
563 *(--bufpt) = 0;
567 /* Add the "eNNN" suffix */
568 if( xtype==etEXP ){
569 *(bufpt++) = aDigits[infop->charset];
570 if( exp<0 ){
571 *(bufpt++) = '-'; exp = -exp;
572 }else{
573 *(bufpt++) = '+';
575 if( exp>=100 ){
576 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
577 exp %= 100;
579 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
580 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
582 *bufpt = 0;
584 /* The converted number is in buf[] and zero terminated. Output it.
585 ** Note that the number is in the usual order, not reversed as with
586 ** integer conversions. */
587 length = (int)(bufpt-zOut);
588 bufpt = zOut;
590 /* Special case: Add leading zeros if the flag_zeropad flag is
591 ** set and we are not left justified */
592 if( flag_zeropad && !flag_leftjustify && length < width){
593 int i;
594 int nPad = width - length;
595 for(i=width; i>=nPad; i--){
596 bufpt[i] = bufpt[i-nPad];
598 i = prefix!=0;
599 while( nPad-- ) bufpt[i++] = '0';
600 length = width;
602 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
603 break;
604 case etSIZE:
605 if( !bArgList ){
606 *(va_arg(ap,int*)) = pAccum->nChar;
608 length = width = 0;
609 break;
610 case etPERCENT:
611 buf[0] = '%';
612 bufpt = buf;
613 length = 1;
614 break;
615 case etCHARX:
616 if( bArgList ){
617 bufpt = getTextArg(pArgList);
618 c = bufpt ? bufpt[0] : 0;
619 }else{
620 c = va_arg(ap,int);
622 if( precision>1 ){
623 width -= precision-1;
624 if( width>1 && !flag_leftjustify ){
625 sqlite3AppendChar(pAccum, width-1, ' ');
626 width = 0;
628 sqlite3AppendChar(pAccum, precision-1, c);
630 length = 1;
631 buf[0] = c;
632 bufpt = buf;
633 break;
634 case etSTRING:
635 case etDYNSTRING:
636 if( bArgList ){
637 bufpt = getTextArg(pArgList);
638 }else{
639 bufpt = va_arg(ap,char*);
641 if( bufpt==0 ){
642 bufpt = "";
643 }else if( xtype==etDYNSTRING && !bArgList ){
644 zExtra = bufpt;
646 if( precision>=0 ){
647 for(length=0; length<precision && bufpt[length]; length++){}
648 }else{
649 length = sqlite3Strlen30(bufpt);
651 break;
652 case etSQLESCAPE:
653 case etSQLESCAPE2:
654 case etSQLESCAPE3: {
655 int i, j, k, n, isnull;
656 int needQuote;
657 char ch;
658 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
659 char *escarg;
661 if( bArgList ){
662 escarg = getTextArg(pArgList);
663 }else{
664 escarg = va_arg(ap,char*);
666 isnull = escarg==0;
667 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
668 k = precision;
669 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
670 if( ch==q ) n++;
672 needQuote = !isnull && xtype==etSQLESCAPE2;
673 n += i + 1 + needQuote*2;
674 if( n>etBUFSIZE ){
675 bufpt = zExtra = sqlite3Malloc( n );
676 if( bufpt==0 ){
677 setStrAccumError(pAccum, STRACCUM_NOMEM);
678 return;
680 }else{
681 bufpt = buf;
683 j = 0;
684 if( needQuote ) bufpt[j++] = q;
685 k = i;
686 for(i=0; i<k; i++){
687 bufpt[j++] = ch = escarg[i];
688 if( ch==q ) bufpt[j++] = ch;
690 if( needQuote ) bufpt[j++] = q;
691 bufpt[j] = 0;
692 length = j;
693 /* The precision in %q and %Q means how many input characters to
694 ** consume, not the length of the output...
695 ** if( precision>=0 && precision<length ) length = precision; */
696 break;
698 case etTOKEN: {
699 Token *pToken = va_arg(ap, Token*);
700 assert( bArgList==0 );
701 if( pToken && pToken->n ){
702 sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
704 length = width = 0;
705 break;
707 case etSRCLIST: {
708 SrcList *pSrc = va_arg(ap, SrcList*);
709 int k = va_arg(ap, int);
710 struct SrcList_item *pItem = &pSrc->a[k];
711 assert( bArgList==0 );
712 assert( k>=0 && k<pSrc->nSrc );
713 if( pItem->zDatabase ){
714 sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
715 sqlite3StrAccumAppend(pAccum, ".", 1);
717 sqlite3StrAccumAppendAll(pAccum, pItem->zName);
718 length = width = 0;
719 break;
721 default: {
722 assert( xtype==etINVALID );
723 return;
725 }/* End switch over the format type */
727 ** The text of the conversion is pointed to by "bufpt" and is
728 ** "length" characters long. The field width is "width". Do
729 ** the output.
731 width -= length;
732 if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
733 sqlite3StrAccumAppend(pAccum, bufpt, length);
734 if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
736 if( zExtra ){
737 sqlite3_free(zExtra);
738 zExtra = 0;
740 }/* End for loop over the format string */
741 } /* End of function */
744 ** Enlarge the memory allocation on a StrAccum object so that it is
745 ** able to accept at least N more bytes of text.
747 ** Return the number of bytes of text that StrAccum is able to accept
748 ** after the attempted enlargement. The value returned might be zero.
750 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
751 char *zNew;
752 assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
753 if( p->accError ){
754 testcase(p->accError==STRACCUM_TOOBIG);
755 testcase(p->accError==STRACCUM_NOMEM);
756 return 0;
758 if( !p->useMalloc ){
759 N = p->nAlloc - p->nChar - 1;
760 setStrAccumError(p, STRACCUM_TOOBIG);
761 return N;
762 }else{
763 char *zOld = (p->zText==p->zBase ? 0 : p->zText);
764 i64 szNew = p->nChar;
765 szNew += N + 1;
766 if( szNew > p->mxAlloc ){
767 sqlite3StrAccumReset(p);
768 setStrAccumError(p, STRACCUM_TOOBIG);
769 return 0;
770 }else{
771 p->nAlloc = (int)szNew;
773 if( p->useMalloc==1 ){
774 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
775 }else{
776 zNew = sqlite3_realloc(zOld, p->nAlloc);
778 if( zNew ){
779 assert( p->zText!=0 || p->nChar==0 );
780 if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
781 p->zText = zNew;
782 }else{
783 sqlite3StrAccumReset(p);
784 setStrAccumError(p, STRACCUM_NOMEM);
785 return 0;
788 return N;
792 ** Append N copies of character c to the given string buffer.
794 void sqlite3AppendChar(StrAccum *p, int N, char c){
795 if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ) return;
796 while( (N--)>0 ) p->zText[p->nChar++] = c;
800 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
801 ** So enlarge if first, then do the append.
803 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
804 ** work (enlarging the buffer) using tail recursion, so that the
805 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
807 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
808 N = sqlite3StrAccumEnlarge(p, N);
809 if( N>0 ){
810 memcpy(&p->zText[p->nChar], z, N);
811 p->nChar += N;
816 ** Append N bytes of text from z to the StrAccum object. Increase the
817 ** size of the memory allocation for StrAccum if necessary.
819 void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
820 assert( z!=0 );
821 assert( p->zText!=0 || p->nChar==0 || p->accError );
822 assert( N>=0 );
823 assert( p->accError==0 || p->nAlloc==0 );
824 if( p->nChar+N >= p->nAlloc ){
825 enlargeAndAppend(p,z,N);
826 }else{
827 assert( p->zText );
828 p->nChar += N;
829 memcpy(&p->zText[p->nChar-N], z, N);
834 ** Append the complete text of zero-terminated string z[] to the p string.
836 void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
837 sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
842 ** Finish off a string by making sure it is zero-terminated.
843 ** Return a pointer to the resulting string. Return a NULL
844 ** pointer if any kind of error was encountered.
846 char *sqlite3StrAccumFinish(StrAccum *p){
847 if( p->zText ){
848 p->zText[p->nChar] = 0;
849 if( p->useMalloc && p->zText==p->zBase ){
850 if( p->useMalloc==1 ){
851 p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
852 }else{
853 p->zText = sqlite3_malloc(p->nChar+1);
855 if( p->zText ){
856 memcpy(p->zText, p->zBase, p->nChar+1);
857 }else{
858 setStrAccumError(p, STRACCUM_NOMEM);
862 return p->zText;
866 ** Reset an StrAccum string. Reclaim all malloced memory.
868 void sqlite3StrAccumReset(StrAccum *p){
869 if( p->zText!=p->zBase ){
870 if( p->useMalloc==1 ){
871 sqlite3DbFree(p->db, p->zText);
872 }else{
873 sqlite3_free(p->zText);
876 p->zText = 0;
880 ** Initialize a string accumulator
882 void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
883 p->zText = p->zBase = zBase;
884 p->db = 0;
885 p->nChar = 0;
886 p->nAlloc = n;
887 p->mxAlloc = mx;
888 p->useMalloc = 1;
889 p->accError = 0;
893 ** Print into memory obtained from sqliteMalloc(). Use the internal
894 ** %-conversion extensions.
896 char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
897 char *z;
898 char zBase[SQLITE_PRINT_BUF_SIZE];
899 StrAccum acc;
900 assert( db!=0 );
901 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
902 db->aLimit[SQLITE_LIMIT_LENGTH]);
903 acc.db = db;
904 sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
905 z = sqlite3StrAccumFinish(&acc);
906 if( acc.accError==STRACCUM_NOMEM ){
907 db->mallocFailed = 1;
909 return z;
913 ** Print into memory obtained from sqliteMalloc(). Use the internal
914 ** %-conversion extensions.
916 char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
917 va_list ap;
918 char *z;
919 va_start(ap, zFormat);
920 z = sqlite3VMPrintf(db, zFormat, ap);
921 va_end(ap);
922 return z;
926 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
927 ** the string and before returning. This routine is intended to be used
928 ** to modify an existing string. For example:
930 ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
933 char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
934 va_list ap;
935 char *z;
936 va_start(ap, zFormat);
937 z = sqlite3VMPrintf(db, zFormat, ap);
938 va_end(ap);
939 sqlite3DbFree(db, zStr);
940 return z;
944 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
945 ** %-conversion extensions.
947 char *sqlite3_vmprintf(const char *zFormat, va_list ap){
948 char *z;
949 char zBase[SQLITE_PRINT_BUF_SIZE];
950 StrAccum acc;
951 #ifndef SQLITE_OMIT_AUTOINIT
952 if( sqlite3_initialize() ) return 0;
953 #endif
954 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
955 acc.useMalloc = 2;
956 sqlite3VXPrintf(&acc, 0, zFormat, ap);
957 z = sqlite3StrAccumFinish(&acc);
958 return z;
962 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
963 ** %-conversion extensions.
965 char *sqlite3_mprintf(const char *zFormat, ...){
966 va_list ap;
967 char *z;
968 #ifndef SQLITE_OMIT_AUTOINIT
969 if( sqlite3_initialize() ) return 0;
970 #endif
971 va_start(ap, zFormat);
972 z = sqlite3_vmprintf(zFormat, ap);
973 va_end(ap);
974 return z;
978 ** sqlite3_snprintf() works like snprintf() except that it ignores the
979 ** current locale settings. This is important for SQLite because we
980 ** are not able to use a "," as the decimal point in place of "." as
981 ** specified by some locales.
983 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
984 ** from the snprintf() standard. Unfortunately, it is too late to change
985 ** this without breaking compatibility, so we just have to live with the
986 ** mistake.
988 ** sqlite3_vsnprintf() is the varargs version.
990 char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
991 StrAccum acc;
992 if( n<=0 ) return zBuf;
993 sqlite3StrAccumInit(&acc, zBuf, n, 0);
994 acc.useMalloc = 0;
995 sqlite3VXPrintf(&acc, 0, zFormat, ap);
996 return sqlite3StrAccumFinish(&acc);
998 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
999 char *z;
1000 va_list ap;
1001 va_start(ap,zFormat);
1002 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
1003 va_end(ap);
1004 return z;
1008 ** This is the routine that actually formats the sqlite3_log() message.
1009 ** We house it in a separate routine from sqlite3_log() to avoid using
1010 ** stack space on small-stack systems when logging is disabled.
1012 ** sqlite3_log() must render into a static buffer. It cannot dynamically
1013 ** allocate memory because it might be called while the memory allocator
1014 ** mutex is held.
1016 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
1017 StrAccum acc; /* String accumulator */
1018 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
1020 sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
1021 acc.useMalloc = 0;
1022 sqlite3VXPrintf(&acc, 0, zFormat, ap);
1023 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
1024 sqlite3StrAccumFinish(&acc));
1028 ** Format and write a message to the log if logging is enabled.
1030 void sqlite3_log(int iErrCode, const char *zFormat, ...){
1031 va_list ap; /* Vararg list */
1032 if( sqlite3GlobalConfig.xLog ){
1033 va_start(ap, zFormat);
1034 renderLogMsg(iErrCode, zFormat, ap);
1035 va_end(ap);
1039 #if defined(SQLITE_DEBUG)
1041 ** A version of printf() that understands %lld. Used for debugging.
1042 ** The printf() built into some versions of windows does not understand %lld
1043 ** and segfaults if you give it a long long int.
1045 void sqlite3DebugPrintf(const char *zFormat, ...){
1046 va_list ap;
1047 StrAccum acc;
1048 char zBuf[500];
1049 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
1050 acc.useMalloc = 0;
1051 va_start(ap,zFormat);
1052 sqlite3VXPrintf(&acc, 0, zFormat, ap);
1053 va_end(ap);
1054 sqlite3StrAccumFinish(&acc);
1055 fprintf(stdout,"%s", zBuf);
1056 fflush(stdout);
1058 #endif
1060 #ifdef SQLITE_DEBUG
1061 /*************************************************************************
1062 ** Routines for implementing the "TreeView" display of hierarchical
1063 ** data structures for debugging.
1065 ** The main entry points (coded elsewhere) are:
1066 ** sqlite3TreeViewExpr(0, pExpr, 0);
1067 ** sqlite3TreeViewExprList(0, pList, 0, 0);
1068 ** sqlite3TreeViewSelect(0, pSelect, 0);
1069 ** Insert calls to those routines while debugging in order to display
1070 ** a diagram of Expr, ExprList, and Select objects.
1073 /* Add a new subitem to the tree. The moreToFollow flag indicates that this
1074 ** is not the last item in the tree. */
1075 TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
1076 if( p==0 ){
1077 p = sqlite3_malloc( sizeof(*p) );
1078 if( p==0 ) return 0;
1079 memset(p, 0, sizeof(*p));
1080 }else{
1081 p->iLevel++;
1083 assert( moreToFollow==0 || moreToFollow==1 );
1084 if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
1085 return p;
1087 /* Finished with one layer of the tree */
1088 void sqlite3TreeViewPop(TreeView *p){
1089 if( p==0 ) return;
1090 p->iLevel--;
1091 if( p->iLevel<0 ) sqlite3_free(p);
1093 /* Generate a single line of output for the tree, with a prefix that contains
1094 ** all the appropriate tree lines */
1095 void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
1096 va_list ap;
1097 int i;
1098 StrAccum acc;
1099 char zBuf[500];
1100 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
1101 acc.useMalloc = 0;
1102 if( p ){
1103 for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
1104 sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
1106 sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
1108 va_start(ap, zFormat);
1109 sqlite3VXPrintf(&acc, 0, zFormat, ap);
1110 va_end(ap);
1111 if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
1112 sqlite3StrAccumFinish(&acc);
1113 fprintf(stdout,"%s", zBuf);
1114 fflush(stdout);
1116 /* Shorthand for starting a new tree item that consists of a single label */
1117 void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){
1118 p = sqlite3TreeViewPush(p, moreToFollow);
1119 sqlite3TreeViewLine(p, "%s", zLabel);
1121 #endif /* SQLITE_DEBUG */
1124 ** variable-argument wrapper around sqlite3VXPrintf().
1126 void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
1127 va_list ap;
1128 va_start(ap,zFormat);
1129 sqlite3VXPrintf(p, bFlags, zFormat, ap);
1130 va_end(ap);