xref: /sqlite-3.40.0/src/printf.c (revision b6907e29)
1a18c5681Sdrh /*
2a18c5681Sdrh ** The "printf" code that follows dates from the 1980's.  It is in
338b4149cSdrh ** the public domain.
4e84a306bSdrh **
5e84a306bSdrh **************************************************************************
6a18c5681Sdrh **
7ed1fddf4Sdrh ** This file contains code for a set of "printf"-like routines.  These
8ed1fddf4Sdrh ** routines format strings much like the printf() from the standard C
9ed1fddf4Sdrh ** library, though the implementation here has enhancements to support
10f5b5f9b9Smistachkin ** SQLite.
11a18c5681Sdrh */
12a18c5681Sdrh #include "sqliteInt.h"
137c68d60bSdrh 
14a18c5681Sdrh /*
15a18c5681Sdrh ** Conversion types fall into various categories as defined by the
16a18c5681Sdrh ** following enumeration.
17a18c5681Sdrh */
182c338a9dSdrh #define etRADIX       0 /* non-decimal integer types.  %x %o */
19ad5a9d71Sdrh #define etFLOAT       1 /* Floating point.  %f */
20ad5a9d71Sdrh #define etEXP         2 /* Exponentional notation. %e and %E */
21ad5a9d71Sdrh #define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
22ad5a9d71Sdrh #define etSIZE        4 /* Return number of characters processed so far. %n */
23ad5a9d71Sdrh #define etSTRING      5 /* Strings. %s */
24ad5a9d71Sdrh #define etDYNSTRING   6 /* Dynamically allocated strings. %z */
25ad5a9d71Sdrh #define etPERCENT     7 /* Percent symbol. %% */
26ad5a9d71Sdrh #define etCHARX       8 /* Characters. %c */
27a18c5681Sdrh /* The rest are extensions, not normally found in printf() */
28ad5a9d71Sdrh #define etSQLESCAPE   9 /* Strings with '\'' doubled.  %q */
29ad5a9d71Sdrh #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
300cfcf3fbSchw                           NULL pointers replaced by SQL NULL.  %Q */
31ad5a9d71Sdrh #define etTOKEN      11 /* a pointer to a Token structure */
32ad5a9d71Sdrh #define etSRCLIST    12 /* a pointer to a SrcList */
33ad5a9d71Sdrh #define etPOINTER    13 /* The %p conversion */
34ad5a9d71Sdrh #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
35ad5a9d71Sdrh #define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
362c338a9dSdrh #define etDECIMAL    16 /* %d or %u, but not %x, %o */
37e84a306bSdrh 
382c338a9dSdrh #define etINVALID    17 /* Any unrecognized conversion type */
39874ba04cSdrh 
40e84a306bSdrh 
41e84a306bSdrh /*
42e84a306bSdrh ** An "etByte" is an 8-bit unsigned value.
43e84a306bSdrh */
44e84a306bSdrh typedef unsigned char etByte;
45a18c5681Sdrh 
46a18c5681Sdrh /*
47a18c5681Sdrh ** Each builtin conversion character (ex: the 'd' in "%d") is described
48a18c5681Sdrh ** by an instance of the following structure
49a18c5681Sdrh */
50a18c5681Sdrh typedef struct et_info {   /* Information about each format field */
51e84a306bSdrh   char fmttype;            /* The format field code letter */
52e84a306bSdrh   etByte base;             /* The base for radix conversion */
53e84a306bSdrh   etByte flags;            /* One or more of FLAG_ constants below */
54e84a306bSdrh   etByte type;             /* Conversion paradigm */
5576ff3a0eSdrh   etByte charset;          /* Offset into aDigits[] of the digits string */
5676ff3a0eSdrh   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
57a18c5681Sdrh } et_info;
58a18c5681Sdrh 
59a18c5681Sdrh /*
60e84a306bSdrh ** Allowed values for et_info.flags
61e84a306bSdrh */
62e84a306bSdrh #define FLAG_SIGNED    1     /* True if the value to convert is signed */
632c338a9dSdrh #define FLAG_STRING    4     /* Allow infinite precision */
64e84a306bSdrh 
65e84a306bSdrh 
66e84a306bSdrh /*
67a18c5681Sdrh ** The following table is searched linearly, so it is good to put the
68a18c5681Sdrh ** most frequently used conversion types first.
69a18c5681Sdrh */
7076ff3a0eSdrh static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
7176ff3a0eSdrh static const char aPrefix[] = "-x0\000X0";
725719628aSdrh static const et_info fmtinfo[] = {
732c338a9dSdrh   {  'd', 10, 1, etDECIMAL,    0,  0 },
744794f735Sdrh   {  's',  0, 4, etSTRING,     0,  0 },
75557cc60fSdrh   {  'g',  0, 1, etGENERIC,    30, 0 },
76153c62c4Sdrh   {  'z',  0, 4, etDYNSTRING,  0,  0 },
774794f735Sdrh   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
784794f735Sdrh   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
79f3b863edSdanielk1977   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
80e84a306bSdrh   {  'c',  0, 0, etCHARX,      0,  0 },
8176ff3a0eSdrh   {  'o',  8, 0, etRADIX,      0,  2 },
822c338a9dSdrh   {  'u', 10, 0, etDECIMAL,    0,  0 },
8376ff3a0eSdrh   {  'x', 16, 0, etRADIX,      16, 1 },
8476ff3a0eSdrh   {  'X', 16, 0, etRADIX,      0,  4 },
85b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
86e84a306bSdrh   {  'f',  0, 1, etFLOAT,      0,  0 },
8776ff3a0eSdrh   {  'e',  0, 1, etEXP,        30, 0 },
8876ff3a0eSdrh   {  'E',  0, 1, etEXP,        14, 0 },
8976ff3a0eSdrh   {  'G',  0, 1, etGENERIC,    14, 0 },
90b37df7b9Sdrh #endif
912c338a9dSdrh   {  'i', 10, 1, etDECIMAL,    0,  0 },
92e84a306bSdrh   {  'n',  0, 0, etSIZE,       0,  0 },
93e84a306bSdrh   {  '%',  0, 0, etPERCENT,    0,  0 },
9476ff3a0eSdrh   {  'p', 16, 0, etPOINTER,    0,  1 },
957e3ff5d8Sdrh 
968236f688Sdrh   /* All the rest are undocumented and are for internal use only */
978236f688Sdrh   {  'T',  0, 0, etTOKEN,      0,  0 },
988236f688Sdrh   {  'S',  0, 0, etSRCLIST,    0,  0 },
998236f688Sdrh   {  'r', 10, 1, etORDINAL,    0,  0 },
100a18c5681Sdrh };
101a18c5681Sdrh 
102a0ed86bcSdrh /* Floating point constants used for rounding */
103a0ed86bcSdrh static const double arRound[] = {
104a0ed86bcSdrh   5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
105a0ed86bcSdrh   5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,
106a0ed86bcSdrh };
107a0ed86bcSdrh 
108a18c5681Sdrh /*
109b37df7b9Sdrh ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
110a18c5681Sdrh ** conversions will work.
111a18c5681Sdrh */
112b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
113a18c5681Sdrh /*
114a18c5681Sdrh ** "*val" is a double such that 0.1 <= *val < 10.0
115a18c5681Sdrh ** Return the ascii code for the leading digit of *val, then
116a18c5681Sdrh ** multiply "*val" by 10.0 to renormalize.
117a18c5681Sdrh **
118a18c5681Sdrh ** Example:
119a18c5681Sdrh **     input:     *val = 3.14159
120a18c5681Sdrh **     output:    *val = 1.4159    function return = '3'
121a18c5681Sdrh **
122a18c5681Sdrh ** The counter *cnt is incremented each time.  After counter exceeds
123a18c5681Sdrh ** 16 (the number of significant digits in a 64-bit float) '0' is
124a18c5681Sdrh ** always returned.
125a18c5681Sdrh */
126ea678832Sdrh static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
127a18c5681Sdrh   int digit;
128384eef32Sdrh   LONGDOUBLE_TYPE d;
12972b3fbc7Sdrh   if( (*cnt)<=0 ) return '0';
13072b3fbc7Sdrh   (*cnt)--;
131a18c5681Sdrh   digit = (int)*val;
132a18c5681Sdrh   d = digit;
133a18c5681Sdrh   digit += '0';
134a18c5681Sdrh   *val = (*val - d)*10.0;
135ea678832Sdrh   return (char)digit;
136a18c5681Sdrh }
137b37df7b9Sdrh #endif /* SQLITE_OMIT_FLOATING_POINT */
138a18c5681Sdrh 
13979158e18Sdrh /*
140a6353a3fSdrh ** Set the StrAccum object to an error mode.
141a6353a3fSdrh */
142a5c1416dSdrh static void setStrAccumError(StrAccum *p, u8 eError){
1430cdbe1aeSdrh   assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
144a6353a3fSdrh   p->accError = eError;
145255a81f1Sdrh   if( p->mxAlloc ) sqlite3_str_reset(p);
146c3dcdba3Sdrh   if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
147a6353a3fSdrh }
148a6353a3fSdrh 
149a6353a3fSdrh /*
150a5c1416dSdrh ** Extra argument values from a PrintfArguments object
151a5c1416dSdrh */
152a5c1416dSdrh static sqlite3_int64 getIntArg(PrintfArguments *p){
153a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0;
154a5c1416dSdrh   return sqlite3_value_int64(p->apArg[p->nUsed++]);
155a5c1416dSdrh }
156a5c1416dSdrh static double getDoubleArg(PrintfArguments *p){
157a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0.0;
158a5c1416dSdrh   return sqlite3_value_double(p->apArg[p->nUsed++]);
159a5c1416dSdrh }
160a5c1416dSdrh static char *getTextArg(PrintfArguments *p){
161a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0;
162a5c1416dSdrh   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
163a5c1416dSdrh }
164a5c1416dSdrh 
16529642252Sdrh /*
16629642252Sdrh ** Allocate memory for a temporary buffer needed for printf rendering.
16729642252Sdrh **
16829642252Sdrh ** If the requested size of the temp buffer is larger than the size
16929642252Sdrh ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
17029642252Sdrh ** Do the size check before the memory allocation to prevent rogue
17129642252Sdrh ** SQL from requesting large allocations using the precision or width
17229642252Sdrh ** field of the printf() function.
17329642252Sdrh */
17429642252Sdrh static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
17529642252Sdrh   char *z;
176255a81f1Sdrh   if( pAccum->accError ) return 0;
17729642252Sdrh   if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
17829642252Sdrh     setStrAccumError(pAccum, SQLITE_TOOBIG);
17929642252Sdrh     return 0;
18029642252Sdrh   }
18129642252Sdrh   z = sqlite3DbMallocRaw(pAccum->db, n);
18229642252Sdrh   if( z==0 ){
18329642252Sdrh     setStrAccumError(pAccum, SQLITE_NOMEM);
18429642252Sdrh   }
18529642252Sdrh   return z;
18629642252Sdrh }
187a5c1416dSdrh 
188a5c1416dSdrh /*
18979158e18Sdrh ** On machines with a small stack size, you can redefine the
190ed1fddf4Sdrh ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19179158e18Sdrh */
19279158e18Sdrh #ifndef SQLITE_PRINT_BUF_SIZE
19359eedf79Sdrh # define SQLITE_PRINT_BUF_SIZE 70
19450d654daSdrh #endif
19579158e18Sdrh #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
196a18c5681Sdrh 
197a18c5681Sdrh /*
198dd6c33d3Sdrh ** Hard limit on the precision of floating-point conversions.
199dd6c33d3Sdrh */
200dd6c33d3Sdrh #ifndef SQLITE_PRINTF_PRECISION_LIMIT
201dd6c33d3Sdrh # define SQLITE_FP_PRECISION_LIMIT 100000000
202dd6c33d3Sdrh #endif
203dd6c33d3Sdrh 
204dd6c33d3Sdrh /*
205ed1fddf4Sdrh ** Render a string given by "fmt" into the StrAccum object.
206a18c5681Sdrh */
2070cdbe1aeSdrh void sqlite3_str_vappendf(
2080cdbe1aeSdrh   sqlite3_str *pAccum,       /* Accumulate results here */
2095f968436Sdrh   const char *fmt,           /* Format string */
2105f968436Sdrh   va_list ap                 /* arguments */
211a18c5681Sdrh ){
212e84a306bSdrh   int c;                     /* Next character in the format string */
213e84a306bSdrh   char *bufpt;               /* Pointer to the conversion buffer */
214e84a306bSdrh   int precision;             /* Precision of the current field */
215e84a306bSdrh   int length;                /* Length of the field */
216e84a306bSdrh   int idx;                   /* A general purpose loop counter */
217a18c5681Sdrh   int width;                 /* Width of the current field */
218e84a306bSdrh   etByte flag_leftjustify;   /* True if "-" flag is present */
2192c338a9dSdrh   etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */
220e84a306bSdrh   etByte flag_alternateform; /* True if "#" flag is present */
221531fe878Sdrh   etByte flag_altform2;      /* True if "!" flag is present */
222e84a306bSdrh   etByte flag_zeropad;       /* True if field width constant starts with zero */
2232c338a9dSdrh   etByte flag_long;          /* 1 for the "l" flag, 2 for "ll", 0 by default */
2243e9aeec0Sdrh   etByte done;               /* Loop termination flag */
2252c338a9dSdrh   etByte cThousand;          /* Thousands separator for %d and %u */
226ad5a9d71Sdrh   etByte xtype = etINVALID;  /* Conversion paradigm */
227a5c1416dSdrh   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
228ed1fddf4Sdrh   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
22927436af7Sdrh   sqlite_uint64 longvalue;   /* Value for integer types */
230384eef32Sdrh   LONGDOUBLE_TYPE realvalue; /* Value for real types */
2315719628aSdrh   const et_info *infop;      /* Pointer to the appropriate info structure */
23259eedf79Sdrh   char *zOut;                /* Rendering buffer */
23359eedf79Sdrh   int nOut;                  /* Size of the rendering buffer */
234af8f513fSdrh   char *zExtra = 0;          /* Malloced memory used by some conversion */
235b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
236557cc60fSdrh   int  exp, e2;              /* exponent of real numbers */
237ed1fddf4Sdrh   int nsd;                   /* Number of significant digits returned */
238a18c5681Sdrh   double rounder;            /* Used for rounding floating point values */
239e84a306bSdrh   etByte flag_dp;            /* True if decimal point should be shown */
240e84a306bSdrh   etByte flag_rtz;           /* True if trailing zeros should be removed */
241a18c5681Sdrh #endif
242a5c1416dSdrh   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
243ed1fddf4Sdrh   char buf[etBUFSIZE];       /* Conversion buffer */
244a18c5681Sdrh 
245cc398969Sdrh   /* pAccum never starts out with an empty buffer that was obtained from
246cc398969Sdrh   ** malloc().  This precondition is required by the mprintf("%z...")
247cc398969Sdrh   ** optimization. */
248cc398969Sdrh   assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
249cc398969Sdrh 
250a18c5681Sdrh   bufpt = 0;
2518236f688Sdrh   if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
252a5c1416dSdrh     pArgList = va_arg(ap, PrintfArguments*);
2538236f688Sdrh     bArgList = 1;
254a5c1416dSdrh   }else{
2558236f688Sdrh     bArgList = 0;
256a5c1416dSdrh   }
257a18c5681Sdrh   for(; (c=(*fmt))!=0; ++fmt){
258a18c5681Sdrh     if( c!='%' ){
259a18c5681Sdrh       bufpt = (char *)fmt;
260760b1598Sdrh #if HAVE_STRCHRNUL
261760b1598Sdrh       fmt = strchrnul(fmt, '%');
262760b1598Sdrh #else
263760b1598Sdrh       do{ fmt++; }while( *fmt && *fmt != '%' );
264760b1598Sdrh #endif
2650cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
266760b1598Sdrh       if( *fmt==0 ) break;
267a18c5681Sdrh     }
268a18c5681Sdrh     if( (c=(*++fmt))==0 ){
2690cdbe1aeSdrh       sqlite3_str_append(pAccum, "%", 1);
270a18c5681Sdrh       break;
271a18c5681Sdrh     }
272a18c5681Sdrh     /* Find out what flags are present */
2732c338a9dSdrh     flag_leftjustify = flag_prefix = cThousand =
274557cc60fSdrh      flag_alternateform = flag_altform2 = flag_zeropad = 0;
2753e9aeec0Sdrh     done = 0;
2769a6d01bfSdrh     width = 0;
2779a6d01bfSdrh     flag_long = 0;
2789a6d01bfSdrh     precision = -1;
279a18c5681Sdrh     do{
280a18c5681Sdrh       switch( c ){
2813e9aeec0Sdrh         case '-':   flag_leftjustify = 1;     break;
2822c338a9dSdrh         case '+':   flag_prefix = '+';        break;
2832c338a9dSdrh         case ' ':   flag_prefix = ' ';        break;
2843e9aeec0Sdrh         case '#':   flag_alternateform = 1;   break;
2853e9aeec0Sdrh         case '!':   flag_altform2 = 1;        break;
2863e9aeec0Sdrh         case '0':   flag_zeropad = 1;         break;
2872c338a9dSdrh         case ',':   cThousand = ',';          break;
2883e9aeec0Sdrh         default:    done = 1;                 break;
2899a6d01bfSdrh         case 'l': {
2909a6d01bfSdrh           flag_long = 1;
2919a6d01bfSdrh           c = *++fmt;
2929a6d01bfSdrh           if( c=='l' ){
2939a6d01bfSdrh             c = *++fmt;
2949a6d01bfSdrh             flag_long = 2;
295a18c5681Sdrh           }
2969a6d01bfSdrh           done = 1;
2979a6d01bfSdrh           break;
2989a6d01bfSdrh         }
2999a6d01bfSdrh         case '1': case '2': case '3': case '4': case '5':
3009a6d01bfSdrh         case '6': case '7': case '8': case '9': {
3019a6d01bfSdrh           unsigned wx = c - '0';
3029a6d01bfSdrh           while( (c = *++fmt)>='0' && c<='9' ){
3039a6d01bfSdrh             wx = wx*10 + c - '0';
3049a6d01bfSdrh           }
3059a6d01bfSdrh           testcase( wx>0x7fffffff );
3069a6d01bfSdrh           width = wx & 0x7fffffff;
3079a6d01bfSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
3089a6d01bfSdrh           if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
3099a6d01bfSdrh             width = SQLITE_PRINTF_PRECISION_LIMIT;
3109a6d01bfSdrh           }
3119a6d01bfSdrh #endif
3129a6d01bfSdrh           if( c!='.' && c!='l' ){
3139a6d01bfSdrh             done = 1;
3149a6d01bfSdrh           }else{
3159a6d01bfSdrh             fmt--;
3169a6d01bfSdrh           }
3179a6d01bfSdrh           break;
3189a6d01bfSdrh         }
3199a6d01bfSdrh         case '*': {
320a5c1416dSdrh           if( bArgList ){
321a5c1416dSdrh             width = (int)getIntArg(pArgList);
322a5c1416dSdrh           }else{
323a18c5681Sdrh             width = va_arg(ap,int);
324a5c1416dSdrh           }
325a18c5681Sdrh           if( width<0 ){
326a18c5681Sdrh             flag_leftjustify = 1;
327b6f47debSdrh             width = width >= -2147483647 ? -width : 0;
328a18c5681Sdrh           }
329c386ef4fSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
330c386ef4fSdrh           if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
331c386ef4fSdrh             width = SQLITE_PRINTF_PRECISION_LIMIT;
332c386ef4fSdrh           }
333c386ef4fSdrh #endif
3349a6d01bfSdrh           if( (c = fmt[1])!='.' && c!='l' ){
3359a6d01bfSdrh             c = *++fmt;
3369a6d01bfSdrh             done = 1;
3379a6d01bfSdrh           }
3389a6d01bfSdrh           break;
3399a6d01bfSdrh         }
3409a6d01bfSdrh         case '.': {
341a18c5681Sdrh           c = *++fmt;
342a18c5681Sdrh           if( c=='*' ){
343a5c1416dSdrh             if( bArgList ){
344a5c1416dSdrh               precision = (int)getIntArg(pArgList);
345a5c1416dSdrh             }else{
346a18c5681Sdrh               precision = va_arg(ap,int);
347a5c1416dSdrh             }
348b6f47debSdrh             if( precision<0 ){
349b6f47debSdrh               precision = precision >= -2147483647 ? -precision : -1;
350b6f47debSdrh             }
3519a6d01bfSdrh             c = *++fmt;
352a18c5681Sdrh           }else{
353b6f47debSdrh             unsigned px = 0;
35417a68934Sdrh             while( c>='0' && c<='9' ){
355b6f47debSdrh               px = px*10 + c - '0';
356a18c5681Sdrh               c = *++fmt;
357a18c5681Sdrh             }
358b6f47debSdrh             testcase( px>0x7fffffff );
359b6f47debSdrh             precision = px & 0x7fffffff;
360a18c5681Sdrh           }
361c386ef4fSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
362c386ef4fSdrh           if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
363c386ef4fSdrh             precision = SQLITE_PRINTF_PRECISION_LIMIT;
364c386ef4fSdrh           }
365c386ef4fSdrh #endif
366a18c5681Sdrh           if( c=='l' ){
3679a6d01bfSdrh             --fmt;
368a34b6764Sdrh           }else{
3699a6d01bfSdrh             done = 1;
370a18c5681Sdrh           }
3719a6d01bfSdrh           break;
3729a6d01bfSdrh         }
3739a6d01bfSdrh       }
3749a6d01bfSdrh     }while( !done && (c=(*++fmt))!=0 );
3759a6d01bfSdrh 
376a18c5681Sdrh     /* Fetch the info entry for the field */
377874ba04cSdrh     infop = &fmtinfo[0];
378874ba04cSdrh     xtype = etINVALID;
37900e13613Sdanielk1977     for(idx=0; idx<ArraySize(fmtinfo); idx++){
380a18c5681Sdrh       if( c==fmtinfo[idx].fmttype ){
381a18c5681Sdrh         infop = &fmtinfo[idx];
382e84a306bSdrh         xtype = infop->type;
383a18c5681Sdrh         break;
384a18c5681Sdrh       }
385a18c5681Sdrh     }
38643617e9aSdrh 
387a18c5681Sdrh     /*
388a18c5681Sdrh     ** At this point, variables are initialized as follows:
389a18c5681Sdrh     **
390a18c5681Sdrh     **   flag_alternateform          TRUE if a '#' is present.
3913e9aeec0Sdrh     **   flag_altform2               TRUE if a '!' is present.
3922c338a9dSdrh     **   flag_prefix                 '+' or ' ' or zero
393a18c5681Sdrh     **   flag_leftjustify            TRUE if a '-' is present or if the
394a18c5681Sdrh     **                               field width was negative.
395a18c5681Sdrh     **   flag_zeropad                TRUE if the width began with 0.
3962c338a9dSdrh     **   flag_long                   1 for "l", 2 for "ll"
397a18c5681Sdrh     **   width                       The specified field width.  This is
398a18c5681Sdrh     **                               always non-negative.  Zero is the default.
399a18c5681Sdrh     **   precision                   The specified precision.  The default
400a18c5681Sdrh     **                               is -1.
401a18c5681Sdrh     **   xtype                       The class of the conversion.
402a18c5681Sdrh     **   infop                       Pointer to the appropriate info struct.
403a18c5681Sdrh     */
404*b6907e29Sdrh     assert( width>=0 );
405*b6907e29Sdrh     assert( precision>=(-1) );
406a18c5681Sdrh     switch( xtype ){
407fe63d1c9Sdrh       case etPOINTER:
4082c338a9dSdrh         flag_long = sizeof(char*)==sizeof(i64) ? 2 :
4092c338a9dSdrh                      sizeof(char*)==sizeof(long int) ? 1 : 0;
410fe63d1c9Sdrh         /* Fall through into the next case */
4119a99334dSdrh       case etORDINAL:
412a18c5681Sdrh       case etRADIX:
4132c338a9dSdrh         cThousand = 0;
4142c338a9dSdrh         /* Fall through into the next case */
4152c338a9dSdrh       case etDECIMAL:
416e84a306bSdrh         if( infop->flags & FLAG_SIGNED ){
417e9707671Sdrh           i64 v;
418a5c1416dSdrh           if( bArgList ){
419a5c1416dSdrh             v = getIntArg(pArgList);
420eeb23a4cSdrh           }else if( flag_long ){
4212c338a9dSdrh             if( flag_long==2 ){
4222c338a9dSdrh               v = va_arg(ap,i64) ;
4232c338a9dSdrh             }else{
424eeb23a4cSdrh               v = va_arg(ap,long int);
4252c338a9dSdrh             }
426eeb23a4cSdrh           }else{
427eeb23a4cSdrh             v = va_arg(ap,int);
428eeb23a4cSdrh           }
429e9707671Sdrh           if( v<0 ){
430158b9cb9Sdrh             if( v==SMALLEST_INT64 ){
431158b9cb9Sdrh               longvalue = ((u64)1)<<63;
432158b9cb9Sdrh             }else{
433158b9cb9Sdrh               longvalue = -v;
434158b9cb9Sdrh             }
435cfcdaefeSdanielk1977             prefix = '-';
436cfcdaefeSdanielk1977           }else{
437e9707671Sdrh             longvalue = v;
4382c338a9dSdrh             prefix = flag_prefix;
439cfcdaefeSdanielk1977           }
440e9707671Sdrh         }else{
441a5c1416dSdrh           if( bArgList ){
442a5c1416dSdrh             longvalue = (u64)getIntArg(pArgList);
443eeb23a4cSdrh           }else if( flag_long ){
4442c338a9dSdrh             if( flag_long==2 ){
4452c338a9dSdrh               longvalue = va_arg(ap,u64);
4462c338a9dSdrh             }else{
447eeb23a4cSdrh               longvalue = va_arg(ap,unsigned long int);
4482c338a9dSdrh             }
449eeb23a4cSdrh           }else{
450eeb23a4cSdrh             longvalue = va_arg(ap,unsigned int);
451eeb23a4cSdrh           }
452e9707671Sdrh           prefix = 0;
453e9707671Sdrh         }
454e9707671Sdrh         if( longvalue==0 ) flag_alternateform = 0;
455a18c5681Sdrh         if( flag_zeropad && precision<width-(prefix!=0) ){
456a18c5681Sdrh           precision = width-(prefix!=0);
457a18c5681Sdrh         }
4582c338a9dSdrh         if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
45959eedf79Sdrh           nOut = etBUFSIZE;
46059eedf79Sdrh           zOut = buf;
46159eedf79Sdrh         }else{
4627ba03ea1Sdrh           u64 n;
4637ba03ea1Sdrh           n = (u64)precision + 10;
4647ba03ea1Sdrh           if( cThousand ) n += precision/3;
46529642252Sdrh           zOut = zExtra = printfTempBuf(pAccum, n);
46629642252Sdrh           if( zOut==0 ) return;
4675f42995aSdrh           nOut = (int)n;
46859eedf79Sdrh         }
46959eedf79Sdrh         bufpt = &zOut[nOut-1];
4709a99334dSdrh         if( xtype==etORDINAL ){
47143f6e064Sdrh           static const char zOrd[] = "thstndrd";
472ea678832Sdrh           int x = (int)(longvalue % 10);
47343f6e064Sdrh           if( x>=4 || (longvalue/10)%10==1 ){
47443f6e064Sdrh             x = 0;
47543f6e064Sdrh           }
47659eedf79Sdrh           *(--bufpt) = zOrd[x*2+1];
47759eedf79Sdrh           *(--bufpt) = zOrd[x*2];
4789a99334dSdrh         }
479a18c5681Sdrh         {
4800e682099Sdrh           const char *cset = &aDigits[infop->charset];
4810e682099Sdrh           u8 base = infop->base;
482a18c5681Sdrh           do{                                           /* Convert to ascii */
483a18c5681Sdrh             *(--bufpt) = cset[longvalue%base];
484a18c5681Sdrh             longvalue = longvalue/base;
485a18c5681Sdrh           }while( longvalue>0 );
486a18c5681Sdrh         }
48759eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
4882c338a9dSdrh         while( precision>length ){
489a18c5681Sdrh           *(--bufpt) = '0';                             /* Zero pad */
4902c338a9dSdrh           length++;
4912c338a9dSdrh         }
4922c338a9dSdrh         if( cThousand ){
4932c338a9dSdrh           int nn = (length - 1)/3;  /* Number of "," to insert */
4942c338a9dSdrh           int ix = (length - 1)%3 + 1;
4952c338a9dSdrh           bufpt -= nn;
4962c338a9dSdrh           for(idx=0; nn>0; idx++){
4972c338a9dSdrh             bufpt[idx] = bufpt[idx+nn];
4982c338a9dSdrh             ix--;
4992c338a9dSdrh             if( ix==0 ){
5002c338a9dSdrh               bufpt[++idx] = cThousand;
5012c338a9dSdrh               nn--;
5022c338a9dSdrh               ix = 3;
5032c338a9dSdrh             }
5042c338a9dSdrh           }
505a18c5681Sdrh         }
506a18c5681Sdrh         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
507a18c5681Sdrh         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
50876ff3a0eSdrh           const char *pre;
50976ff3a0eSdrh           char x;
51076ff3a0eSdrh           pre = &aPrefix[infop->prefix];
51176ff3a0eSdrh           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
512a18c5681Sdrh         }
51359eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
514a18c5681Sdrh         break;
515a18c5681Sdrh       case etFLOAT:
516a18c5681Sdrh       case etEXP:
517a18c5681Sdrh       case etGENERIC:
518a5c1416dSdrh         if( bArgList ){
519a5c1416dSdrh           realvalue = getDoubleArg(pArgList);
520a5c1416dSdrh         }else{
521a18c5681Sdrh           realvalue = va_arg(ap,double);
522a5c1416dSdrh         }
52369ef7036Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
52469ef7036Sdrh         length = 0;
52569ef7036Sdrh #else
526a18c5681Sdrh         if( precision<0 ) precision = 6;         /* Set default precision */
527dd6c33d3Sdrh #ifdef SQLITE_FP_PRECISION_LIMIT
528dd6c33d3Sdrh         if( precision>SQLITE_FP_PRECISION_LIMIT ){
529dd6c33d3Sdrh           precision = SQLITE_FP_PRECISION_LIMIT;
530dd6c33d3Sdrh         }
531dd6c33d3Sdrh #endif
532a18c5681Sdrh         if( realvalue<0.0 ){
533a18c5681Sdrh           realvalue = -realvalue;
534a18c5681Sdrh           prefix = '-';
535a18c5681Sdrh         }else{
5362c338a9dSdrh           prefix = flag_prefix;
537a18c5681Sdrh         }
5383e9aeec0Sdrh         if( xtype==etGENERIC && precision>0 ) precision--;
539a30d22a7Sdrh         testcase( precision>0xfff );
540a0ed86bcSdrh         idx = precision & 0xfff;
541a0ed86bcSdrh         rounder = arRound[idx%10];
542a0ed86bcSdrh         while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
543a0ed86bcSdrh         if( xtype==etFLOAT ){
544ef7d5187Sdrh           double rx = (double)realvalue;
545ef7d5187Sdrh           sqlite3_uint64 u;
546ef7d5187Sdrh           int ex;
547ef7d5187Sdrh           memcpy(&u, &rx, sizeof(u));
548ef7d5187Sdrh           ex = -1023 + (int)((u>>52)&0x7ff);
549ef7d5187Sdrh           if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
550a0ed86bcSdrh           realvalue += rounder;
551a0ed86bcSdrh         }
552a18c5681Sdrh         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
553a18c5681Sdrh         exp = 0;
554ea678832Sdrh         if( sqlite3IsNaN((double)realvalue) ){
55553c14021Sdrh           bufpt = "NaN";
55653c14021Sdrh           length = 3;
55753c14021Sdrh           break;
55853c14021Sdrh         }
559a18c5681Sdrh         if( realvalue>0.0 ){
56072b3fbc7Sdrh           LONGDOUBLE_TYPE scale = 1.0;
5614ef94130Sdrh           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
5622a8f6712Sdrh           while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
56372b3fbc7Sdrh           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
56472b3fbc7Sdrh           realvalue /= scale;
565af005fbcSdrh           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
566af005fbcSdrh           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
567af005fbcSdrh           if( exp>350 ){
5682a8f6712Sdrh             bufpt = buf;
5692a8f6712Sdrh             buf[0] = prefix;
5702a8f6712Sdrh             memcpy(buf+(prefix!=0),"Inf",4);
5712a8f6712Sdrh             length = 3+(prefix!=0);
572a18c5681Sdrh             break;
573a18c5681Sdrh           }
574a18c5681Sdrh         }
575a18c5681Sdrh         bufpt = buf;
576a18c5681Sdrh         /*
577a18c5681Sdrh         ** If the field type is etGENERIC, then convert to either etEXP
578a18c5681Sdrh         ** or etFLOAT, as appropriate.
579a18c5681Sdrh         */
580a18c5681Sdrh         if( xtype!=etFLOAT ){
581a18c5681Sdrh           realvalue += rounder;
582a18c5681Sdrh           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
583a18c5681Sdrh         }
584a18c5681Sdrh         if( xtype==etGENERIC ){
585a18c5681Sdrh           flag_rtz = !flag_alternateform;
586a18c5681Sdrh           if( exp<-4 || exp>precision ){
587a18c5681Sdrh             xtype = etEXP;
588a18c5681Sdrh           }else{
589a18c5681Sdrh             precision = precision - exp;
590a18c5681Sdrh             xtype = etFLOAT;
591a18c5681Sdrh           }
592a18c5681Sdrh         }else{
59372b3fbc7Sdrh           flag_rtz = flag_altform2;
594a18c5681Sdrh         }
595557cc60fSdrh         if( xtype==etEXP ){
596557cc60fSdrh           e2 = 0;
597557cc60fSdrh         }else{
598557cc60fSdrh           e2 = exp;
599557cc60fSdrh         }
60029642252Sdrh         {
60129642252Sdrh           i64 szBufNeeded;           /* Size of a temporary buffer needed */
60229642252Sdrh           szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
60329642252Sdrh           if( szBufNeeded > etBUFSIZE ){
60429642252Sdrh             bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
60529642252Sdrh             if( bufpt==0 ) return;
60659eedf79Sdrh           }
60759eedf79Sdrh         }
60859eedf79Sdrh         zOut = bufpt;
60972b3fbc7Sdrh         nsd = 16 + flag_altform2*10;
610ea678832Sdrh         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
611557cc60fSdrh         /* The sign in front of the number */
612557cc60fSdrh         if( prefix ){
613557cc60fSdrh           *(bufpt++) = prefix;
614557cc60fSdrh         }
615557cc60fSdrh         /* Digits prior to the decimal point */
616557cc60fSdrh         if( e2<0 ){
617557cc60fSdrh           *(bufpt++) = '0';
618557cc60fSdrh         }else{
619557cc60fSdrh           for(; e2>=0; e2--){
620557cc60fSdrh             *(bufpt++) = et_getdigit(&realvalue,&nsd);
621557cc60fSdrh           }
622557cc60fSdrh         }
623557cc60fSdrh         /* The decimal point */
624557cc60fSdrh         if( flag_dp ){
625557cc60fSdrh           *(bufpt++) = '.';
626557cc60fSdrh         }
627557cc60fSdrh         /* "0" digits after the decimal point but before the first
628557cc60fSdrh         ** significant digit of the number */
629af005fbcSdrh         for(e2++; e2<0; precision--, e2++){
630af005fbcSdrh           assert( precision>0 );
631a18c5681Sdrh           *(bufpt++) = '0';
632a18c5681Sdrh         }
633557cc60fSdrh         /* Significant digits after the decimal point */
634557cc60fSdrh         while( (precision--)>0 ){
635557cc60fSdrh           *(bufpt++) = et_getdigit(&realvalue,&nsd);
636a18c5681Sdrh         }
637557cc60fSdrh         /* Remove trailing zeros and the "." if no digits follow the "." */
638557cc60fSdrh         if( flag_rtz && flag_dp ){
6393e9aeec0Sdrh           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
64059eedf79Sdrh           assert( bufpt>zOut );
6413e9aeec0Sdrh           if( bufpt[-1]=='.' ){
642557cc60fSdrh             if( flag_altform2 ){
643557cc60fSdrh               *(bufpt++) = '0';
644557cc60fSdrh             }else{
645557cc60fSdrh               *(--bufpt) = 0;
646a18c5681Sdrh             }
647557cc60fSdrh           }
648557cc60fSdrh         }
649557cc60fSdrh         /* Add the "eNNN" suffix */
65059eedf79Sdrh         if( xtype==etEXP ){
65176ff3a0eSdrh           *(bufpt++) = aDigits[infop->charset];
652557cc60fSdrh           if( exp<0 ){
653557cc60fSdrh             *(bufpt++) = '-'; exp = -exp;
654557cc60fSdrh           }else{
655557cc60fSdrh             *(bufpt++) = '+';
656557cc60fSdrh           }
657a18c5681Sdrh           if( exp>=100 ){
658ea678832Sdrh             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
659a18c5681Sdrh             exp %= 100;
660a18c5681Sdrh           }
661ea678832Sdrh           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
662ea678832Sdrh           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
663a18c5681Sdrh         }
664557cc60fSdrh         *bufpt = 0;
665557cc60fSdrh 
666a18c5681Sdrh         /* The converted number is in buf[] and zero terminated. Output it.
667a18c5681Sdrh         ** Note that the number is in the usual order, not reversed as with
668a18c5681Sdrh         ** integer conversions. */
66959eedf79Sdrh         length = (int)(bufpt-zOut);
67059eedf79Sdrh         bufpt = zOut;
671a18c5681Sdrh 
672a18c5681Sdrh         /* Special case:  Add leading zeros if the flag_zeropad flag is
673a18c5681Sdrh         ** set and we are not left justified */
674a18c5681Sdrh         if( flag_zeropad && !flag_leftjustify && length < width){
675a18c5681Sdrh           int i;
676a18c5681Sdrh           int nPad = width - length;
677a18c5681Sdrh           for(i=width; i>=nPad; i--){
678a18c5681Sdrh             bufpt[i] = bufpt[i-nPad];
679a18c5681Sdrh           }
680a18c5681Sdrh           i = prefix!=0;
681a18c5681Sdrh           while( nPad-- ) bufpt[i++] = '0';
682a18c5681Sdrh           length = width;
683a18c5681Sdrh         }
68469ef7036Sdrh #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
685a18c5681Sdrh         break;
686a18c5681Sdrh       case etSIZE:
687fc6ee9dfSdrh         if( !bArgList ){
688fc6ee9dfSdrh           *(va_arg(ap,int*)) = pAccum->nChar;
689fc6ee9dfSdrh         }
690a18c5681Sdrh         length = width = 0;
691a18c5681Sdrh         break;
692a18c5681Sdrh       case etPERCENT:
693a18c5681Sdrh         buf[0] = '%';
694a18c5681Sdrh         bufpt = buf;
695a18c5681Sdrh         length = 1;
696a18c5681Sdrh         break;
697a18c5681Sdrh       case etCHARX:
698a5c1416dSdrh         if( bArgList ){
699fc6ee9dfSdrh           bufpt = getTextArg(pArgList);
700a15a7c35Sdrh           length = 1;
701136102beSdrh           if( bufpt ){
702136102beSdrh             buf[0] = c = *(bufpt++);
703136102beSdrh             if( (c&0xc0)==0xc0 ){
704136102beSdrh               while( length<4 && (bufpt[0]&0xc0)==0x80 ){
705136102beSdrh                 buf[length++] = *(bufpt++);
706136102beSdrh               }
707136102beSdrh             }
708a15a7c35Sdrh           }else{
709a15a7c35Sdrh             buf[0] = 0;
710136102beSdrh           }
711a5c1416dSdrh         }else{
712136102beSdrh           unsigned int ch = va_arg(ap,unsigned int);
713136102beSdrh           if( ch<0x00080 ){
714136102beSdrh             buf[0] = ch & 0xff;
715136102beSdrh             length = 1;
716136102beSdrh           }else if( ch<0x00800 ){
717136102beSdrh             buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
718136102beSdrh             buf[1] = 0x80 + (u8)(ch & 0x3f);
719136102beSdrh             length = 2;
720136102beSdrh           }else if( ch<0x10000 ){
721136102beSdrh             buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
722136102beSdrh             buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
723136102beSdrh             buf[2] = 0x80 + (u8)(ch & 0x3f);
724136102beSdrh             length = 3;
725136102beSdrh           }else{
726136102beSdrh             buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
727136102beSdrh             buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
728136102beSdrh             buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
729136102beSdrh             buf[3] = 0x80 + (u8)(ch & 0x3f);
730136102beSdrh             length = 4;
731136102beSdrh           }
732a5c1416dSdrh         }
733af8f513fSdrh         if( precision>1 ){
734af8f513fSdrh           width -= precision-1;
735af8f513fSdrh           if( width>1 && !flag_leftjustify ){
7360cdbe1aeSdrh             sqlite3_str_appendchar(pAccum, width-1, ' ');
737af8f513fSdrh             width = 0;
738a18c5681Sdrh           }
739136102beSdrh           while( precision-- > 1 ){
7400cdbe1aeSdrh             sqlite3_str_append(pAccum, buf, length);
741af8f513fSdrh           }
742136102beSdrh         }
743a18c5681Sdrh         bufpt = buf;
744cf7c8370Sdrh         flag_altform2 = 1;
745cf7c8370Sdrh         goto adjust_width_for_utf8;
746a18c5681Sdrh       case etSTRING:
747d93d8a81Sdrh       case etDYNSTRING:
748a5c1416dSdrh         if( bArgList ){
749a5c1416dSdrh           bufpt = getTextArg(pArgList);
7502a8f6712Sdrh           xtype = etSTRING;
751a5c1416dSdrh         }else{
752cb485882Sdrh           bufpt = va_arg(ap,char*);
753a5c1416dSdrh         }
754d93d8a81Sdrh         if( bufpt==0 ){
755d93d8a81Sdrh           bufpt = "";
7562a8f6712Sdrh         }else if( xtype==etDYNSTRING ){
757af524a63Sdrh           if( pAccum->nChar==0
758af524a63Sdrh            && pAccum->mxAlloc
759af524a63Sdrh            && width==0
760af524a63Sdrh            && precision<0
761af524a63Sdrh            && pAccum->accError==0
762af524a63Sdrh           ){
763cc398969Sdrh             /* Special optimization for sqlite3_mprintf("%z..."):
764cc398969Sdrh             ** Extend an existing memory allocation rather than creating
765cc398969Sdrh             ** a new one. */
766cc398969Sdrh             assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
767cc398969Sdrh             pAccum->zText = bufpt;
768cc398969Sdrh             pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
769cc398969Sdrh             pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
770cc398969Sdrh             pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
771cc398969Sdrh             length = 0;
772cc398969Sdrh             break;
773cc398969Sdrh           }
774d93d8a81Sdrh           zExtra = bufpt;
775d93d8a81Sdrh         }
776e509094bSdrh         if( precision>=0 ){
77762856465Sdrh           if( flag_altform2 ){
77862856465Sdrh             /* Set length to the number of bytes needed in order to display
77962856465Sdrh             ** precision characters */
78062856465Sdrh             unsigned char *z = (unsigned char*)bufpt;
78162856465Sdrh             while( precision-- > 0 && z[0] ){
78262856465Sdrh               SQLITE_SKIP_UTF8(z);
78362856465Sdrh             }
78462856465Sdrh             length = (int)(z - (unsigned char*)bufpt);
78562856465Sdrh           }else{
786e509094bSdrh             for(length=0; length<precision && bufpt[length]; length++){}
78762856465Sdrh           }
788e509094bSdrh         }else{
789c84ddf14Sdrh           length = 0x7fffffff & (int)strlen(bufpt);
790e509094bSdrh         }
79157e3ba76Sdrh       adjust_width_for_utf8:
79262856465Sdrh         if( flag_altform2 && width>0 ){
79362856465Sdrh           /* Adjust width to account for extra bytes in UTF-8 characters */
79462856465Sdrh           int ii = length - 1;
79562856465Sdrh           while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
79662856465Sdrh         }
797a18c5681Sdrh         break;
79857e3ba76Sdrh       case etSQLESCAPE:           /* %q: Escape ' characters */
79957e3ba76Sdrh       case etSQLESCAPE2:          /* %Q: Escape ' and enclose in '...' */
80057e3ba76Sdrh       case etSQLESCAPE3: {        /* %w: Escape " characters */
8018965b50eSdrh         int i, j, k, n, isnull;
8024794f735Sdrh         int needQuote;
803ea678832Sdrh         char ch;
804f3b863edSdanielk1977         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
805a5c1416dSdrh         char *escarg;
806a5c1416dSdrh 
807a5c1416dSdrh         if( bArgList ){
808a5c1416dSdrh           escarg = getTextArg(pArgList);
809a5c1416dSdrh         }else{
810a5c1416dSdrh           escarg = va_arg(ap,char*);
811a5c1416dSdrh         }
812f0113000Sdanielk1977         isnull = escarg==0;
813f0113000Sdanielk1977         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
814*b6907e29Sdrh         /* For %q, %Q, and %w, the precision is the number of bytes (or
81557e3ba76Sdrh         ** characters if the ! flags is present) to use from the input.
81657e3ba76Sdrh         ** Because of the extra quoting characters inserted, the number
81757e3ba76Sdrh         ** of output characters may be larger than the precision.
81857e3ba76Sdrh         */
8198965b50eSdrh         k = precision;
82060d4a304Sdan         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
821f3b863edSdanielk1977           if( ch==q )  n++;
82257e3ba76Sdrh           if( flag_altform2 && (ch&0xc0)==0xc0 ){
82357e3ba76Sdrh             while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
82457e3ba76Sdrh           }
825a18c5681Sdrh         }
8264794f735Sdrh         needQuote = !isnull && xtype==etSQLESCAPE2;
8272a8f6712Sdrh         n += i + 3;
828a18c5681Sdrh         if( n>etBUFSIZE ){
82929642252Sdrh           bufpt = zExtra = printfTempBuf(pAccum, n);
83029642252Sdrh           if( bufpt==0 ) return;
831a18c5681Sdrh         }else{
832a18c5681Sdrh           bufpt = buf;
833a18c5681Sdrh         }
8340cfcf3fbSchw         j = 0;
835f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
8368965b50eSdrh         k = i;
8378965b50eSdrh         for(i=0; i<k; i++){
8388965b50eSdrh           bufpt[j++] = ch = escarg[i];
839f3b863edSdanielk1977           if( ch==q ) bufpt[j++] = ch;
840a18c5681Sdrh         }
841f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
842a18c5681Sdrh         bufpt[j] = 0;
843a18c5681Sdrh         length = j;
84457e3ba76Sdrh         goto adjust_width_for_utf8;
8455eba8c09Sdrh       }
8465f968436Sdrh       case etTOKEN: {
8478236f688Sdrh         Token *pToken;
8488236f688Sdrh         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
8498236f688Sdrh         pToken = va_arg(ap, Token*);
850a5c1416dSdrh         assert( bArgList==0 );
851a9ab481fSdrh         if( pToken && pToken->n ){
8520cdbe1aeSdrh           sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
853ad6d9460Sdrh         }
8545f968436Sdrh         length = width = 0;
8555f968436Sdrh         break;
8565f968436Sdrh       }
8575f968436Sdrh       case etSRCLIST: {
8588236f688Sdrh         SrcList *pSrc;
8598236f688Sdrh         int k;
8608236f688Sdrh         struct SrcList_item *pItem;
8618236f688Sdrh         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
8628236f688Sdrh         pSrc = va_arg(ap, SrcList*);
8638236f688Sdrh         k = va_arg(ap, int);
8648236f688Sdrh         pItem = &pSrc->a[k];
865a5c1416dSdrh         assert( bArgList==0 );
8665f968436Sdrh         assert( k>=0 && k<pSrc->nSrc );
86793a960a0Sdrh         if( pItem->zDatabase ){
8680cdbe1aeSdrh           sqlite3_str_appendall(pAccum, pItem->zDatabase);
8690cdbe1aeSdrh           sqlite3_str_append(pAccum, ".", 1);
8705f968436Sdrh         }
8710cdbe1aeSdrh         sqlite3_str_appendall(pAccum, pItem->zName);
8725f968436Sdrh         length = width = 0;
8735f968436Sdrh         break;
8745f968436Sdrh       }
875874ba04cSdrh       default: {
876874ba04cSdrh         assert( xtype==etINVALID );
877874ba04cSdrh         return;
878874ba04cSdrh       }
879a18c5681Sdrh     }/* End switch over the format type */
880a18c5681Sdrh     /*
881a18c5681Sdrh     ** The text of the conversion is pointed to by "bufpt" and is
882a18c5681Sdrh     ** "length" characters long.  The field width is "width".  Do
88362856465Sdrh     ** the output.  Both length and width are in bytes, not characters,
88462856465Sdrh     ** at this point.  If the "!" flag was present on string conversions
88562856465Sdrh     ** indicating that width and precision should be expressed in characters,
88662856465Sdrh     ** then the values have been translated prior to reaching this point.
887a18c5681Sdrh     */
888a70a073bSdrh     width -= length;
8898236f688Sdrh     if( width>0 ){
8900cdbe1aeSdrh       if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
8910cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, length);
8920cdbe1aeSdrh       if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
8938236f688Sdrh     }else{
8940cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, length);
8958236f688Sdrh     }
896a70a073bSdrh 
897af8f513fSdrh     if( zExtra ){
89896ceaf86Sdrh       sqlite3DbFree(pAccum->db, zExtra);
899af8f513fSdrh       zExtra = 0;
900af8f513fSdrh     }
901a18c5681Sdrh   }/* End for loop over the format string */
902a18c5681Sdrh } /* End of function */
903a18c5681Sdrh 
904a18c5681Sdrh /*
905a70a073bSdrh ** Enlarge the memory allocation on a StrAccum object so that it is
906a70a073bSdrh ** able to accept at least N more bytes of text.
907a70a073bSdrh **
908a70a073bSdrh ** Return the number of bytes of text that StrAccum is able to accept
909a70a073bSdrh ** after the attempted enlargement.  The value returned might be zero.
910a18c5681Sdrh */
911a70a073bSdrh static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
912a6353a3fSdrh   char *zNew;
913a30d22a7Sdrh   assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
914b49bc86aSdrh   if( p->accError ){
9150cdbe1aeSdrh     testcase(p->accError==SQLITE_TOOBIG);
9160cdbe1aeSdrh     testcase(p->accError==SQLITE_NOMEM);
917a70a073bSdrh     return 0;
918ade86483Sdrh   }
919c0490572Sdrh   if( p->mxAlloc==0 ){
9200cdbe1aeSdrh     setStrAccumError(p, SQLITE_TOOBIG);
921255a81f1Sdrh     return p->nAlloc - p->nChar - 1;
922a18c5681Sdrh   }else{
9235f4a686fSdrh     char *zOld = isMalloced(p) ? p->zText : 0;
92493a960a0Sdrh     i64 szNew = p->nChar;
925b1a6c3c1Sdrh     szNew += N + 1;
9267b4d780bSdrh     if( szNew+p->nChar<=p->mxAlloc ){
9277b4d780bSdrh       /* Force exponential buffer size growth as long as it does not overflow,
9287b4d780bSdrh       ** to avoid having to call this routine too often */
9297b4d780bSdrh       szNew += p->nChar;
9307b4d780bSdrh     }
931b1a6c3c1Sdrh     if( szNew > p->mxAlloc ){
9320cdbe1aeSdrh       sqlite3_str_reset(p);
9330cdbe1aeSdrh       setStrAccumError(p, SQLITE_TOOBIG);
934a70a073bSdrh       return 0;
935b1a6c3c1Sdrh     }else{
936ea678832Sdrh       p->nAlloc = (int)szNew;
937a18c5681Sdrh     }
938c0490572Sdrh     if( p->db ){
939a9ef7097Sdan       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
940b975598eSdrh     }else{
941d924e7bcSdrh       zNew = sqlite3Realloc(zOld, p->nAlloc);
942b975598eSdrh     }
94353f733c7Sdrh     if( zNew ){
9447ef4d1c4Sdrh       assert( p->zText!=0 || p->nChar==0 );
9455f4a686fSdrh       if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
946ade86483Sdrh       p->zText = zNew;
9477f5a7ecdSdrh       p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
9485f4a686fSdrh       p->printfFlags |= SQLITE_PRINTF_MALLOCED;
949ade86483Sdrh     }else{
9500cdbe1aeSdrh       sqlite3_str_reset(p);
9510cdbe1aeSdrh       setStrAccumError(p, SQLITE_NOMEM);
952a70a073bSdrh       return 0;
953a70a073bSdrh     }
954a70a073bSdrh   }
955a70a073bSdrh   return N;
956a70a073bSdrh }
957a70a073bSdrh 
958a70a073bSdrh /*
959af8f513fSdrh ** Append N copies of character c to the given string buffer.
960a70a073bSdrh */
9610cdbe1aeSdrh void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
962a30d22a7Sdrh   testcase( p->nChar + (i64)N > 0x7fffffff );
963a30d22a7Sdrh   if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
964a30d22a7Sdrh     return;
965a30d22a7Sdrh   }
966af8f513fSdrh   while( (N--)>0 ) p->zText[p->nChar++] = c;
967a70a073bSdrh }
968a70a073bSdrh 
969a70a073bSdrh /*
970a70a073bSdrh ** The StrAccum "p" is not large enough to accept N new bytes of z[].
971a70a073bSdrh ** So enlarge if first, then do the append.
972a70a073bSdrh **
9730cdbe1aeSdrh ** This is a helper routine to sqlite3_str_append() that does special-case
974a70a073bSdrh ** work (enlarging the buffer) using tail recursion, so that the
9750cdbe1aeSdrh ** sqlite3_str_append() routine can use fast calling semantics.
976a70a073bSdrh */
977172087fbSdrh static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
978a70a073bSdrh   N = sqlite3StrAccumEnlarge(p, N);
979a70a073bSdrh   if( N>0 ){
980a70a073bSdrh     memcpy(&p->zText[p->nChar], z, N);
981a70a073bSdrh     p->nChar += N;
982a70a073bSdrh   }
983a70a073bSdrh }
984a70a073bSdrh 
985a70a073bSdrh /*
986a70a073bSdrh ** Append N bytes of text from z to the StrAccum object.  Increase the
987a70a073bSdrh ** size of the memory allocation for StrAccum if necessary.
988a70a073bSdrh */
9890cdbe1aeSdrh void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
9903457338cSdrh   assert( z!=0 || N==0 );
991a70a073bSdrh   assert( p->zText!=0 || p->nChar==0 || p->accError );
992a70a073bSdrh   assert( N>=0 );
993255a81f1Sdrh   assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
994a70a073bSdrh   if( p->nChar+N >= p->nAlloc ){
995a70a073bSdrh     enlargeAndAppend(p,z,N);
996895decf6Sdan   }else if( N ){
997b07028f7Sdrh     assert( p->zText );
998ade86483Sdrh     p->nChar += N;
999172087fbSdrh     memcpy(&p->zText[p->nChar-N], z, N);
1000172087fbSdrh   }
1001483750baSdrh }
1002483750baSdrh 
1003483750baSdrh /*
1004a6353a3fSdrh ** Append the complete text of zero-terminated string z[] to the p string.
1005a6353a3fSdrh */
10060cdbe1aeSdrh void sqlite3_str_appendall(sqlite3_str *p, const char *z){
10070cdbe1aeSdrh   sqlite3_str_append(p, z, sqlite3Strlen30(z));
1008a6353a3fSdrh }
1009a6353a3fSdrh 
1010a6353a3fSdrh 
1011a6353a3fSdrh /*
1012ade86483Sdrh ** Finish off a string by making sure it is zero-terminated.
1013ade86483Sdrh ** Return a pointer to the resulting string.  Return a NULL
1014ade86483Sdrh ** pointer if any kind of error was encountered.
10155f968436Sdrh */
1016043e586eSdrh static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
10173f18e6d7Sdrh   char *zText;
1018043e586eSdrh   assert( p->mxAlloc>0 && !isMalloced(p) );
10193f18e6d7Sdrh   zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
10203f18e6d7Sdrh   if( zText ){
10213f18e6d7Sdrh     memcpy(zText, p->zText, p->nChar+1);
10225f4a686fSdrh     p->printfFlags |= SQLITE_PRINTF_MALLOCED;
1023ade86483Sdrh   }else{
10240cdbe1aeSdrh     setStrAccumError(p, SQLITE_NOMEM);
1025ade86483Sdrh   }
10263f18e6d7Sdrh   p->zText = zText;
10273f18e6d7Sdrh   return zText;
1028043e586eSdrh }
1029043e586eSdrh char *sqlite3StrAccumFinish(StrAccum *p){
1030043e586eSdrh   if( p->zText ){
1031043e586eSdrh     p->zText[p->nChar] = 0;
1032043e586eSdrh     if( p->mxAlloc>0 && !isMalloced(p) ){
1033043e586eSdrh       return strAccumFinishRealloc(p);
1034ade86483Sdrh     }
1035ade86483Sdrh   }
1036ade86483Sdrh   return p->zText;
1037ade86483Sdrh }
1038ade86483Sdrh 
1039f80bba9dSdrh /*
1040f80bba9dSdrh ** This singleton is an sqlite3_str object that is returned if
1041f80bba9dSdrh ** sqlite3_malloc() fails to provide space for a real one.  This
1042f80bba9dSdrh ** sqlite3_str object accepts no new text and always returns
1043f80bba9dSdrh ** an SQLITE_NOMEM error.
1044f80bba9dSdrh */
1045f80bba9dSdrh static sqlite3_str sqlite3OomStr = {
10463e62ddbfSdrh    0, 0, 0, 0, 0, SQLITE_NOMEM, 0
1047f80bba9dSdrh };
1048f80bba9dSdrh 
10490cdbe1aeSdrh /* Finalize a string created using sqlite3_str_new().
10500cdbe1aeSdrh */
10510cdbe1aeSdrh char *sqlite3_str_finish(sqlite3_str *p){
10520cdbe1aeSdrh   char *z;
1053f80bba9dSdrh   if( p!=0 && p!=&sqlite3OomStr ){
10540cdbe1aeSdrh     z = sqlite3StrAccumFinish(p);
1055446135d7Sdrh     sqlite3_free(p);
10560cdbe1aeSdrh   }else{
10570cdbe1aeSdrh     z = 0;
10580cdbe1aeSdrh   }
10590cdbe1aeSdrh   return z;
10600cdbe1aeSdrh }
10610cdbe1aeSdrh 
10620cdbe1aeSdrh /* Return any error code associated with p */
10630cdbe1aeSdrh int sqlite3_str_errcode(sqlite3_str *p){
10640cdbe1aeSdrh   return p ? p->accError : SQLITE_NOMEM;
10650cdbe1aeSdrh }
10660cdbe1aeSdrh 
10670cdbe1aeSdrh /* Return the current length of p in bytes */
10680cdbe1aeSdrh int sqlite3_str_length(sqlite3_str *p){
10690cdbe1aeSdrh   return p ? p->nChar : 0;
10700cdbe1aeSdrh }
10710cdbe1aeSdrh 
10720cdbe1aeSdrh /* Return the current value for p */
10730cdbe1aeSdrh char *sqlite3_str_value(sqlite3_str *p){
1074446135d7Sdrh   if( p==0 || p->nChar==0 ) return 0;
1075446135d7Sdrh   p->zText[p->nChar] = 0;
1076446135d7Sdrh   return p->zText;
10770cdbe1aeSdrh }
10780cdbe1aeSdrh 
1079ade86483Sdrh /*
1080ade86483Sdrh ** Reset an StrAccum string.  Reclaim all malloced memory.
1081ade86483Sdrh */
10820cdbe1aeSdrh void sqlite3_str_reset(StrAccum *p){
10835f4a686fSdrh   if( isMalloced(p) ){
1084633e6d57Sdrh     sqlite3DbFree(p->db, p->zText);
10855f4a686fSdrh     p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
1086ade86483Sdrh   }
1087446135d7Sdrh   p->nAlloc = 0;
1088446135d7Sdrh   p->nChar = 0;
1089f089aa45Sdrh   p->zText = 0;
1090ade86483Sdrh }
1091ade86483Sdrh 
1092ade86483Sdrh /*
1093c0490572Sdrh ** Initialize a string accumulator.
1094c0490572Sdrh **
1095c0490572Sdrh ** p:     The accumulator to be initialized.
1096c0490572Sdrh ** db:    Pointer to a database connection.  May be NULL.  Lookaside
1097c0490572Sdrh **        memory is used if not NULL. db->mallocFailed is set appropriately
1098c0490572Sdrh **        when not NULL.
1099c0490572Sdrh ** zBase: An initial buffer.  May be NULL in which case the initial buffer
1100c0490572Sdrh **        is malloced.
1101c0490572Sdrh ** n:     Size of zBase in bytes.  If total space requirements never exceed
1102c0490572Sdrh **        n then no memory allocations ever occur.
1103c0490572Sdrh ** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
1104c0490572Sdrh **        allocations will ever occur.
1105ade86483Sdrh */
1106c0490572Sdrh void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
11073f18e6d7Sdrh   p->zText = zBase;
1108c0490572Sdrh   p->db = db;
1109ade86483Sdrh   p->nAlloc = n;
1110bb4957f8Sdrh   p->mxAlloc = mx;
11113f18e6d7Sdrh   p->nChar = 0;
1112b49bc86aSdrh   p->accError = 0;
11135f4a686fSdrh   p->printfFlags = 0;
11145f968436Sdrh }
11155f968436Sdrh 
11160cdbe1aeSdrh /* Allocate and initialize a new dynamic string object */
11170cdbe1aeSdrh sqlite3_str *sqlite3_str_new(sqlite3 *db){
1118446135d7Sdrh   sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
11190cdbe1aeSdrh   if( p ){
1120446135d7Sdrh     sqlite3StrAccumInit(p, 0, 0, 0,
1121446135d7Sdrh             db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
1122f80bba9dSdrh   }else{
1123f80bba9dSdrh     p = &sqlite3OomStr;
11240cdbe1aeSdrh   }
11250cdbe1aeSdrh   return p;
11260cdbe1aeSdrh }
11270cdbe1aeSdrh 
11285f968436Sdrh /*
11295f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
11305f968436Sdrh ** %-conversion extensions.
11315f968436Sdrh */
113217435752Sdrh char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
113317435752Sdrh   char *z;
113479158e18Sdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
1135ade86483Sdrh   StrAccum acc;
1136bc6160b0Sdrh   assert( db!=0 );
1137c0490572Sdrh   sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
1138bc6160b0Sdrh                       db->aLimit[SQLITE_LIMIT_LENGTH]);
11395f4a686fSdrh   acc.printfFlags = SQLITE_PRINTF_INTERNAL;
11400cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1141ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
11420cdbe1aeSdrh   if( acc.accError==SQLITE_NOMEM ){
11434a642b60Sdrh     sqlite3OomFault(db);
114417435752Sdrh   }
114517435752Sdrh   return z;
11465f968436Sdrh }
11475f968436Sdrh 
11485f968436Sdrh /*
11495f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
11505f968436Sdrh ** %-conversion extensions.
11515f968436Sdrh */
115217435752Sdrh char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
11535f968436Sdrh   va_list ap;
11545f968436Sdrh   char *z;
11555f968436Sdrh   va_start(ap, zFormat);
1156ade86483Sdrh   z = sqlite3VMPrintf(db, zFormat, ap);
11575f968436Sdrh   va_end(ap);
11585f968436Sdrh   return z;
11595f968436Sdrh }
11605f968436Sdrh 
11615f968436Sdrh /*
116228dd479cSdrh ** Print into memory obtained from sqlite3_malloc().  Omit the internal
116328dd479cSdrh ** %-conversion extensions.
116428dd479cSdrh */
116528dd479cSdrh char *sqlite3_vmprintf(const char *zFormat, va_list ap){
1166ade86483Sdrh   char *z;
116728dd479cSdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
1168ade86483Sdrh   StrAccum acc;
11699ca95730Sdrh 
11709ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
11719ca95730Sdrh   if( zFormat==0 ){
11729ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
11739ca95730Sdrh     return 0;
11749ca95730Sdrh   }
11759ca95730Sdrh #endif
1176ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
1177ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
1178ff1590eeSdrh #endif
1179c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
11800cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1181ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
1182ade86483Sdrh   return z;
118328dd479cSdrh }
118428dd479cSdrh 
118528dd479cSdrh /*
118628dd479cSdrh ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
118728dd479cSdrh ** %-conversion extensions.
1188483750baSdrh */
11896f8a503dSdanielk1977 char *sqlite3_mprintf(const char *zFormat, ...){
1190a18c5681Sdrh   va_list ap;
11915f968436Sdrh   char *z;
1192ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
1193ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
1194ff1590eeSdrh #endif
1195a18c5681Sdrh   va_start(ap, zFormat);
1196b3738b6cSdrh   z = sqlite3_vmprintf(zFormat, ap);
1197a18c5681Sdrh   va_end(ap);
11985f968436Sdrh   return z;
1199a18c5681Sdrh }
1200a18c5681Sdrh 
1201a18c5681Sdrh /*
12026f8a503dSdanielk1977 ** sqlite3_snprintf() works like snprintf() except that it ignores the
120393a5c6bdSdrh ** current locale settings.  This is important for SQLite because we
120493a5c6bdSdrh ** are not able to use a "," as the decimal point in place of "." as
120593a5c6bdSdrh ** specified by some locales.
1206db26d4c9Sdrh **
1207db26d4c9Sdrh ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
1208db26d4c9Sdrh ** from the snprintf() standard.  Unfortunately, it is too late to change
1209db26d4c9Sdrh ** this without breaking compatibility, so we just have to live with the
1210db26d4c9Sdrh ** mistake.
1211db26d4c9Sdrh **
1212db26d4c9Sdrh ** sqlite3_vsnprintf() is the varargs version.
121393a5c6bdSdrh */
1214db26d4c9Sdrh char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
1215db26d4c9Sdrh   StrAccum acc;
1216db26d4c9Sdrh   if( n<=0 ) return zBuf;
12179ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
12189ca95730Sdrh   if( zBuf==0 || zFormat==0 ) {
12199ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
122096c707a3Sdrh     if( zBuf ) zBuf[0] = 0;
12219ca95730Sdrh     return zBuf;
12229ca95730Sdrh   }
12239ca95730Sdrh #endif
1224c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
12250cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1226e9bb5660Sdrh   zBuf[acc.nChar] = 0;
1227e9bb5660Sdrh   return zBuf;
1228db26d4c9Sdrh }
12296f8a503dSdanielk1977 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
12305f968436Sdrh   char *z;
123193a5c6bdSdrh   va_list ap;
123293a5c6bdSdrh   va_start(ap,zFormat);
1233db26d4c9Sdrh   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
123493a5c6bdSdrh   va_end(ap);
12355f968436Sdrh   return z;
123693a5c6bdSdrh }
123793a5c6bdSdrh 
12383f280701Sdrh /*
12397c0c460fSdrh ** This is the routine that actually formats the sqlite3_log() message.
12407c0c460fSdrh ** We house it in a separate routine from sqlite3_log() to avoid using
12417c0c460fSdrh ** stack space on small-stack systems when logging is disabled.
12427c0c460fSdrh **
12437c0c460fSdrh ** sqlite3_log() must render into a static buffer.  It cannot dynamically
12447c0c460fSdrh ** allocate memory because it might be called while the memory allocator
12457c0c460fSdrh ** mutex is held.
1246a8dbd52aSdrh **
12470cdbe1aeSdrh ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
1248a8dbd52aSdrh ** certain format characters (%q) or for very large precisions or widths.
1249a8dbd52aSdrh ** Care must be taken that any sqlite3_log() calls that occur while the
1250a8dbd52aSdrh ** memory mutex is held do not use these mechanisms.
12517c0c460fSdrh */
12527c0c460fSdrh static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
12537c0c460fSdrh   StrAccum acc;                          /* String accumulator */
1254a64fa912Sdrh   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
12557c0c460fSdrh 
1256c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
12570cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
12587c0c460fSdrh   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
12597c0c460fSdrh                            sqlite3StrAccumFinish(&acc));
12607c0c460fSdrh }
12617c0c460fSdrh 
12627c0c460fSdrh /*
12633f280701Sdrh ** Format and write a message to the log if logging is enabled.
12643f280701Sdrh */
1265a7564663Sdrh void sqlite3_log(int iErrCode, const char *zFormat, ...){
12663f280701Sdrh   va_list ap;                             /* Vararg list */
12677c0c460fSdrh   if( sqlite3GlobalConfig.xLog ){
12683f280701Sdrh     va_start(ap, zFormat);
12697c0c460fSdrh     renderLogMsg(iErrCode, zFormat, ap);
12703f280701Sdrh     va_end(ap);
12713f280701Sdrh   }
12723f280701Sdrh }
12733f280701Sdrh 
127402b0e267Smistachkin #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
1275e54ca3feSdrh /*
1276e54ca3feSdrh ** A version of printf() that understands %lld.  Used for debugging.
1277e54ca3feSdrh ** The printf() built into some versions of windows does not understand %lld
1278e54ca3feSdrh ** and segfaults if you give it a long long int.
1279e54ca3feSdrh */
1280e54ca3feSdrh void sqlite3DebugPrintf(const char *zFormat, ...){
1281e54ca3feSdrh   va_list ap;
1282ade86483Sdrh   StrAccum acc;
1283a8e41ecaSmistachkin   char zBuf[SQLITE_PRINT_BUF_SIZE*10];
1284c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
1285e54ca3feSdrh   va_start(ap,zFormat);
12860cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1287e54ca3feSdrh   va_end(ap);
1288bed8e7e5Sdrh   sqlite3StrAccumFinish(&acc);
12894a9ff918Smistachkin #ifdef SQLITE_OS_TRACE_PROC
12904a9ff918Smistachkin   {
12914a9ff918Smistachkin     extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
12924a9ff918Smistachkin     SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
12934a9ff918Smistachkin   }
12944a9ff918Smistachkin #else
1295485f0039Sdrh   fprintf(stdout,"%s", zBuf);
12962ac3ee97Sdrh   fflush(stdout);
12974a9ff918Smistachkin #endif
1298e54ca3feSdrh }
1299e54ca3feSdrh #endif
1300c7bc4fdeSdrh 
13014fa4a54fSdrh 
1302c7bc4fdeSdrh /*
13030cdbe1aeSdrh ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
1304d37bea5bSdrh ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
1305c7bc4fdeSdrh */
13060cdbe1aeSdrh void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
1307c7bc4fdeSdrh   va_list ap;
1308c7bc4fdeSdrh   va_start(ap,zFormat);
13090cdbe1aeSdrh   sqlite3_str_vappendf(p, zFormat, ap);
1310c7bc4fdeSdrh   va_end(ap);
1311c7bc4fdeSdrh }
1312