xref: /sqlite-3.40.0/src/printf.c (revision 2c338a9d)
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 */
18*2c338a9dSdrh #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 */
36*2c338a9dSdrh #define etDECIMAL    16 /* %d or %u, but not %x, %o */
37e84a306bSdrh 
38*2c338a9dSdrh #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 */
63*2c338a9dSdrh #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[] = {
73*2c338a9dSdrh   {  '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 },
82*2c338a9dSdrh   {  '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
91*2c338a9dSdrh   {  '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 
102a18c5681Sdrh /*
103b37df7b9Sdrh ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
104a18c5681Sdrh ** conversions will work.
105a18c5681Sdrh */
106b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
107a18c5681Sdrh /*
108a18c5681Sdrh ** "*val" is a double such that 0.1 <= *val < 10.0
109a18c5681Sdrh ** Return the ascii code for the leading digit of *val, then
110a18c5681Sdrh ** multiply "*val" by 10.0 to renormalize.
111a18c5681Sdrh **
112a18c5681Sdrh ** Example:
113a18c5681Sdrh **     input:     *val = 3.14159
114a18c5681Sdrh **     output:    *val = 1.4159    function return = '3'
115a18c5681Sdrh **
116a18c5681Sdrh ** The counter *cnt is incremented each time.  After counter exceeds
117a18c5681Sdrh ** 16 (the number of significant digits in a 64-bit float) '0' is
118a18c5681Sdrh ** always returned.
119a18c5681Sdrh */
120ea678832Sdrh static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
121a18c5681Sdrh   int digit;
122384eef32Sdrh   LONGDOUBLE_TYPE d;
12372b3fbc7Sdrh   if( (*cnt)<=0 ) return '0';
12472b3fbc7Sdrh   (*cnt)--;
125a18c5681Sdrh   digit = (int)*val;
126a18c5681Sdrh   d = digit;
127a18c5681Sdrh   digit += '0';
128a18c5681Sdrh   *val = (*val - d)*10.0;
129ea678832Sdrh   return (char)digit;
130a18c5681Sdrh }
131b37df7b9Sdrh #endif /* SQLITE_OMIT_FLOATING_POINT */
132a18c5681Sdrh 
13379158e18Sdrh /*
134a6353a3fSdrh ** Set the StrAccum object to an error mode.
135a6353a3fSdrh */
136a5c1416dSdrh static void setStrAccumError(StrAccum *p, u8 eError){
137c0490572Sdrh   assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
138a6353a3fSdrh   p->accError = eError;
139a6353a3fSdrh   p->nAlloc = 0;
140a6353a3fSdrh }
141a6353a3fSdrh 
142a6353a3fSdrh /*
143a5c1416dSdrh ** Extra argument values from a PrintfArguments object
144a5c1416dSdrh */
145a5c1416dSdrh static sqlite3_int64 getIntArg(PrintfArguments *p){
146a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0;
147a5c1416dSdrh   return sqlite3_value_int64(p->apArg[p->nUsed++]);
148a5c1416dSdrh }
149a5c1416dSdrh static double getDoubleArg(PrintfArguments *p){
150a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0.0;
151a5c1416dSdrh   return sqlite3_value_double(p->apArg[p->nUsed++]);
152a5c1416dSdrh }
153a5c1416dSdrh static char *getTextArg(PrintfArguments *p){
154a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0;
155a5c1416dSdrh   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
156a5c1416dSdrh }
157a5c1416dSdrh 
158a5c1416dSdrh 
159a5c1416dSdrh /*
16079158e18Sdrh ** On machines with a small stack size, you can redefine the
161ed1fddf4Sdrh ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
16279158e18Sdrh */
16379158e18Sdrh #ifndef SQLITE_PRINT_BUF_SIZE
16459eedf79Sdrh # define SQLITE_PRINT_BUF_SIZE 70
16550d654daSdrh #endif
16679158e18Sdrh #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
167a18c5681Sdrh 
168a18c5681Sdrh /*
169ed1fddf4Sdrh ** Render a string given by "fmt" into the StrAccum object.
170a18c5681Sdrh */
171f089aa45Sdrh void sqlite3VXPrintf(
172ade86483Sdrh   StrAccum *pAccum,          /* Accumulate results here */
1735f968436Sdrh   const char *fmt,           /* Format string */
1745f968436Sdrh   va_list ap                 /* arguments */
175a18c5681Sdrh ){
176e84a306bSdrh   int c;                     /* Next character in the format string */
177e84a306bSdrh   char *bufpt;               /* Pointer to the conversion buffer */
178e84a306bSdrh   int precision;             /* Precision of the current field */
179e84a306bSdrh   int length;                /* Length of the field */
180e84a306bSdrh   int idx;                   /* A general purpose loop counter */
181a18c5681Sdrh   int width;                 /* Width of the current field */
182e84a306bSdrh   etByte flag_leftjustify;   /* True if "-" flag is present */
183*2c338a9dSdrh   etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */
184e84a306bSdrh   etByte flag_alternateform; /* True if "#" flag is present */
185531fe878Sdrh   etByte flag_altform2;      /* True if "!" flag is present */
186e84a306bSdrh   etByte flag_zeropad;       /* True if field width constant starts with zero */
187*2c338a9dSdrh   etByte flag_long;          /* 1 for the "l" flag, 2 for "ll", 0 by default */
1883e9aeec0Sdrh   etByte done;               /* Loop termination flag */
189*2c338a9dSdrh   etByte cThousand;          /* Thousands separator for %d and %u */
190ad5a9d71Sdrh   etByte xtype = etINVALID;  /* Conversion paradigm */
191a5c1416dSdrh   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
192ed1fddf4Sdrh   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19327436af7Sdrh   sqlite_uint64 longvalue;   /* Value for integer types */
194384eef32Sdrh   LONGDOUBLE_TYPE realvalue; /* Value for real types */
1955719628aSdrh   const et_info *infop;      /* Pointer to the appropriate info structure */
19659eedf79Sdrh   char *zOut;                /* Rendering buffer */
19759eedf79Sdrh   int nOut;                  /* Size of the rendering buffer */
198af8f513fSdrh   char *zExtra = 0;          /* Malloced memory used by some conversion */
199b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
200557cc60fSdrh   int  exp, e2;              /* exponent of real numbers */
201ed1fddf4Sdrh   int nsd;                   /* Number of significant digits returned */
202a18c5681Sdrh   double rounder;            /* Used for rounding floating point values */
203e84a306bSdrh   etByte flag_dp;            /* True if decimal point should be shown */
204e84a306bSdrh   etByte flag_rtz;           /* True if trailing zeros should be removed */
205a18c5681Sdrh #endif
206a5c1416dSdrh   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
207ed1fddf4Sdrh   char buf[etBUFSIZE];       /* Conversion buffer */
208a18c5681Sdrh 
209a18c5681Sdrh   bufpt = 0;
2108236f688Sdrh   if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
211a5c1416dSdrh     pArgList = va_arg(ap, PrintfArguments*);
2128236f688Sdrh     bArgList = 1;
213a5c1416dSdrh   }else{
2148236f688Sdrh     bArgList = 0;
215a5c1416dSdrh   }
216a18c5681Sdrh   for(; (c=(*fmt))!=0; ++fmt){
217a18c5681Sdrh     if( c!='%' ){
218a18c5681Sdrh       bufpt = (char *)fmt;
219760b1598Sdrh #if HAVE_STRCHRNUL
220760b1598Sdrh       fmt = strchrnul(fmt, '%');
221760b1598Sdrh #else
222760b1598Sdrh       do{ fmt++; }while( *fmt && *fmt != '%' );
223760b1598Sdrh #endif
224a70a073bSdrh       sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
225760b1598Sdrh       if( *fmt==0 ) break;
226a18c5681Sdrh     }
227a18c5681Sdrh     if( (c=(*++fmt))==0 ){
228ade86483Sdrh       sqlite3StrAccumAppend(pAccum, "%", 1);
229a18c5681Sdrh       break;
230a18c5681Sdrh     }
231a18c5681Sdrh     /* Find out what flags are present */
232*2c338a9dSdrh     flag_leftjustify = flag_prefix = cThousand =
233557cc60fSdrh      flag_alternateform = flag_altform2 = flag_zeropad = 0;
2343e9aeec0Sdrh     done = 0;
235a18c5681Sdrh     do{
236a18c5681Sdrh       switch( c ){
2373e9aeec0Sdrh         case '-':   flag_leftjustify = 1;     break;
238*2c338a9dSdrh         case '+':   flag_prefix = '+';        break;
239*2c338a9dSdrh         case ' ':   flag_prefix = ' ';        break;
2403e9aeec0Sdrh         case '#':   flag_alternateform = 1;   break;
2413e9aeec0Sdrh         case '!':   flag_altform2 = 1;        break;
2423e9aeec0Sdrh         case '0':   flag_zeropad = 1;         break;
243*2c338a9dSdrh         case ',':   cThousand = ',';          break;
2443e9aeec0Sdrh         default:    done = 1;                 break;
245a18c5681Sdrh       }
2463e9aeec0Sdrh     }while( !done && (c=(*++fmt))!=0 );
247a18c5681Sdrh     /* Get the field width */
248a18c5681Sdrh     if( c=='*' ){
249a5c1416dSdrh       if( bArgList ){
250a5c1416dSdrh         width = (int)getIntArg(pArgList);
251a5c1416dSdrh       }else{
252a18c5681Sdrh         width = va_arg(ap,int);
253a5c1416dSdrh       }
254a18c5681Sdrh       if( width<0 ){
255a18c5681Sdrh         flag_leftjustify = 1;
256b6f47debSdrh         width = width >= -2147483647 ? -width : 0;
257a18c5681Sdrh       }
258a18c5681Sdrh       c = *++fmt;
259a18c5681Sdrh     }else{
260b6f47debSdrh       unsigned wx = 0;
26117a68934Sdrh       while( c>='0' && c<='9' ){
262b6f47debSdrh         wx = wx*10 + c - '0';
263a18c5681Sdrh         c = *++fmt;
264a18c5681Sdrh       }
265b6f47debSdrh       testcase( wx>0x7fffffff );
266b6f47debSdrh       width = wx & 0x7fffffff;
267a18c5681Sdrh     }
268c386ef4fSdrh     assert( width>=0 );
269c386ef4fSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
270c386ef4fSdrh     if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
271c386ef4fSdrh       width = SQLITE_PRINTF_PRECISION_LIMIT;
272c386ef4fSdrh     }
273c386ef4fSdrh #endif
2748c069147Sdan 
275a18c5681Sdrh     /* Get the precision */
276a18c5681Sdrh     if( c=='.' ){
277a18c5681Sdrh       c = *++fmt;
278a18c5681Sdrh       if( c=='*' ){
279a5c1416dSdrh         if( bArgList ){
280a5c1416dSdrh           precision = (int)getIntArg(pArgList);
281a5c1416dSdrh         }else{
282a18c5681Sdrh           precision = va_arg(ap,int);
283a5c1416dSdrh         }
284a18c5681Sdrh         c = *++fmt;
285b6f47debSdrh         if( precision<0 ){
286b6f47debSdrh           precision = precision >= -2147483647 ? -precision : -1;
287b6f47debSdrh         }
288a18c5681Sdrh       }else{
289b6f47debSdrh         unsigned px = 0;
29017a68934Sdrh         while( c>='0' && c<='9' ){
291b6f47debSdrh           px = px*10 + c - '0';
292a18c5681Sdrh           c = *++fmt;
293a18c5681Sdrh         }
294b6f47debSdrh         testcase( px>0x7fffffff );
295b6f47debSdrh         precision = px & 0x7fffffff;
296a18c5681Sdrh       }
297a18c5681Sdrh     }else{
298a18c5681Sdrh       precision = -1;
299a18c5681Sdrh     }
300c386ef4fSdrh     assert( precision>=(-1) );
301c386ef4fSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
302c386ef4fSdrh     if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
303c386ef4fSdrh       precision = SQLITE_PRINTF_PRECISION_LIMIT;
304c386ef4fSdrh     }
305c386ef4fSdrh #endif
306c386ef4fSdrh 
307c386ef4fSdrh 
308a18c5681Sdrh     /* Get the conversion type modifier */
309a18c5681Sdrh     if( c=='l' ){
310a18c5681Sdrh       flag_long = 1;
311a18c5681Sdrh       c = *++fmt;
312a34b6764Sdrh       if( c=='l' ){
313*2c338a9dSdrh         flag_long = 2;
314a34b6764Sdrh         c = *++fmt;
315a34b6764Sdrh       }
316a34b6764Sdrh     }else{
317*2c338a9dSdrh       flag_long = 0;
318a18c5681Sdrh     }
319a18c5681Sdrh     /* Fetch the info entry for the field */
320874ba04cSdrh     infop = &fmtinfo[0];
321874ba04cSdrh     xtype = etINVALID;
32200e13613Sdanielk1977     for(idx=0; idx<ArraySize(fmtinfo); idx++){
323a18c5681Sdrh       if( c==fmtinfo[idx].fmttype ){
324a18c5681Sdrh         infop = &fmtinfo[idx];
325e84a306bSdrh         xtype = infop->type;
326a18c5681Sdrh         break;
327a18c5681Sdrh       }
328a18c5681Sdrh     }
32943617e9aSdrh 
330a18c5681Sdrh     /*
331a18c5681Sdrh     ** At this point, variables are initialized as follows:
332a18c5681Sdrh     **
333a18c5681Sdrh     **   flag_alternateform          TRUE if a '#' is present.
3343e9aeec0Sdrh     **   flag_altform2               TRUE if a '!' is present.
335*2c338a9dSdrh     **   flag_prefix                 '+' or ' ' or zero
336a18c5681Sdrh     **   flag_leftjustify            TRUE if a '-' is present or if the
337a18c5681Sdrh     **                               field width was negative.
338a18c5681Sdrh     **   flag_zeropad                TRUE if the width began with 0.
339*2c338a9dSdrh     **   flag_long                   1 for "l", 2 for "ll"
340a18c5681Sdrh     **   width                       The specified field width.  This is
341a18c5681Sdrh     **                               always non-negative.  Zero is the default.
342a18c5681Sdrh     **   precision                   The specified precision.  The default
343a18c5681Sdrh     **                               is -1.
344a18c5681Sdrh     **   xtype                       The class of the conversion.
345a18c5681Sdrh     **   infop                       Pointer to the appropriate info struct.
346a18c5681Sdrh     */
347a18c5681Sdrh     switch( xtype ){
348fe63d1c9Sdrh       case etPOINTER:
349*2c338a9dSdrh         flag_long = sizeof(char*)==sizeof(i64) ? 2 :
350*2c338a9dSdrh                      sizeof(char*)==sizeof(long int) ? 1 : 0;
351fe63d1c9Sdrh         /* Fall through into the next case */
3529a99334dSdrh       case etORDINAL:
353a18c5681Sdrh       case etRADIX:
354*2c338a9dSdrh         cThousand = 0;
355*2c338a9dSdrh         /* Fall through into the next case */
356*2c338a9dSdrh       case etDECIMAL:
357e84a306bSdrh         if( infop->flags & FLAG_SIGNED ){
358e9707671Sdrh           i64 v;
359a5c1416dSdrh           if( bArgList ){
360a5c1416dSdrh             v = getIntArg(pArgList);
361eeb23a4cSdrh           }else if( flag_long ){
362*2c338a9dSdrh             if( flag_long==2 ){
363*2c338a9dSdrh               v = va_arg(ap,i64) ;
364*2c338a9dSdrh             }else{
365eeb23a4cSdrh               v = va_arg(ap,long int);
366*2c338a9dSdrh             }
367eeb23a4cSdrh           }else{
368eeb23a4cSdrh             v = va_arg(ap,int);
369eeb23a4cSdrh           }
370e9707671Sdrh           if( v<0 ){
371158b9cb9Sdrh             if( v==SMALLEST_INT64 ){
372158b9cb9Sdrh               longvalue = ((u64)1)<<63;
373158b9cb9Sdrh             }else{
374158b9cb9Sdrh               longvalue = -v;
375158b9cb9Sdrh             }
376cfcdaefeSdanielk1977             prefix = '-';
377cfcdaefeSdanielk1977           }else{
378e9707671Sdrh             longvalue = v;
379*2c338a9dSdrh             prefix = flag_prefix;
380cfcdaefeSdanielk1977           }
381e9707671Sdrh         }else{
382a5c1416dSdrh           if( bArgList ){
383a5c1416dSdrh             longvalue = (u64)getIntArg(pArgList);
384eeb23a4cSdrh           }else if( flag_long ){
385*2c338a9dSdrh             if( flag_long==2 ){
386*2c338a9dSdrh               longvalue = va_arg(ap,u64);
387*2c338a9dSdrh             }else{
388eeb23a4cSdrh               longvalue = va_arg(ap,unsigned long int);
389*2c338a9dSdrh             }
390eeb23a4cSdrh           }else{
391eeb23a4cSdrh             longvalue = va_arg(ap,unsigned int);
392eeb23a4cSdrh           }
393e9707671Sdrh           prefix = 0;
394e9707671Sdrh         }
395e9707671Sdrh         if( longvalue==0 ) flag_alternateform = 0;
396a18c5681Sdrh         if( flag_zeropad && precision<width-(prefix!=0) ){
397a18c5681Sdrh           precision = width-(prefix!=0);
398a18c5681Sdrh         }
399*2c338a9dSdrh         if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
40059eedf79Sdrh           nOut = etBUFSIZE;
40159eedf79Sdrh           zOut = buf;
40259eedf79Sdrh         }else{
403*2c338a9dSdrh           nOut = precision + 10 + precision/3;
40459eedf79Sdrh           zOut = zExtra = sqlite3Malloc( nOut );
40559eedf79Sdrh           if( zOut==0 ){
406a6353a3fSdrh             setStrAccumError(pAccum, STRACCUM_NOMEM);
40759eedf79Sdrh             return;
40859eedf79Sdrh           }
40959eedf79Sdrh         }
41059eedf79Sdrh         bufpt = &zOut[nOut-1];
4119a99334dSdrh         if( xtype==etORDINAL ){
41243f6e064Sdrh           static const char zOrd[] = "thstndrd";
413ea678832Sdrh           int x = (int)(longvalue % 10);
41443f6e064Sdrh           if( x>=4 || (longvalue/10)%10==1 ){
41543f6e064Sdrh             x = 0;
41643f6e064Sdrh           }
41759eedf79Sdrh           *(--bufpt) = zOrd[x*2+1];
41859eedf79Sdrh           *(--bufpt) = zOrd[x*2];
4199a99334dSdrh         }
420a18c5681Sdrh         {
4210e682099Sdrh           const char *cset = &aDigits[infop->charset];
4220e682099Sdrh           u8 base = infop->base;
423a18c5681Sdrh           do{                                           /* Convert to ascii */
424a18c5681Sdrh             *(--bufpt) = cset[longvalue%base];
425a18c5681Sdrh             longvalue = longvalue/base;
426a18c5681Sdrh           }while( longvalue>0 );
427a18c5681Sdrh         }
42859eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
429*2c338a9dSdrh         while( precision>length ){
430a18c5681Sdrh           *(--bufpt) = '0';                             /* Zero pad */
431*2c338a9dSdrh           length++;
432*2c338a9dSdrh         }
433*2c338a9dSdrh         if( cThousand ){
434*2c338a9dSdrh           int nn = (length - 1)/3;  /* Number of "," to insert */
435*2c338a9dSdrh           int ix = (length - 1)%3 + 1;
436*2c338a9dSdrh           bufpt -= nn;
437*2c338a9dSdrh           for(idx=0; nn>0; idx++){
438*2c338a9dSdrh             bufpt[idx] = bufpt[idx+nn];
439*2c338a9dSdrh             ix--;
440*2c338a9dSdrh             if( ix==0 ){
441*2c338a9dSdrh               bufpt[++idx] = cThousand;
442*2c338a9dSdrh               nn--;
443*2c338a9dSdrh               ix = 3;
444*2c338a9dSdrh             }
445*2c338a9dSdrh           }
446a18c5681Sdrh         }
447a18c5681Sdrh         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
448a18c5681Sdrh         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
44976ff3a0eSdrh           const char *pre;
45076ff3a0eSdrh           char x;
45176ff3a0eSdrh           pre = &aPrefix[infop->prefix];
45276ff3a0eSdrh           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
453a18c5681Sdrh         }
45459eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
455a18c5681Sdrh         break;
456a18c5681Sdrh       case etFLOAT:
457a18c5681Sdrh       case etEXP:
458a18c5681Sdrh       case etGENERIC:
459a5c1416dSdrh         if( bArgList ){
460a5c1416dSdrh           realvalue = getDoubleArg(pArgList);
461a5c1416dSdrh         }else{
462a18c5681Sdrh           realvalue = va_arg(ap,double);
463a5c1416dSdrh         }
46469ef7036Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
46569ef7036Sdrh         length = 0;
46669ef7036Sdrh #else
467a18c5681Sdrh         if( precision<0 ) precision = 6;         /* Set default precision */
468a18c5681Sdrh         if( realvalue<0.0 ){
469a18c5681Sdrh           realvalue = -realvalue;
470a18c5681Sdrh           prefix = '-';
471a18c5681Sdrh         }else{
472*2c338a9dSdrh           prefix = flag_prefix;
473a18c5681Sdrh         }
4743e9aeec0Sdrh         if( xtype==etGENERIC && precision>0 ) precision--;
475a30d22a7Sdrh         testcase( precision>0xfff );
47674b42275Sdrh         for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
4773e9aeec0Sdrh         if( xtype==etFLOAT ) realvalue += rounder;
478a18c5681Sdrh         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
479a18c5681Sdrh         exp = 0;
480ea678832Sdrh         if( sqlite3IsNaN((double)realvalue) ){
48153c14021Sdrh           bufpt = "NaN";
48253c14021Sdrh           length = 3;
48353c14021Sdrh           break;
48453c14021Sdrh         }
485a18c5681Sdrh         if( realvalue>0.0 ){
48672b3fbc7Sdrh           LONGDOUBLE_TYPE scale = 1.0;
4874ef94130Sdrh           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
4882a8f6712Sdrh           while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
48972b3fbc7Sdrh           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
49072b3fbc7Sdrh           realvalue /= scale;
491af005fbcSdrh           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
492af005fbcSdrh           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
493af005fbcSdrh           if( exp>350 ){
4942a8f6712Sdrh             bufpt = buf;
4952a8f6712Sdrh             buf[0] = prefix;
4962a8f6712Sdrh             memcpy(buf+(prefix!=0),"Inf",4);
4972a8f6712Sdrh             length = 3+(prefix!=0);
498a18c5681Sdrh             break;
499a18c5681Sdrh           }
500a18c5681Sdrh         }
501a18c5681Sdrh         bufpt = buf;
502a18c5681Sdrh         /*
503a18c5681Sdrh         ** If the field type is etGENERIC, then convert to either etEXP
504a18c5681Sdrh         ** or etFLOAT, as appropriate.
505a18c5681Sdrh         */
506a18c5681Sdrh         if( xtype!=etFLOAT ){
507a18c5681Sdrh           realvalue += rounder;
508a18c5681Sdrh           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
509a18c5681Sdrh         }
510a18c5681Sdrh         if( xtype==etGENERIC ){
511a18c5681Sdrh           flag_rtz = !flag_alternateform;
512a18c5681Sdrh           if( exp<-4 || exp>precision ){
513a18c5681Sdrh             xtype = etEXP;
514a18c5681Sdrh           }else{
515a18c5681Sdrh             precision = precision - exp;
516a18c5681Sdrh             xtype = etFLOAT;
517a18c5681Sdrh           }
518a18c5681Sdrh         }else{
51972b3fbc7Sdrh           flag_rtz = flag_altform2;
520a18c5681Sdrh         }
521557cc60fSdrh         if( xtype==etEXP ){
522557cc60fSdrh           e2 = 0;
523557cc60fSdrh         }else{
524557cc60fSdrh           e2 = exp;
525557cc60fSdrh         }
52674b42275Sdrh         if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
52774b42275Sdrh           bufpt = zExtra
52874b42275Sdrh               = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
52959eedf79Sdrh           if( bufpt==0 ){
530a6353a3fSdrh             setStrAccumError(pAccum, STRACCUM_NOMEM);
53159eedf79Sdrh             return;
53259eedf79Sdrh           }
53359eedf79Sdrh         }
53459eedf79Sdrh         zOut = bufpt;
53572b3fbc7Sdrh         nsd = 16 + flag_altform2*10;
536ea678832Sdrh         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
537557cc60fSdrh         /* The sign in front of the number */
538557cc60fSdrh         if( prefix ){
539557cc60fSdrh           *(bufpt++) = prefix;
540557cc60fSdrh         }
541557cc60fSdrh         /* Digits prior to the decimal point */
542557cc60fSdrh         if( e2<0 ){
543557cc60fSdrh           *(bufpt++) = '0';
544557cc60fSdrh         }else{
545557cc60fSdrh           for(; e2>=0; e2--){
546557cc60fSdrh             *(bufpt++) = et_getdigit(&realvalue,&nsd);
547557cc60fSdrh           }
548557cc60fSdrh         }
549557cc60fSdrh         /* The decimal point */
550557cc60fSdrh         if( flag_dp ){
551557cc60fSdrh           *(bufpt++) = '.';
552557cc60fSdrh         }
553557cc60fSdrh         /* "0" digits after the decimal point but before the first
554557cc60fSdrh         ** significant digit of the number */
555af005fbcSdrh         for(e2++; e2<0; precision--, e2++){
556af005fbcSdrh           assert( precision>0 );
557a18c5681Sdrh           *(bufpt++) = '0';
558a18c5681Sdrh         }
559557cc60fSdrh         /* Significant digits after the decimal point */
560557cc60fSdrh         while( (precision--)>0 ){
561557cc60fSdrh           *(bufpt++) = et_getdigit(&realvalue,&nsd);
562a18c5681Sdrh         }
563557cc60fSdrh         /* Remove trailing zeros and the "." if no digits follow the "." */
564557cc60fSdrh         if( flag_rtz && flag_dp ){
5653e9aeec0Sdrh           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
56659eedf79Sdrh           assert( bufpt>zOut );
5673e9aeec0Sdrh           if( bufpt[-1]=='.' ){
568557cc60fSdrh             if( flag_altform2 ){
569557cc60fSdrh               *(bufpt++) = '0';
570557cc60fSdrh             }else{
571557cc60fSdrh               *(--bufpt) = 0;
572a18c5681Sdrh             }
573557cc60fSdrh           }
574557cc60fSdrh         }
575557cc60fSdrh         /* Add the "eNNN" suffix */
57659eedf79Sdrh         if( xtype==etEXP ){
57776ff3a0eSdrh           *(bufpt++) = aDigits[infop->charset];
578557cc60fSdrh           if( exp<0 ){
579557cc60fSdrh             *(bufpt++) = '-'; exp = -exp;
580557cc60fSdrh           }else{
581557cc60fSdrh             *(bufpt++) = '+';
582557cc60fSdrh           }
583a18c5681Sdrh           if( exp>=100 ){
584ea678832Sdrh             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
585a18c5681Sdrh             exp %= 100;
586a18c5681Sdrh           }
587ea678832Sdrh           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
588ea678832Sdrh           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
589a18c5681Sdrh         }
590557cc60fSdrh         *bufpt = 0;
591557cc60fSdrh 
592a18c5681Sdrh         /* The converted number is in buf[] and zero terminated. Output it.
593a18c5681Sdrh         ** Note that the number is in the usual order, not reversed as with
594a18c5681Sdrh         ** integer conversions. */
59559eedf79Sdrh         length = (int)(bufpt-zOut);
59659eedf79Sdrh         bufpt = zOut;
597a18c5681Sdrh 
598a18c5681Sdrh         /* Special case:  Add leading zeros if the flag_zeropad flag is
599a18c5681Sdrh         ** set and we are not left justified */
600a18c5681Sdrh         if( flag_zeropad && !flag_leftjustify && length < width){
601a18c5681Sdrh           int i;
602a18c5681Sdrh           int nPad = width - length;
603a18c5681Sdrh           for(i=width; i>=nPad; i--){
604a18c5681Sdrh             bufpt[i] = bufpt[i-nPad];
605a18c5681Sdrh           }
606a18c5681Sdrh           i = prefix!=0;
607a18c5681Sdrh           while( nPad-- ) bufpt[i++] = '0';
608a18c5681Sdrh           length = width;
609a18c5681Sdrh         }
61069ef7036Sdrh #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
611a18c5681Sdrh         break;
612a18c5681Sdrh       case etSIZE:
613fc6ee9dfSdrh         if( !bArgList ){
614fc6ee9dfSdrh           *(va_arg(ap,int*)) = pAccum->nChar;
615fc6ee9dfSdrh         }
616a18c5681Sdrh         length = width = 0;
617a18c5681Sdrh         break;
618a18c5681Sdrh       case etPERCENT:
619a18c5681Sdrh         buf[0] = '%';
620a18c5681Sdrh         bufpt = buf;
621a18c5681Sdrh         length = 1;
622a18c5681Sdrh         break;
623a18c5681Sdrh       case etCHARX:
624a5c1416dSdrh         if( bArgList ){
625fc6ee9dfSdrh           bufpt = getTextArg(pArgList);
626fc6ee9dfSdrh           c = bufpt ? bufpt[0] : 0;
627a5c1416dSdrh         }else{
628ea678832Sdrh           c = va_arg(ap,int);
629a5c1416dSdrh         }
630af8f513fSdrh         if( precision>1 ){
631af8f513fSdrh           width -= precision-1;
632af8f513fSdrh           if( width>1 && !flag_leftjustify ){
633af8f513fSdrh             sqlite3AppendChar(pAccum, width-1, ' ');
634af8f513fSdrh             width = 0;
635a18c5681Sdrh           }
636af8f513fSdrh           sqlite3AppendChar(pAccum, precision-1, c);
637af8f513fSdrh         }
638af8f513fSdrh         length = 1;
639af8f513fSdrh         buf[0] = c;
640a18c5681Sdrh         bufpt = buf;
641a18c5681Sdrh         break;
642a18c5681Sdrh       case etSTRING:
643d93d8a81Sdrh       case etDYNSTRING:
644a5c1416dSdrh         if( bArgList ){
645a5c1416dSdrh           bufpt = getTextArg(pArgList);
6462a8f6712Sdrh           xtype = etSTRING;
647a5c1416dSdrh         }else{
648cb485882Sdrh           bufpt = va_arg(ap,char*);
649a5c1416dSdrh         }
650d93d8a81Sdrh         if( bufpt==0 ){
651d93d8a81Sdrh           bufpt = "";
6522a8f6712Sdrh         }else if( xtype==etDYNSTRING ){
653d93d8a81Sdrh           zExtra = bufpt;
654d93d8a81Sdrh         }
655e509094bSdrh         if( precision>=0 ){
656e509094bSdrh           for(length=0; length<precision && bufpt[length]; length++){}
657e509094bSdrh         }else{
658ea678832Sdrh           length = sqlite3Strlen30(bufpt);
659e509094bSdrh         }
660a18c5681Sdrh         break;
6612a8f6712Sdrh       case etSQLESCAPE:           /* Escape ' characters */
6622a8f6712Sdrh       case etSQLESCAPE2:          /* Escape ' and enclose in '...' */
6632a8f6712Sdrh       case etSQLESCAPE3: {        /* Escape " characters */
6648965b50eSdrh         int i, j, k, n, isnull;
6654794f735Sdrh         int needQuote;
666ea678832Sdrh         char ch;
667f3b863edSdanielk1977         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
668a5c1416dSdrh         char *escarg;
669a5c1416dSdrh 
670a5c1416dSdrh         if( bArgList ){
671a5c1416dSdrh           escarg = getTextArg(pArgList);
672a5c1416dSdrh         }else{
673a5c1416dSdrh           escarg = va_arg(ap,char*);
674a5c1416dSdrh         }
675f0113000Sdanielk1977         isnull = escarg==0;
676f0113000Sdanielk1977         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
6778965b50eSdrh         k = precision;
67860d4a304Sdan         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
679f3b863edSdanielk1977           if( ch==q )  n++;
680a18c5681Sdrh         }
6814794f735Sdrh         needQuote = !isnull && xtype==etSQLESCAPE2;
6822a8f6712Sdrh         n += i + 3;
683a18c5681Sdrh         if( n>etBUFSIZE ){
684e5ae5735Sdrh           bufpt = zExtra = sqlite3Malloc( n );
685d164fd34Sdrh           if( bufpt==0 ){
686a6353a3fSdrh             setStrAccumError(pAccum, STRACCUM_NOMEM);
687d164fd34Sdrh             return;
688d164fd34Sdrh           }
689a18c5681Sdrh         }else{
690a18c5681Sdrh           bufpt = buf;
691a18c5681Sdrh         }
6920cfcf3fbSchw         j = 0;
693f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
6948965b50eSdrh         k = i;
6958965b50eSdrh         for(i=0; i<k; i++){
6968965b50eSdrh           bufpt[j++] = ch = escarg[i];
697f3b863edSdanielk1977           if( ch==q ) bufpt[j++] = ch;
698a18c5681Sdrh         }
699f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
700a18c5681Sdrh         bufpt[j] = 0;
701a18c5681Sdrh         length = j;
7028965b50eSdrh         /* The precision in %q and %Q means how many input characters to
7038965b50eSdrh         ** consume, not the length of the output...
7048965b50eSdrh         ** if( precision>=0 && precision<length ) length = precision; */
705a18c5681Sdrh         break;
7065eba8c09Sdrh       }
7075f968436Sdrh       case etTOKEN: {
7088236f688Sdrh         Token *pToken;
7098236f688Sdrh         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
7108236f688Sdrh         pToken = va_arg(ap, Token*);
711a5c1416dSdrh         assert( bArgList==0 );
712a9ab481fSdrh         if( pToken && pToken->n ){
713ade86483Sdrh           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
714ad6d9460Sdrh         }
7155f968436Sdrh         length = width = 0;
7165f968436Sdrh         break;
7175f968436Sdrh       }
7185f968436Sdrh       case etSRCLIST: {
7198236f688Sdrh         SrcList *pSrc;
7208236f688Sdrh         int k;
7218236f688Sdrh         struct SrcList_item *pItem;
7228236f688Sdrh         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
7238236f688Sdrh         pSrc = va_arg(ap, SrcList*);
7248236f688Sdrh         k = va_arg(ap, int);
7258236f688Sdrh         pItem = &pSrc->a[k];
726a5c1416dSdrh         assert( bArgList==0 );
7275f968436Sdrh         assert( k>=0 && k<pSrc->nSrc );
72893a960a0Sdrh         if( pItem->zDatabase ){
729a6353a3fSdrh           sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
730ade86483Sdrh           sqlite3StrAccumAppend(pAccum, ".", 1);
7315f968436Sdrh         }
732a6353a3fSdrh         sqlite3StrAccumAppendAll(pAccum, pItem->zName);
7335f968436Sdrh         length = width = 0;
7345f968436Sdrh         break;
7355f968436Sdrh       }
736874ba04cSdrh       default: {
737874ba04cSdrh         assert( xtype==etINVALID );
738874ba04cSdrh         return;
739874ba04cSdrh       }
740a18c5681Sdrh     }/* End switch over the format type */
741a18c5681Sdrh     /*
742a18c5681Sdrh     ** The text of the conversion is pointed to by "bufpt" and is
743a18c5681Sdrh     ** "length" characters long.  The field width is "width".  Do
744a18c5681Sdrh     ** the output.
745a18c5681Sdrh     */
746a70a073bSdrh     width -= length;
7478236f688Sdrh     if( width>0 ){
7488236f688Sdrh       if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
749ade86483Sdrh       sqlite3StrAccumAppend(pAccum, bufpt, length);
7508236f688Sdrh       if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
7518236f688Sdrh     }else{
7528236f688Sdrh       sqlite3StrAccumAppend(pAccum, bufpt, length);
7538236f688Sdrh     }
754a70a073bSdrh 
755af8f513fSdrh     if( zExtra ){
75696ceaf86Sdrh       sqlite3DbFree(pAccum->db, zExtra);
757af8f513fSdrh       zExtra = 0;
758af8f513fSdrh     }
759a18c5681Sdrh   }/* End for loop over the format string */
760a18c5681Sdrh } /* End of function */
761a18c5681Sdrh 
762a18c5681Sdrh /*
763a70a073bSdrh ** Enlarge the memory allocation on a StrAccum object so that it is
764a70a073bSdrh ** able to accept at least N more bytes of text.
765a70a073bSdrh **
766a70a073bSdrh ** Return the number of bytes of text that StrAccum is able to accept
767a70a073bSdrh ** after the attempted enlargement.  The value returned might be zero.
768a18c5681Sdrh */
769a70a073bSdrh static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
770a6353a3fSdrh   char *zNew;
771a30d22a7Sdrh   assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
772b49bc86aSdrh   if( p->accError ){
773b49bc86aSdrh     testcase(p->accError==STRACCUM_TOOBIG);
774b49bc86aSdrh     testcase(p->accError==STRACCUM_NOMEM);
775a70a073bSdrh     return 0;
776ade86483Sdrh   }
777c0490572Sdrh   if( p->mxAlloc==0 ){
778ade86483Sdrh     N = p->nAlloc - p->nChar - 1;
779a6353a3fSdrh     setStrAccumError(p, STRACCUM_TOOBIG);
780a70a073bSdrh     return N;
781a18c5681Sdrh   }else{
7825f4a686fSdrh     char *zOld = isMalloced(p) ? p->zText : 0;
78393a960a0Sdrh     i64 szNew = p->nChar;
7845f4a686fSdrh     assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
785b1a6c3c1Sdrh     szNew += N + 1;
7867b4d780bSdrh     if( szNew+p->nChar<=p->mxAlloc ){
7877b4d780bSdrh       /* Force exponential buffer size growth as long as it does not overflow,
7887b4d780bSdrh       ** to avoid having to call this routine too often */
7897b4d780bSdrh       szNew += p->nChar;
7907b4d780bSdrh     }
791b1a6c3c1Sdrh     if( szNew > p->mxAlloc ){
792ade86483Sdrh       sqlite3StrAccumReset(p);
793a6353a3fSdrh       setStrAccumError(p, STRACCUM_TOOBIG);
794a70a073bSdrh       return 0;
795b1a6c3c1Sdrh     }else{
796ea678832Sdrh       p->nAlloc = (int)szNew;
797a18c5681Sdrh     }
798c0490572Sdrh     if( p->db ){
799a9ef7097Sdan       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
800b975598eSdrh     }else{
801f3cdcdccSdrh       zNew = sqlite3_realloc64(zOld, p->nAlloc);
802b975598eSdrh     }
80353f733c7Sdrh     if( zNew ){
8047ef4d1c4Sdrh       assert( p->zText!=0 || p->nChar==0 );
8055f4a686fSdrh       if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
806ade86483Sdrh       p->zText = zNew;
8077f5a7ecdSdrh       p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
8085f4a686fSdrh       p->printfFlags |= SQLITE_PRINTF_MALLOCED;
809ade86483Sdrh     }else{
810ade86483Sdrh       sqlite3StrAccumReset(p);
811a6353a3fSdrh       setStrAccumError(p, STRACCUM_NOMEM);
812a70a073bSdrh       return 0;
813a70a073bSdrh     }
814a70a073bSdrh   }
815a70a073bSdrh   return N;
816a70a073bSdrh }
817a70a073bSdrh 
818a70a073bSdrh /*
819af8f513fSdrh ** Append N copies of character c to the given string buffer.
820a70a073bSdrh */
821af8f513fSdrh void sqlite3AppendChar(StrAccum *p, int N, char c){
822a30d22a7Sdrh   testcase( p->nChar + (i64)N > 0x7fffffff );
823a30d22a7Sdrh   if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
824a30d22a7Sdrh     return;
825a30d22a7Sdrh   }
8265f4a686fSdrh   assert( (p->zText==p->zBase)==!isMalloced(p) );
827af8f513fSdrh   while( (N--)>0 ) p->zText[p->nChar++] = c;
828a70a073bSdrh }
829a70a073bSdrh 
830a70a073bSdrh /*
831a70a073bSdrh ** The StrAccum "p" is not large enough to accept N new bytes of z[].
832a70a073bSdrh ** So enlarge if first, then do the append.
833a70a073bSdrh **
834a70a073bSdrh ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
835a70a073bSdrh ** work (enlarging the buffer) using tail recursion, so that the
836a70a073bSdrh ** sqlite3StrAccumAppend() routine can use fast calling semantics.
837a70a073bSdrh */
838172087fbSdrh static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
839a70a073bSdrh   N = sqlite3StrAccumEnlarge(p, N);
840a70a073bSdrh   if( N>0 ){
841a70a073bSdrh     memcpy(&p->zText[p->nChar], z, N);
842a70a073bSdrh     p->nChar += N;
843a70a073bSdrh   }
8445f4a686fSdrh   assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
845a70a073bSdrh }
846a70a073bSdrh 
847a70a073bSdrh /*
848a70a073bSdrh ** Append N bytes of text from z to the StrAccum object.  Increase the
849a70a073bSdrh ** size of the memory allocation for StrAccum if necessary.
850a70a073bSdrh */
851a70a073bSdrh void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
8523457338cSdrh   assert( z!=0 || N==0 );
853a70a073bSdrh   assert( p->zText!=0 || p->nChar==0 || p->accError );
854a70a073bSdrh   assert( N>=0 );
855a70a073bSdrh   assert( p->accError==0 || p->nAlloc==0 );
856a70a073bSdrh   if( p->nChar+N >= p->nAlloc ){
857a70a073bSdrh     enlargeAndAppend(p,z,N);
858895decf6Sdan   }else if( N ){
859b07028f7Sdrh     assert( p->zText );
860ade86483Sdrh     p->nChar += N;
861172087fbSdrh     memcpy(&p->zText[p->nChar-N], z, N);
862172087fbSdrh   }
863483750baSdrh }
864483750baSdrh 
865483750baSdrh /*
866a6353a3fSdrh ** Append the complete text of zero-terminated string z[] to the p string.
867a6353a3fSdrh */
868a6353a3fSdrh void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
86953cd9646Smistachkin   sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
870a6353a3fSdrh }
871a6353a3fSdrh 
872a6353a3fSdrh 
873a6353a3fSdrh /*
874ade86483Sdrh ** Finish off a string by making sure it is zero-terminated.
875ade86483Sdrh ** Return a pointer to the resulting string.  Return a NULL
876ade86483Sdrh ** pointer if any kind of error was encountered.
8775f968436Sdrh */
878043e586eSdrh static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
879043e586eSdrh   assert( p->mxAlloc>0 && !isMalloced(p) );
880633e6d57Sdrh   p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
881ade86483Sdrh   if( p->zText ){
882ade86483Sdrh     memcpy(p->zText, p->zBase, p->nChar+1);
8835f4a686fSdrh     p->printfFlags |= SQLITE_PRINTF_MALLOCED;
884ade86483Sdrh   }else{
885a6353a3fSdrh     setStrAccumError(p, STRACCUM_NOMEM);
886ade86483Sdrh   }
887043e586eSdrh   return p->zText;
888043e586eSdrh }
889043e586eSdrh char *sqlite3StrAccumFinish(StrAccum *p){
890043e586eSdrh   if( p->zText ){
891043e586eSdrh     assert( (p->zText==p->zBase)==!isMalloced(p) );
892043e586eSdrh     p->zText[p->nChar] = 0;
893043e586eSdrh     if( p->mxAlloc>0 && !isMalloced(p) ){
894043e586eSdrh       return strAccumFinishRealloc(p);
895ade86483Sdrh     }
896ade86483Sdrh   }
897ade86483Sdrh   return p->zText;
898ade86483Sdrh }
899ade86483Sdrh 
900ade86483Sdrh /*
901ade86483Sdrh ** Reset an StrAccum string.  Reclaim all malloced memory.
902ade86483Sdrh */
903ade86483Sdrh void sqlite3StrAccumReset(StrAccum *p){
9045f4a686fSdrh   assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
9055f4a686fSdrh   if( isMalloced(p) ){
906633e6d57Sdrh     sqlite3DbFree(p->db, p->zText);
9075f4a686fSdrh     p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
908ade86483Sdrh   }
909f089aa45Sdrh   p->zText = 0;
910ade86483Sdrh }
911ade86483Sdrh 
912ade86483Sdrh /*
913c0490572Sdrh ** Initialize a string accumulator.
914c0490572Sdrh **
915c0490572Sdrh ** p:     The accumulator to be initialized.
916c0490572Sdrh ** db:    Pointer to a database connection.  May be NULL.  Lookaside
917c0490572Sdrh **        memory is used if not NULL. db->mallocFailed is set appropriately
918c0490572Sdrh **        when not NULL.
919c0490572Sdrh ** zBase: An initial buffer.  May be NULL in which case the initial buffer
920c0490572Sdrh **        is malloced.
921c0490572Sdrh ** n:     Size of zBase in bytes.  If total space requirements never exceed
922c0490572Sdrh **        n then no memory allocations ever occur.
923c0490572Sdrh ** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
924c0490572Sdrh **        allocations will ever occur.
925ade86483Sdrh */
926c0490572Sdrh void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
927ade86483Sdrh   p->zText = p->zBase = zBase;
928c0490572Sdrh   p->db = db;
929ade86483Sdrh   p->nChar = 0;
930ade86483Sdrh   p->nAlloc = n;
931bb4957f8Sdrh   p->mxAlloc = mx;
932b49bc86aSdrh   p->accError = 0;
9335f4a686fSdrh   p->printfFlags = 0;
9345f968436Sdrh }
9355f968436Sdrh 
9365f968436Sdrh /*
9375f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
9385f968436Sdrh ** %-conversion extensions.
9395f968436Sdrh */
94017435752Sdrh char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
94117435752Sdrh   char *z;
94279158e18Sdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
943ade86483Sdrh   StrAccum acc;
944bc6160b0Sdrh   assert( db!=0 );
945c0490572Sdrh   sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
946bc6160b0Sdrh                       db->aLimit[SQLITE_LIMIT_LENGTH]);
9475f4a686fSdrh   acc.printfFlags = SQLITE_PRINTF_INTERNAL;
9485f4a686fSdrh   sqlite3VXPrintf(&acc, zFormat, ap);
949ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
950b49bc86aSdrh   if( acc.accError==STRACCUM_NOMEM ){
9514a642b60Sdrh     sqlite3OomFault(db);
95217435752Sdrh   }
95317435752Sdrh   return z;
9545f968436Sdrh }
9555f968436Sdrh 
9565f968436Sdrh /*
9575f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
9585f968436Sdrh ** %-conversion extensions.
9595f968436Sdrh */
96017435752Sdrh char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
9615f968436Sdrh   va_list ap;
9625f968436Sdrh   char *z;
9635f968436Sdrh   va_start(ap, zFormat);
964ade86483Sdrh   z = sqlite3VMPrintf(db, zFormat, ap);
9655f968436Sdrh   va_end(ap);
9665f968436Sdrh   return z;
9675f968436Sdrh }
9685f968436Sdrh 
9695f968436Sdrh /*
97028dd479cSdrh ** Print into memory obtained from sqlite3_malloc().  Omit the internal
97128dd479cSdrh ** %-conversion extensions.
97228dd479cSdrh */
97328dd479cSdrh char *sqlite3_vmprintf(const char *zFormat, va_list ap){
974ade86483Sdrh   char *z;
97528dd479cSdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
976ade86483Sdrh   StrAccum acc;
9779ca95730Sdrh 
9789ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
9799ca95730Sdrh   if( zFormat==0 ){
9809ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
9819ca95730Sdrh     return 0;
9829ca95730Sdrh   }
9839ca95730Sdrh #endif
984ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
985ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
986ff1590eeSdrh #endif
987c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
9885f4a686fSdrh   sqlite3VXPrintf(&acc, zFormat, ap);
989ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
990ade86483Sdrh   return z;
99128dd479cSdrh }
99228dd479cSdrh 
99328dd479cSdrh /*
99428dd479cSdrh ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
99528dd479cSdrh ** %-conversion extensions.
996483750baSdrh */
9976f8a503dSdanielk1977 char *sqlite3_mprintf(const char *zFormat, ...){
998a18c5681Sdrh   va_list ap;
9995f968436Sdrh   char *z;
1000ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
1001ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
1002ff1590eeSdrh #endif
1003a18c5681Sdrh   va_start(ap, zFormat);
1004b3738b6cSdrh   z = sqlite3_vmprintf(zFormat, ap);
1005a18c5681Sdrh   va_end(ap);
10065f968436Sdrh   return z;
1007a18c5681Sdrh }
1008a18c5681Sdrh 
1009a18c5681Sdrh /*
10106f8a503dSdanielk1977 ** sqlite3_snprintf() works like snprintf() except that it ignores the
101193a5c6bdSdrh ** current locale settings.  This is important for SQLite because we
101293a5c6bdSdrh ** are not able to use a "," as the decimal point in place of "." as
101393a5c6bdSdrh ** specified by some locales.
1014db26d4c9Sdrh **
1015db26d4c9Sdrh ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
1016db26d4c9Sdrh ** from the snprintf() standard.  Unfortunately, it is too late to change
1017db26d4c9Sdrh ** this without breaking compatibility, so we just have to live with the
1018db26d4c9Sdrh ** mistake.
1019db26d4c9Sdrh **
1020db26d4c9Sdrh ** sqlite3_vsnprintf() is the varargs version.
102193a5c6bdSdrh */
1022db26d4c9Sdrh char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
1023db26d4c9Sdrh   StrAccum acc;
1024db26d4c9Sdrh   if( n<=0 ) return zBuf;
10259ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
10269ca95730Sdrh   if( zBuf==0 || zFormat==0 ) {
10279ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
102896c707a3Sdrh     if( zBuf ) zBuf[0] = 0;
10299ca95730Sdrh     return zBuf;
10309ca95730Sdrh   }
10319ca95730Sdrh #endif
1032c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
10335f4a686fSdrh   sqlite3VXPrintf(&acc, zFormat, ap);
1034e9bb5660Sdrh   zBuf[acc.nChar] = 0;
1035e9bb5660Sdrh   return zBuf;
1036db26d4c9Sdrh }
10376f8a503dSdanielk1977 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
10385f968436Sdrh   char *z;
103993a5c6bdSdrh   va_list ap;
104093a5c6bdSdrh   va_start(ap,zFormat);
1041db26d4c9Sdrh   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
104293a5c6bdSdrh   va_end(ap);
10435f968436Sdrh   return z;
104493a5c6bdSdrh }
104593a5c6bdSdrh 
10463f280701Sdrh /*
10477c0c460fSdrh ** This is the routine that actually formats the sqlite3_log() message.
10487c0c460fSdrh ** We house it in a separate routine from sqlite3_log() to avoid using
10497c0c460fSdrh ** stack space on small-stack systems when logging is disabled.
10507c0c460fSdrh **
10517c0c460fSdrh ** sqlite3_log() must render into a static buffer.  It cannot dynamically
10527c0c460fSdrh ** allocate memory because it might be called while the memory allocator
10537c0c460fSdrh ** mutex is held.
1054a8dbd52aSdrh **
1055a8dbd52aSdrh ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
1056a8dbd52aSdrh ** certain format characters (%q) or for very large precisions or widths.
1057a8dbd52aSdrh ** Care must be taken that any sqlite3_log() calls that occur while the
1058a8dbd52aSdrh ** memory mutex is held do not use these mechanisms.
10597c0c460fSdrh */
10607c0c460fSdrh static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
10617c0c460fSdrh   StrAccum acc;                          /* String accumulator */
1062a64fa912Sdrh   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
10637c0c460fSdrh 
1064c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
10655f4a686fSdrh   sqlite3VXPrintf(&acc, zFormat, ap);
10667c0c460fSdrh   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
10677c0c460fSdrh                            sqlite3StrAccumFinish(&acc));
10687c0c460fSdrh }
10697c0c460fSdrh 
10707c0c460fSdrh /*
10713f280701Sdrh ** Format and write a message to the log if logging is enabled.
10723f280701Sdrh */
1073a7564663Sdrh void sqlite3_log(int iErrCode, const char *zFormat, ...){
10743f280701Sdrh   va_list ap;                             /* Vararg list */
10757c0c460fSdrh   if( sqlite3GlobalConfig.xLog ){
10763f280701Sdrh     va_start(ap, zFormat);
10777c0c460fSdrh     renderLogMsg(iErrCode, zFormat, ap);
10783f280701Sdrh     va_end(ap);
10793f280701Sdrh   }
10803f280701Sdrh }
10813f280701Sdrh 
108202b0e267Smistachkin #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
1083e54ca3feSdrh /*
1084e54ca3feSdrh ** A version of printf() that understands %lld.  Used for debugging.
1085e54ca3feSdrh ** The printf() built into some versions of windows does not understand %lld
1086e54ca3feSdrh ** and segfaults if you give it a long long int.
1087e54ca3feSdrh */
1088e54ca3feSdrh void sqlite3DebugPrintf(const char *zFormat, ...){
1089e54ca3feSdrh   va_list ap;
1090ade86483Sdrh   StrAccum acc;
1091e54ca3feSdrh   char zBuf[500];
1092c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
1093e54ca3feSdrh   va_start(ap,zFormat);
10945f4a686fSdrh   sqlite3VXPrintf(&acc, zFormat, ap);
1095e54ca3feSdrh   va_end(ap);
1096bed8e7e5Sdrh   sqlite3StrAccumFinish(&acc);
1097485f0039Sdrh   fprintf(stdout,"%s", zBuf);
10982ac3ee97Sdrh   fflush(stdout);
1099e54ca3feSdrh }
1100e54ca3feSdrh #endif
1101c7bc4fdeSdrh 
11024fa4a54fSdrh 
1103c7bc4fdeSdrh /*
1104d37bea5bSdrh ** variable-argument wrapper around sqlite3VXPrintf().  The bFlags argument
1105d37bea5bSdrh ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
1106c7bc4fdeSdrh */
11075f4a686fSdrh void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
1108c7bc4fdeSdrh   va_list ap;
1109c7bc4fdeSdrh   va_start(ap,zFormat);
11105f4a686fSdrh   sqlite3VXPrintf(p, zFormat, ap);
1111c7bc4fdeSdrh   va_end(ap);
1112c7bc4fdeSdrh }
1113