printf.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. /*
  2. ** The "printf" code that follows dates from the 1980's. It is in
  3. ** the public domain. The original comments are included here for
  4. ** completeness. They are very out-of-date but might be useful as
  5. ** an historical reference. Most of the "enhancements" have been backed
  6. ** out so that the functionality is now the same as standard printf().
  7. **
  8. **************************************************************************
  9. **
  10. ** This file contains code for a set of "printf"-like routines. These
  11. ** routines format strings much like the printf() from the standard C
  12. ** library, though the implementation here has enhancements to support
  13. ** SQLlite.
  14. */
  15. #include "sqliteInt.h"
  16. /*
  17. ** Conversion types fall into various categories as defined by the
  18. ** following enumeration.
  19. */
  20. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  21. #define etFLOAT 2 /* Floating point. %f */
  22. #define etEXP 3 /* Exponentional notation. %e and %E */
  23. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  24. #define etSIZE 5 /* Return number of characters processed so far. %n */
  25. #define etSTRING 6 /* Strings. %s */
  26. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  27. #define etPERCENT 8 /* Percent symbol. %% */
  28. #define etCHARX 9 /* Characters. %c */
  29. /* The rest are extensions, not normally found in printf() */
  30. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  31. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  32. NULL pointers replaced by SQL NULL. %Q */
  33. #define etTOKEN 12 /* a pointer to a Token structure */
  34. #define etSRCLIST 13 /* a pointer to a SrcList */
  35. #define etPOINTER 14 /* The %p conversion */
  36. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  37. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  38. #define etINVALID 0 /* Any unrecognized conversion type */
  39. /*
  40. ** An "etByte" is an 8-bit unsigned value.
  41. */
  42. typedef unsigned char etByte;
  43. /*
  44. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  45. ** by an instance of the following structure
  46. */
  47. typedef struct et_info { /* Information about each format field */
  48. char fmttype; /* The format field code letter */
  49. etByte base; /* The base for radix conversion */
  50. etByte flags; /* One or more of FLAG_ constants below */
  51. etByte type; /* Conversion paradigm */
  52. etByte charset; /* Offset into aDigits[] of the digits string */
  53. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  54. } et_info;
  55. /*
  56. ** Allowed values for et_info.flags
  57. */
  58. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  59. #define FLAG_INTERN 2 /* True if for internal use only */
  60. #define FLAG_STRING 4 /* Allow infinity precision */
  61. /*
  62. ** The following table is searched linearly, so it is good to put the
  63. ** most frequently used conversion types first.
  64. */
  65. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  66. static const char aPrefix[] = "-x0\000X0";
  67. static const et_info fmtinfo[] = {
  68. { 'd', 10, 1, etRADIX, 0, 0 },
  69. { 's', 0, 4, etSTRING, 0, 0 },
  70. { 'g', 0, 1, etGENERIC, 30, 0 },
  71. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  72. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  73. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  74. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  75. { 'c', 0, 0, etCHARX, 0, 0 },
  76. { 'o', 8, 0, etRADIX, 0, 2 },
  77. { 'u', 10, 0, etRADIX, 0, 0 },
  78. { 'x', 16, 0, etRADIX, 16, 1 },
  79. { 'X', 16, 0, etRADIX, 0, 4 },
  80. #ifndef SQLITE_OMIT_FLOATING_POINT
  81. { 'f', 0, 1, etFLOAT, 0, 0 },
  82. { 'e', 0, 1, etEXP, 30, 0 },
  83. { 'E', 0, 1, etEXP, 14, 0 },
  84. { 'G', 0, 1, etGENERIC, 14, 0 },
  85. #endif
  86. { 'i', 10, 1, etRADIX, 0, 0 },
  87. { 'n', 0, 0, etSIZE, 0, 0 },
  88. { '%', 0, 0, etPERCENT, 0, 0 },
  89. { 'p', 16, 0, etPOINTER, 0, 1 },
  90. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  91. ** use only */
  92. { 'T', 0, 2, etTOKEN, 0, 0 },
  93. { 'S', 0, 2, etSRCLIST, 0, 0 },
  94. { 'r', 10, 3, etORDINAL, 0, 0 },
  95. };
  96. /*
  97. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  98. ** conversions will work.
  99. */
  100. #ifndef SQLITE_OMIT_FLOATING_POINT
  101. /*
  102. ** "*val" is a double such that 0.1 <= *val < 10.0
  103. ** Return the ascii code for the leading digit of *val, then
  104. ** multiply "*val" by 10.0 to renormalize.
  105. **
  106. ** Example:
  107. ** input: *val = 3.14159
  108. ** output: *val = 1.4159 function return = '3'
  109. **
  110. ** The counter *cnt is incremented each time. After counter exceeds
  111. ** 16 (the number of significant digits in a 64-bit float) '0' is
  112. ** always returned.
  113. */
  114. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  115. int digit;
  116. LONGDOUBLE_TYPE d;
  117. if( (*cnt)<=0 ) return '0';
  118. (*cnt)--;
  119. digit = (int)*val;
  120. d = digit;
  121. digit += '0';
  122. *val = (*val - d)*10.0;
  123. return (char)digit;
  124. }
  125. #endif /* SQLITE_OMIT_FLOATING_POINT */
  126. /*
  127. ** Append N space characters to the given string buffer.
  128. */
  129. void sqlite3AppendSpace(StrAccum *pAccum, int N){
  130. static const char zSpaces[] = " ";
  131. while( N>=(int)sizeof(zSpaces)-1 ){
  132. sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
  133. N -= sizeof(zSpaces)-1;
  134. }
  135. if( N>0 ){
  136. sqlite3StrAccumAppend(pAccum, zSpaces, N);
  137. }
  138. }
  139. /*
  140. ** On machines with a small stack size, you can redefine the
  141. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  142. */
  143. #ifndef SQLITE_PRINT_BUF_SIZE
  144. # define SQLITE_PRINT_BUF_SIZE 70
  145. #endif
  146. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  147. /*
  148. ** Render a string given by "fmt" into the StrAccum object.
  149. */
  150. void sqlite3VXPrintf(
  151. StrAccum *pAccum, /* Accumulate results here */
  152. int useExtended, /* Allow extended %-conversions */
  153. const char *fmt, /* Format string */
  154. va_list ap /* arguments */
  155. ){
  156. int c; /* Next character in the format string */
  157. char *bufpt; /* Pointer to the conversion buffer */
  158. int precision; /* Precision of the current field */
  159. int length; /* Length of the field */
  160. int idx; /* A general purpose loop counter */
  161. int width; /* Width of the current field */
  162. etByte flag_leftjustify; /* True if "-" flag is present */
  163. etByte flag_plussign; /* True if "+" flag is present */
  164. etByte flag_blanksign; /* True if " " flag is present */
  165. etByte flag_alternateform; /* True if "#" flag is present */
  166. etByte flag_altform2; /* True if "!" flag is present */
  167. etByte flag_zeropad; /* True if field width constant starts with zero */
  168. etByte flag_long; /* True if "l" flag is present */
  169. etByte flag_longlong; /* True if the "ll" flag is present */
  170. etByte done; /* Loop termination flag */
  171. etByte xtype = 0; /* Conversion paradigm */
  172. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  173. sqlite_uint64 longvalue; /* Value for integer types */
  174. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  175. const et_info *infop; /* Pointer to the appropriate info structure */
  176. char *zOut; /* Rendering buffer */
  177. int nOut; /* Size of the rendering buffer */
  178. char *zExtra; /* Malloced memory used by some conversion */
  179. #ifndef SQLITE_OMIT_FLOATING_POINT
  180. int exp, e2; /* exponent of real numbers */
  181. int nsd; /* Number of significant digits returned */
  182. double rounder; /* Used for rounding floating point values */
  183. etByte flag_dp; /* True if decimal point should be shown */
  184. etByte flag_rtz; /* True if trailing zeros should be removed */
  185. #endif
  186. char buf[etBUFSIZE]; /* Conversion buffer */
  187. bufpt = 0;
  188. for(; (c=(*fmt))!=0; ++fmt){
  189. if( c!='%' ){
  190. int amt;
  191. bufpt = (char *)fmt;
  192. amt = 1;
  193. while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  194. sqlite3StrAccumAppend(pAccum, bufpt, amt);
  195. if( c==0 ) break;
  196. }
  197. if( (c=(*++fmt))==0 ){
  198. sqlite3StrAccumAppend(pAccum, "%", 1);
  199. break;
  200. }
  201. /* Find out what flags are present */
  202. flag_leftjustify = flag_plussign = flag_blanksign =
  203. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  204. done = 0;
  205. do{
  206. switch( c ){
  207. case '-': flag_leftjustify = 1; break;
  208. case '+': flag_plussign = 1; break;
  209. case ' ': flag_blanksign = 1; break;
  210. case '#': flag_alternateform = 1; break;
  211. case '!': flag_altform2 = 1; break;
  212. case '0': flag_zeropad = 1; break;
  213. default: done = 1; break;
  214. }
  215. }while( !done && (c=(*++fmt))!=0 );
  216. /* Get the field width */
  217. width = 0;
  218. if( c=='*' ){
  219. width = va_arg(ap,int);
  220. if( width<0 ){
  221. flag_leftjustify = 1;
  222. width = -width;
  223. }
  224. c = *++fmt;
  225. }else{
  226. while( c>='0' && c<='9' ){
  227. width = width*10 + c - '0';
  228. c = *++fmt;
  229. }
  230. }
  231. /* Get the precision */
  232. if( c=='.' ){
  233. precision = 0;
  234. c = *++fmt;
  235. if( c=='*' ){
  236. precision = va_arg(ap,int);
  237. if( precision<0 ) precision = -precision;
  238. c = *++fmt;
  239. }else{
  240. while( c>='0' && c<='9' ){
  241. precision = precision*10 + c - '0';
  242. c = *++fmt;
  243. }
  244. }
  245. }else{
  246. precision = -1;
  247. }
  248. /* Get the conversion type modifier */
  249. if( c=='l' ){
  250. flag_long = 1;
  251. c = *++fmt;
  252. if( c=='l' ){
  253. flag_longlong = 1;
  254. c = *++fmt;
  255. }else{
  256. flag_longlong = 0;
  257. }
  258. }else{
  259. flag_long = flag_longlong = 0;
  260. }
  261. /* Fetch the info entry for the field */
  262. infop = &fmtinfo[0];
  263. xtype = etINVALID;
  264. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  265. if( c==fmtinfo[idx].fmttype ){
  266. infop = &fmtinfo[idx];
  267. if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  268. xtype = infop->type;
  269. }else{
  270. return;
  271. }
  272. break;
  273. }
  274. }
  275. zExtra = 0;
  276. /*
  277. ** At this point, variables are initialized as follows:
  278. **
  279. ** flag_alternateform TRUE if a '#' is present.
  280. ** flag_altform2 TRUE if a '!' is present.
  281. ** flag_plussign TRUE if a '+' is present.
  282. ** flag_leftjustify TRUE if a '-' is present or if the
  283. ** field width was negative.
  284. ** flag_zeropad TRUE if the width began with 0.
  285. ** flag_long TRUE if the letter 'l' (ell) prefixed
  286. ** the conversion character.
  287. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  288. ** the conversion character.
  289. ** flag_blanksign TRUE if a ' ' is present.
  290. ** width The specified field width. This is
  291. ** always non-negative. Zero is the default.
  292. ** precision The specified precision. The default
  293. ** is -1.
  294. ** xtype The class of the conversion.
  295. ** infop Pointer to the appropriate info struct.
  296. */
  297. switch( xtype ){
  298. case etPOINTER:
  299. flag_longlong = sizeof(char*)==sizeof(i64);
  300. flag_long = sizeof(char*)==sizeof(long int);
  301. /* Fall through into the next case */
  302. case etORDINAL:
  303. case etRADIX:
  304. if( infop->flags & FLAG_SIGNED ){
  305. i64 v;
  306. if( flag_longlong ){
  307. v = va_arg(ap,i64);
  308. }else if( flag_long ){
  309. v = va_arg(ap,long int);
  310. }else{
  311. v = va_arg(ap,int);
  312. }
  313. if( v<0 ){
  314. if( v==SMALLEST_INT64 ){
  315. longvalue = ((u64)1)<<63;
  316. }else{
  317. longvalue = -v;
  318. }
  319. prefix = '-';
  320. }else{
  321. longvalue = v;
  322. if( flag_plussign ) prefix = '+';
  323. else if( flag_blanksign ) prefix = ' ';
  324. else prefix = 0;
  325. }
  326. }else{
  327. if( flag_longlong ){
  328. longvalue = va_arg(ap,u64);
  329. }else if( flag_long ){
  330. longvalue = va_arg(ap,unsigned long int);
  331. }else{
  332. longvalue = va_arg(ap,unsigned int);
  333. }
  334. prefix = 0;
  335. }
  336. if( longvalue==0 ) flag_alternateform = 0;
  337. if( flag_zeropad && precision<width-(prefix!=0) ){
  338. precision = width-(prefix!=0);
  339. }
  340. if( precision<etBUFSIZE-10 ){
  341. nOut = etBUFSIZE;
  342. zOut = buf;
  343. }else{
  344. nOut = precision + 10;
  345. zOut = zExtra = sqlite3Malloc( nOut );
  346. if( zOut==0 ){
  347. pAccum->accError = STRACCUM_NOMEM;
  348. return;
  349. }
  350. }
  351. bufpt = &zOut[nOut-1];
  352. if( xtype==etORDINAL ){
  353. static const char zOrd[] = "thstndrd";
  354. int x = (int)(longvalue % 10);
  355. if( x>=4 || (longvalue/10)%10==1 ){
  356. x = 0;
  357. }
  358. *(--bufpt) = zOrd[x*2+1];
  359. *(--bufpt) = zOrd[x*2];
  360. }
  361. {
  362. register const char *cset; /* Use registers for speed */
  363. register int base;
  364. cset = &aDigits[infop->charset];
  365. base = infop->base;
  366. do{ /* Convert to ascii */
  367. *(--bufpt) = cset[longvalue%base];
  368. longvalue = longvalue/base;
  369. }while( longvalue>0 );
  370. }
  371. length = (int)(&zOut[nOut-1]-bufpt);
  372. for(idx=precision-length; idx>0; idx--){
  373. *(--bufpt) = '0'; /* Zero pad */
  374. }
  375. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  376. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  377. const char *pre;
  378. char x;
  379. pre = &aPrefix[infop->prefix];
  380. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  381. }
  382. length = (int)(&zOut[nOut-1]-bufpt);
  383. break;
  384. case etFLOAT:
  385. case etEXP:
  386. case etGENERIC:
  387. realvalue = va_arg(ap,double);
  388. #ifdef SQLITE_OMIT_FLOATING_POINT
  389. length = 0;
  390. #else
  391. if( precision<0 ) precision = 6; /* Set default precision */
  392. if( realvalue<0.0 ){
  393. realvalue = -realvalue;
  394. prefix = '-';
  395. }else{
  396. if( flag_plussign ) prefix = '+';
  397. else if( flag_blanksign ) prefix = ' ';
  398. else prefix = 0;
  399. }
  400. if( xtype==etGENERIC && precision>0 ) precision--;
  401. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  402. if( xtype==etFLOAT ) realvalue += rounder;
  403. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  404. exp = 0;
  405. if( sqlite3IsNaN((double)realvalue) ){
  406. bufpt = "NaN";
  407. length = 3;
  408. break;
  409. }
  410. if( realvalue>0.0 ){
  411. LONGDOUBLE_TYPE scale = 1.0;
  412. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  413. while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
  414. while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
  415. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  416. realvalue /= scale;
  417. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  418. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  419. if( exp>350 ){
  420. if( prefix=='-' ){
  421. bufpt = "-Inf";
  422. }else if( prefix=='+' ){
  423. bufpt = "+Inf";
  424. }else{
  425. bufpt = "Inf";
  426. }
  427. length = sqlite3Strlen30(bufpt);
  428. break;
  429. }
  430. }
  431. bufpt = buf;
  432. /*
  433. ** If the field type is etGENERIC, then convert to either etEXP
  434. ** or etFLOAT, as appropriate.
  435. */
  436. if( xtype!=etFLOAT ){
  437. realvalue += rounder;
  438. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  439. }
  440. if( xtype==etGENERIC ){
  441. flag_rtz = !flag_alternateform;
  442. if( exp<-4 || exp>precision ){
  443. xtype = etEXP;
  444. }else{
  445. precision = precision - exp;
  446. xtype = etFLOAT;
  447. }
  448. }else{
  449. flag_rtz = flag_altform2;
  450. }
  451. if( xtype==etEXP ){
  452. e2 = 0;
  453. }else{
  454. e2 = exp;
  455. }
  456. if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
  457. bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
  458. if( bufpt==0 ){
  459. pAccum->accError = STRACCUM_NOMEM;
  460. return;
  461. }
  462. }
  463. zOut = bufpt;
  464. nsd = 16 + flag_altform2*10;
  465. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  466. /* The sign in front of the number */
  467. if( prefix ){
  468. *(bufpt++) = prefix;
  469. }
  470. /* Digits prior to the decimal point */
  471. if( e2<0 ){
  472. *(bufpt++) = '0';
  473. }else{
  474. for(; e2>=0; e2--){
  475. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  476. }
  477. }
  478. /* The decimal point */
  479. if( flag_dp ){
  480. *(bufpt++) = '.';
  481. }
  482. /* "0" digits after the decimal point but before the first
  483. ** significant digit of the number */
  484. for(e2++; e2<0; precision--, e2++){
  485. assert( precision>0 );
  486. *(bufpt++) = '0';
  487. }
  488. /* Significant digits after the decimal point */
  489. while( (precision--)>0 ){
  490. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  491. }
  492. /* Remove trailing zeros and the "." if no digits follow the "." */
  493. if( flag_rtz && flag_dp ){
  494. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  495. assert( bufpt>zOut );
  496. if( bufpt[-1]=='.' ){
  497. if( flag_altform2 ){
  498. *(bufpt++) = '0';
  499. }else{
  500. *(--bufpt) = 0;
  501. }
  502. }
  503. }
  504. /* Add the "eNNN" suffix */
  505. if( xtype==etEXP ){
  506. *(bufpt++) = aDigits[infop->charset];
  507. if( exp<0 ){
  508. *(bufpt++) = '-'; exp = -exp;
  509. }else{
  510. *(bufpt++) = '+';
  511. }
  512. if( exp>=100 ){
  513. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  514. exp %= 100;
  515. }
  516. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  517. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  518. }
  519. *bufpt = 0;
  520. /* The converted number is in buf[] and zero terminated. Output it.
  521. ** Note that the number is in the usual order, not reversed as with
  522. ** integer conversions. */
  523. length = (int)(bufpt-zOut);
  524. bufpt = zOut;
  525. /* Special case: Add leading zeros if the flag_zeropad flag is
  526. ** set and we are not left justified */
  527. if( flag_zeropad && !flag_leftjustify && length < width){
  528. int i;
  529. int nPad = width - length;
  530. for(i=width; i>=nPad; i--){
  531. bufpt[i] = bufpt[i-nPad];
  532. }
  533. i = prefix!=0;
  534. while( nPad-- ) bufpt[i++] = '0';
  535. length = width;
  536. }
  537. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  538. break;
  539. case etSIZE:
  540. *(va_arg(ap,int*)) = pAccum->nChar;
  541. length = width = 0;
  542. break;
  543. case etPERCENT:
  544. buf[0] = '%';
  545. bufpt = buf;
  546. length = 1;
  547. break;
  548. case etCHARX:
  549. c = va_arg(ap,int);
  550. buf[0] = (char)c;
  551. if( precision>=0 ){
  552. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  553. length = precision;
  554. }else{
  555. length =1;
  556. }
  557. bufpt = buf;
  558. break;
  559. case etSTRING:
  560. case etDYNSTRING:
  561. bufpt = va_arg(ap,char*);
  562. if( bufpt==0 ){
  563. bufpt = "";
  564. }else if( xtype==etDYNSTRING ){
  565. zExtra = bufpt;
  566. }
  567. if( precision>=0 ){
  568. for(length=0; length<precision && bufpt[length]; length++){}
  569. }else{
  570. length = sqlite3Strlen30(bufpt);
  571. }
  572. break;
  573. case etSQLESCAPE:
  574. case etSQLESCAPE2:
  575. case etSQLESCAPE3: {
  576. int i, j, k, n, isnull;
  577. int needQuote;
  578. char ch;
  579. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  580. char *escarg = va_arg(ap,char*);
  581. isnull = escarg==0;
  582. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  583. k = precision;
  584. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  585. if( ch==q ) n++;
  586. }
  587. needQuote = !isnull && xtype==etSQLESCAPE2;
  588. n += i + 1 + needQuote*2;
  589. if( n>etBUFSIZE ){
  590. bufpt = zExtra = sqlite3Malloc( n );
  591. if( bufpt==0 ){
  592. pAccum->accError = STRACCUM_NOMEM;
  593. return;
  594. }
  595. }else{
  596. bufpt = buf;
  597. }
  598. j = 0;
  599. if( needQuote ) bufpt[j++] = q;
  600. k = i;
  601. for(i=0; i<k; i++){
  602. bufpt[j++] = ch = escarg[i];
  603. if( ch==q ) bufpt[j++] = ch;
  604. }
  605. if( needQuote ) bufpt[j++] = q;
  606. bufpt[j] = 0;
  607. length = j;
  608. /* The precision in %q and %Q means how many input characters to
  609. ** consume, not the length of the output...
  610. ** if( precision>=0 && precision<length ) length = precision; */
  611. break;
  612. }
  613. case etTOKEN: {
  614. Token *pToken = va_arg(ap, Token*);
  615. if( pToken ){
  616. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  617. }
  618. length = width = 0;
  619. break;
  620. }
  621. case etSRCLIST: {
  622. SrcList *pSrc = va_arg(ap, SrcList*);
  623. int k = va_arg(ap, int);
  624. struct SrcList_item *pItem = &pSrc->a[k];
  625. assert( k>=0 && k<pSrc->nSrc );
  626. if( pItem->zDatabase ){
  627. sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
  628. sqlite3StrAccumAppend(pAccum, ".", 1);
  629. }
  630. sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
  631. length = width = 0;
  632. break;
  633. }
  634. default: {
  635. assert( xtype==etINVALID );
  636. return;
  637. }
  638. }/* End switch over the format type */
  639. /*
  640. ** The text of the conversion is pointed to by "bufpt" and is
  641. ** "length" characters long. The field width is "width". Do
  642. ** the output.
  643. */
  644. if( !flag_leftjustify ){
  645. register int nspace;
  646. nspace = width-length;
  647. if( nspace>0 ){
  648. sqlite3AppendSpace(pAccum, nspace);
  649. }
  650. }
  651. if( length>0 ){
  652. sqlite3StrAccumAppend(pAccum, bufpt, length);
  653. }
  654. if( flag_leftjustify ){
  655. register int nspace;
  656. nspace = width-length;
  657. if( nspace>0 ){
  658. sqlite3AppendSpace(pAccum, nspace);
  659. }
  660. }
  661. sqlite3_free(zExtra);
  662. }/* End for loop over the format string */
  663. } /* End of function */
  664. /*
  665. ** Append N bytes of text from z to the StrAccum object.
  666. */
  667. void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  668. assert( z!=0 || N==0 );
  669. if( p->accError ){
  670. testcase(p->accError==STRACCUM_TOOBIG);
  671. testcase(p->accError==STRACCUM_NOMEM);
  672. return;
  673. }
  674. assert( p->zText!=0 || p->nChar==0 );
  675. if( N<=0 ){
  676. if( N==0 || z[0]==0 ) return;
  677. N = sqlite3Strlen30(z);
  678. }
  679. if( p->nChar+N >= p->nAlloc ){
  680. char *zNew;
  681. if( !p->useMalloc ){
  682. p->accError = STRACCUM_TOOBIG;
  683. N = p->nAlloc - p->nChar - 1;
  684. if( N<=0 ){
  685. return;
  686. }
  687. }else{
  688. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  689. i64 szNew = p->nChar;
  690. szNew += N + 1;
  691. if( szNew > p->mxAlloc ){
  692. sqlite3StrAccumReset(p);
  693. p->accError = STRACCUM_TOOBIG;
  694. return;
  695. }else{
  696. p->nAlloc = (int)szNew;
  697. }
  698. if( p->useMalloc==1 ){
  699. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  700. }else{
  701. zNew = sqlite3_realloc(zOld, p->nAlloc);
  702. }
  703. if( zNew ){
  704. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  705. p->zText = zNew;
  706. }else{
  707. p->accError = STRACCUM_NOMEM;
  708. sqlite3StrAccumReset(p);
  709. return;
  710. }
  711. }
  712. }
  713. assert( p->zText );
  714. memcpy(&p->zText[p->nChar], z, N);
  715. p->nChar += N;
  716. }
  717. /*
  718. ** Finish off a string by making sure it is zero-terminated.
  719. ** Return a pointer to the resulting string. Return a NULL
  720. ** pointer if any kind of error was encountered.
  721. */
  722. char *sqlite3StrAccumFinish(StrAccum *p){
  723. if( p->zText ){
  724. p->zText[p->nChar] = 0;
  725. if( p->useMalloc && p->zText==p->zBase ){
  726. if( p->useMalloc==1 ){
  727. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  728. }else{
  729. p->zText = sqlite3_malloc(p->nChar+1);
  730. }
  731. if( p->zText ){
  732. memcpy(p->zText, p->zBase, p->nChar+1);
  733. }else{
  734. p->accError = STRACCUM_NOMEM;
  735. }
  736. }
  737. }
  738. return p->zText;
  739. }
  740. /*
  741. ** Reset an StrAccum string. Reclaim all malloced memory.
  742. */
  743. void sqlite3StrAccumReset(StrAccum *p){
  744. if( p->zText!=p->zBase ){
  745. if( p->useMalloc==1 ){
  746. sqlite3DbFree(p->db, p->zText);
  747. }else{
  748. sqlite3_free(p->zText);
  749. }
  750. }
  751. p->zText = 0;
  752. }
  753. /*
  754. ** Initialize a string accumulator
  755. */
  756. void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  757. p->zText = p->zBase = zBase;
  758. p->db = 0;
  759. p->nChar = 0;
  760. p->nAlloc = n;
  761. p->mxAlloc = mx;
  762. p->useMalloc = 1;
  763. p->accError = 0;
  764. }
  765. /*
  766. ** Print into memory obtained from sqliteMalloc(). Use the internal
  767. ** %-conversion extensions.
  768. */
  769. char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  770. char *z;
  771. char zBase[SQLITE_PRINT_BUF_SIZE];
  772. StrAccum acc;
  773. assert( db!=0 );
  774. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  775. db->aLimit[SQLITE_LIMIT_LENGTH]);
  776. acc.db = db;
  777. sqlite3VXPrintf(&acc, 1, zFormat, ap);
  778. z = sqlite3StrAccumFinish(&acc);
  779. if( acc.accError==STRACCUM_NOMEM ){
  780. db->mallocFailed = 1;
  781. }
  782. return z;
  783. }
  784. /*
  785. ** Print into memory obtained from sqliteMalloc(). Use the internal
  786. ** %-conversion extensions.
  787. */
  788. char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  789. va_list ap;
  790. char *z;
  791. va_start(ap, zFormat);
  792. z = sqlite3VMPrintf(db, zFormat, ap);
  793. va_end(ap);
  794. return z;
  795. }
  796. /*
  797. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  798. ** the string and before returnning. This routine is intended to be used
  799. ** to modify an existing string. For example:
  800. **
  801. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  802. **
  803. */
  804. char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  805. va_list ap;
  806. char *z;
  807. va_start(ap, zFormat);
  808. z = sqlite3VMPrintf(db, zFormat, ap);
  809. va_end(ap);
  810. sqlite3DbFree(db, zStr);
  811. return z;
  812. }
  813. /*
  814. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  815. ** %-conversion extensions.
  816. */
  817. char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  818. char *z;
  819. char zBase[SQLITE_PRINT_BUF_SIZE];
  820. StrAccum acc;
  821. #ifndef SQLITE_OMIT_AUTOINIT
  822. if( sqlite3_initialize() ) return 0;
  823. #endif
  824. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  825. acc.useMalloc = 2;
  826. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  827. z = sqlite3StrAccumFinish(&acc);
  828. return z;
  829. }
  830. /*
  831. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  832. ** %-conversion extensions.
  833. */
  834. char *sqlite3_mprintf(const char *zFormat, ...){
  835. va_list ap;
  836. char *z;
  837. #ifndef SQLITE_OMIT_AUTOINIT
  838. if( sqlite3_initialize() ) return 0;
  839. #endif
  840. va_start(ap, zFormat);
  841. z = sqlite3_vmprintf(zFormat, ap);
  842. va_end(ap);
  843. return z;
  844. }
  845. /*
  846. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  847. ** current locale settings. This is important for SQLite because we
  848. ** are not able to use a "," as the decimal point in place of "." as
  849. ** specified by some locales.
  850. **
  851. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  852. ** from the snprintf() standard. Unfortunately, it is too late to change
  853. ** this without breaking compatibility, so we just have to live with the
  854. ** mistake.
  855. **
  856. ** sqlite3_vsnprintf() is the varargs version.
  857. */
  858. char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  859. StrAccum acc;
  860. if( n<=0 ) return zBuf;
  861. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  862. acc.useMalloc = 0;
  863. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  864. return sqlite3StrAccumFinish(&acc);
  865. }
  866. char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  867. char *z;
  868. va_list ap;
  869. va_start(ap,zFormat);
  870. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  871. va_end(ap);
  872. return z;
  873. }
  874. /*
  875. ** This is the routine that actually formats the sqlite3_log() message.
  876. ** We house it in a separate routine from sqlite3_log() to avoid using
  877. ** stack space on small-stack systems when logging is disabled.
  878. **
  879. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  880. ** allocate memory because it might be called while the memory allocator
  881. ** mutex is held.
  882. */
  883. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  884. StrAccum acc; /* String accumulator */
  885. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  886. sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  887. acc.useMalloc = 0;
  888. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  889. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  890. sqlite3StrAccumFinish(&acc));
  891. }
  892. /*
  893. ** Format and write a message to the log if logging is enabled.
  894. */
  895. void sqlite3_log(int iErrCode, const char *zFormat, ...){
  896. va_list ap; /* Vararg list */
  897. if( sqlite3GlobalConfig.xLog ){
  898. va_start(ap, zFormat);
  899. renderLogMsg(iErrCode, zFormat, ap);
  900. va_end(ap);
  901. }
  902. }
  903. #if defined(SQLITE_DEBUG)
  904. /*
  905. ** A version of printf() that understands %lld. Used for debugging.
  906. ** The printf() built into some versions of windows does not understand %lld
  907. ** and segfaults if you give it a long long int.
  908. */
  909. void sqlite3DebugPrintf(const char *zFormat, ...){
  910. va_list ap;
  911. StrAccum acc;
  912. char zBuf[500];
  913. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  914. acc.useMalloc = 0;
  915. va_start(ap,zFormat);
  916. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  917. va_end(ap);
  918. sqlite3StrAccumFinish(&acc);
  919. fprintf(stdout,"%s", zBuf);
  920. fflush(stdout);
  921. }
  922. #endif
  923. #ifndef SQLITE_OMIT_TRACE
  924. /*
  925. ** variable-argument wrapper around sqlite3VXPrintf().
  926. */
  927. void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  928. va_list ap;
  929. va_start(ap,zFormat);
  930. sqlite3VXPrintf(p, 1, zFormat, ap);
  931. va_end(ap);
  932. }
  933. #endif