new_printf.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // \author (c) Marco Paland (info@paland.com)
  3. // 2014-2019, PALANDesign Hannover, Germany
  4. //
  5. // \license The MIT License (MIT)
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. //
  25. // \brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on
  26. // embedded systems with a very limited resources. These routines are thread
  27. // safe and reentrant!
  28. // Use this instead of the bloated standard/newlib printf cause these use
  29. // malloc for printf (and may not be thread safe).
  30. //
  31. ///////////////////////////////////////////////////////////////////////////////
  32. #include <stdbool.h>
  33. #include <stdint.h>
  34. #include <stdio.h>
  35. #include "printf.h"
  36. // define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the
  37. // printf_config.h header file
  38. // default: undefined
  39. #ifdef PRINTF_INCLUDE_CONFIG_H
  40. #include "printf_config.h"
  41. #endif
  42. // 'ntoa' conversion buffer size, this must be big enough to hold one converted
  43. // numeric number including padded zeros (dynamically created on stack)
  44. // default: 32 byte
  45. #ifndef PRINTF_NTOA_BUFFER_SIZE
  46. #define PRINTF_NTOA_BUFFER_SIZE 32U
  47. #endif
  48. // 'ftoa' conversion buffer size, this must be big enough to hold one converted
  49. // float number including padded zeros (dynamically created on stack)
  50. // default: 32 byte
  51. #ifndef PRINTF_FTOA_BUFFER_SIZE
  52. #define PRINTF_FTOA_BUFFER_SIZE 32U
  53. #endif
  54. // support for the floating point type (%f)
  55. // default: activated
  56. #ifndef PRINTF_DISABLE_SUPPORT_FLOAT
  57. #define PRINTF_SUPPORT_FLOAT
  58. #endif
  59. // support for exponential floating point notation (%e/%g)
  60. // default: activated
  61. #ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL
  62. #define PRINTF_SUPPORT_EXPONENTIAL
  63. #endif
  64. // define the default floating point precision
  65. // default: 6 digits
  66. #ifndef PRINTF_DEFAULT_FLOAT_PRECISION
  67. #define PRINTF_DEFAULT_FLOAT_PRECISION 6U
  68. #endif
  69. // define the largest float suitable to print with %f
  70. // default: 1e9
  71. #ifndef PRINTF_MAX_FLOAT
  72. #define PRINTF_MAX_FLOAT 1e9
  73. #endif
  74. // support for the long long types (%llu or %p)
  75. // default: activated
  76. #ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG
  77. #define PRINTF_SUPPORT_LONG_LONG
  78. #endif
  79. // support for the ptrdiff_t type (%t)
  80. // ptrdiff_t is normally defined in <stddef.h> as long or long long type
  81. // default: activated
  82. #ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T
  83. #define PRINTF_SUPPORT_PTRDIFF_T
  84. #endif
  85. ///////////////////////////////////////////////////////////////////////////////
  86. // internal flag definitions
  87. #define FLAGS_ZEROPAD (1U << 0U)
  88. #define FLAGS_LEFT (1U << 1U)
  89. #define FLAGS_PLUS (1U << 2U)
  90. #define FLAGS_SPACE (1U << 3U)
  91. #define FLAGS_HASH (1U << 4U)
  92. #define FLAGS_UPPERCASE (1U << 5U)
  93. #define FLAGS_CHAR (1U << 6U)
  94. #define FLAGS_SHORT (1U << 7U)
  95. #define FLAGS_LONG (1U << 8U)
  96. #define FLAGS_LONG_LONG (1U << 9U)
  97. #define FLAGS_PRECISION (1U << 10U)
  98. #define FLAGS_ADAPT_EXP (1U << 11U)
  99. // import float.h for DBL_MAX
  100. #if defined(PRINTF_SUPPORT_FLOAT)
  101. #include <float.h>
  102. #endif
  103. // output function type
  104. typedef void (*out_fct_type)(char character, void* buffer, size_t idx, size_t maxlen);
  105. // wrapper (used as buffer) for output function type
  106. typedef struct {
  107. void (*fct)(char character, void* arg);
  108. void* arg;
  109. } out_fct_wrap_type;
  110. // internal buffer output
  111. static inline void _out_buffer(char character, void* buffer, size_t idx, size_t maxlen)
  112. {
  113. if (idx < maxlen) {
  114. ((char*)buffer)[idx] = character;
  115. }
  116. }
  117. // internal null output
  118. static inline void _out_null(char character, void* buffer, size_t idx, size_t maxlen)
  119. {
  120. (void)character; (void)buffer; (void)idx; (void)maxlen;
  121. }
  122. // internal _putchar wrapper
  123. static inline void _out_char(char character, void* buffer, size_t idx, size_t maxlen)
  124. {
  125. (void)buffer; (void)idx; (void)maxlen;
  126. if (character) {
  127. //_putchar(character);
  128. }
  129. }
  130. // internal output function wrapper
  131. static inline void _out_fct(char character, void* buffer, size_t idx, size_t maxlen)
  132. {
  133. (void)idx; (void)maxlen;
  134. if (character) {
  135. // buffer is the output fct pointer
  136. ((out_fct_wrap_type*)buffer)->fct(character, ((out_fct_wrap_type*)buffer)->arg);
  137. }
  138. }
  139. // internal secure strlen
  140. // \return The length of the string (excluding the terminating 0) limited by 'maxsize'
  141. static inline unsigned int _strnlen_s(const char* str, size_t maxsize)
  142. {
  143. const char* s;
  144. for (s = str; *s && maxsize--; ++s);
  145. return (unsigned int)(s - str);
  146. }
  147. // internal test if char is a digit (0-9)
  148. // \return true if char is a digit
  149. static inline bool _is_digit(char ch)
  150. {
  151. return (ch >= '0') && (ch <= '9');
  152. }
  153. // internal ASCII string to unsigned int conversion
  154. static unsigned int _atoi(const char** str)
  155. {
  156. unsigned int i = 0U;
  157. while (_is_digit(**str)) {
  158. i = i * 10U + (unsigned int)(*((*str)++) - '0');
  159. }
  160. return i;
  161. }
  162. // output the specified string in reverse, taking care of any zero-padding
  163. static size_t _out_rev(out_fct_type out, char* buffer, size_t idx, size_t maxlen, const char* buf, size_t len, unsigned int width, unsigned int flags)
  164. {
  165. const size_t start_idx = idx;
  166. // pad spaces up to given width
  167. if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) {
  168. for (size_t i = len; i < width; i++) {
  169. out(' ', buffer, idx++, maxlen);
  170. }
  171. }
  172. // reverse string
  173. while (len) {
  174. out(buf[--len], buffer, idx++, maxlen);
  175. }
  176. // append pad spaces up to given width
  177. if (flags & FLAGS_LEFT) {
  178. while (idx - start_idx < width) {
  179. out(' ', buffer, idx++, maxlen);
  180. }
  181. }
  182. return idx;
  183. }
  184. // internal itoa format
  185. static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags)
  186. {
  187. // pad leading zeros
  188. if (!(flags & FLAGS_LEFT)) {
  189. if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {
  190. width--;
  191. }
  192. while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
  193. buf[len++] = '0';
  194. }
  195. while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
  196. buf[len++] = '0';
  197. }
  198. }
  199. // handle hash
  200. if (flags & FLAGS_HASH) {
  201. if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) {
  202. len--;
  203. if (len && (base == 16U)) {
  204. len--;
  205. }
  206. }
  207. if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
  208. buf[len++] = 'x';
  209. }
  210. else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
  211. buf[len++] = 'X';
  212. }
  213. else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
  214. buf[len++] = 'b';
  215. }
  216. if (len < PRINTF_NTOA_BUFFER_SIZE) {
  217. buf[len++] = '0';
  218. }
  219. }
  220. if (len < PRINTF_NTOA_BUFFER_SIZE) {
  221. if (negative) {
  222. buf[len++] = '-';
  223. }
  224. else if (flags & FLAGS_PLUS) {
  225. buf[len++] = '+'; // ignore the space if the '+' exists
  226. }
  227. else if (flags & FLAGS_SPACE) {
  228. buf[len++] = ' ';
  229. }
  230. }
  231. return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags);
  232. }
  233. // internal itoa for 'long' type
  234. static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long value, bool negative, unsigned long base, unsigned int prec, unsigned int width, unsigned int flags)
  235. {
  236. char buf[PRINTF_NTOA_BUFFER_SIZE];
  237. size_t len = 0U;
  238. // no hash for 0 values
  239. if (!value) {
  240. flags &= ~FLAGS_HASH;
  241. }
  242. // write if precision != 0 and value is != 0
  243. if (!(flags & FLAGS_PRECISION) || value) {
  244. do {
  245. const char digit = (char)(value % base);
  246. buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10;
  247. value /= base;
  248. } while (value && (len < PRINTF_NTOA_BUFFER_SIZE));
  249. }
  250. return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags);
  251. }
  252. // internal itoa for 'long long' type
  253. #if defined(PRINTF_SUPPORT_LONG_LONG)
  254. static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long long value, bool negative, unsigned long long base, unsigned int prec, unsigned int width, unsigned int flags)
  255. {
  256. char buf[PRINTF_NTOA_BUFFER_SIZE];
  257. size_t len = 0U;
  258. // no hash for 0 values
  259. if (!value) {
  260. flags &= ~FLAGS_HASH;
  261. }
  262. // write if precision != 0 and value is != 0
  263. if (!(flags & FLAGS_PRECISION) || value) {
  264. do {
  265. const char digit = (char)(value % base);
  266. buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10;
  267. value /= base;
  268. } while (value && (len < PRINTF_NTOA_BUFFER_SIZE));
  269. }
  270. return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags);
  271. }
  272. #endif // PRINTF_SUPPORT_LONG_LONG
  273. #if defined(PRINTF_SUPPORT_FLOAT)
  274. #if defined(PRINTF_SUPPORT_EXPONENTIAL)
  275. // forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT
  276. static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags);
  277. #endif
  278. // internal ftoa for fixed decimal floating point
  279. static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags)
  280. {
  281. char buf[PRINTF_FTOA_BUFFER_SIZE];
  282. size_t len = 0U;
  283. double diff = 0.0;
  284. // powers of 10
  285. static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
  286. // test for special values
  287. if (value != value)
  288. return _out_rev(out, buffer, idx, maxlen, "nan", 3, width, flags);
  289. if (value < -DBL_MAX)
  290. return _out_rev(out, buffer, idx, maxlen, "fni-", 4, width, flags);
  291. if (value > DBL_MAX)
  292. return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags);
  293. // test for very large values
  294. // standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad
  295. if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) {
  296. #if defined(PRINTF_SUPPORT_EXPONENTIAL)
  297. return _etoa(out, buffer, idx, maxlen, value, prec, width, flags);
  298. #else
  299. return 0U;
  300. #endif
  301. }
  302. // test for negative
  303. bool negative = false;
  304. if (value < 0) {
  305. negative = true;
  306. value = 0 - value;
  307. }
  308. // set default precision, if not set explicitly
  309. if (!(flags & FLAGS_PRECISION)) {
  310. prec = PRINTF_DEFAULT_FLOAT_PRECISION;
  311. }
  312. // limit precision to 9, cause a prec >= 10 can lead to overflow errors
  313. while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) {
  314. buf[len++] = '0';
  315. prec--;
  316. }
  317. int whole = (int)value;
  318. double tmp = (value - whole) * pow10[prec];
  319. unsigned long frac = (unsigned long)tmp;
  320. diff = tmp - frac;
  321. if (diff > 0.5) {
  322. ++frac;
  323. // handle rollover, e.g. case 0.99 with prec 1 is 1.0
  324. if (frac >= pow10[prec]) {
  325. frac = 0;
  326. ++whole;
  327. }
  328. }
  329. else if (diff < 0.5) {
  330. }
  331. else if ((frac == 0U) || (frac & 1U)) {
  332. // if halfway, round up if odd OR if last digit is 0
  333. ++frac;
  334. }
  335. if (prec == 0U) {
  336. diff = value - (double)whole;
  337. if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) {
  338. // exactly 0.5 and ODD, then round up
  339. // 1.5 -> 2, but 2.5 -> 2
  340. ++whole;
  341. }
  342. }
  343. else {
  344. unsigned int count = prec;
  345. // now do fractional part, as an unsigned number
  346. while (len < PRINTF_FTOA_BUFFER_SIZE) {
  347. --count;
  348. buf[len++] = (char)(48U + (frac % 10U));
  349. if (!(frac /= 10U)) {
  350. break;
  351. }
  352. }
  353. // add extra 0s
  354. while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) {
  355. buf[len++] = '0';
  356. }
  357. if (len < PRINTF_FTOA_BUFFER_SIZE) {
  358. // add decimal
  359. buf[len++] = '.';
  360. }
  361. }
  362. // do whole part, number is reversed
  363. while (len < PRINTF_FTOA_BUFFER_SIZE) {
  364. buf[len++] = (char)(48 + (whole % 10));
  365. if (!(whole /= 10)) {
  366. break;
  367. }
  368. }
  369. // pad leading zeros
  370. if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) {
  371. if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {
  372. width--;
  373. }
  374. while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) {
  375. buf[len++] = '0';
  376. }
  377. }
  378. if (len < PRINTF_FTOA_BUFFER_SIZE) {
  379. if (negative) {
  380. buf[len++] = '-';
  381. }
  382. else if (flags & FLAGS_PLUS) {
  383. buf[len++] = '+'; // ignore the space if the '+' exists
  384. }
  385. else if (flags & FLAGS_SPACE) {
  386. buf[len++] = ' ';
  387. }
  388. }
  389. return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags);
  390. }
  391. #if defined(PRINTF_SUPPORT_EXPONENTIAL)
  392. // internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse <m.jasperse@gmail.com>
  393. static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags)
  394. {
  395. // check for NaN and special values
  396. if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) {
  397. return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags);
  398. }
  399. // determine the sign
  400. const bool negative = value < 0;
  401. if (negative) {
  402. value = -value;
  403. }
  404. // default precision
  405. if (!(flags & FLAGS_PRECISION)) {
  406. prec = PRINTF_DEFAULT_FLOAT_PRECISION;
  407. }
  408. // determine the decimal exponent
  409. // based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c)
  410. union {
  411. uint64_t U;
  412. double F;
  413. } conv;
  414. conv.F = value;
  415. int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2
  416. conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2)
  417. // now approximate log10 from the log2 integer part and an expansion of ln around 1.5
  418. int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168);
  419. // now we want to compute 10^expval but we want to be sure it won't overflow
  420. exp2 = (int)(expval * 3.321928094887362 + 0.5);
  421. const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453;
  422. const double z2 = z * z;
  423. conv.U = (uint64_t)(exp2 + 1023) << 52U;
  424. // compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex
  425. conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14)))));
  426. // correct for rounding errors
  427. if (value < conv.F) {
  428. expval--;
  429. conv.F /= 10;
  430. }
  431. // the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters
  432. unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U;
  433. // in "%g" mode, "prec" is the number of *significant figures* not decimals
  434. if (flags & FLAGS_ADAPT_EXP) {
  435. // do we want to fall-back to "%f" mode?
  436. if ((value >= 1e-4) && (value < 1e6)) {
  437. if ((int)prec > expval) {
  438. prec = (unsigned)((int)prec - expval - 1);
  439. }
  440. else {
  441. prec = 0;
  442. }
  443. flags |= FLAGS_PRECISION; // make sure _ftoa respects precision
  444. // no characters in exponent
  445. minwidth = 0U;
  446. expval = 0;
  447. }
  448. else {
  449. // we use one sigfig for the whole part
  450. if ((prec > 0) && (flags & FLAGS_PRECISION)) {
  451. --prec;
  452. }
  453. }
  454. }
  455. // will everything fit?
  456. unsigned int fwidth = width;
  457. if (width > minwidth) {
  458. // we didn't fall-back so subtract the characters required for the exponent
  459. fwidth -= minwidth;
  460. } else {
  461. // not enough characters, so go back to default sizing
  462. fwidth = 0U;
  463. }
  464. if ((flags & FLAGS_LEFT) && minwidth) {
  465. // if we're padding on the right, DON'T pad the floating part
  466. fwidth = 0U;
  467. }
  468. // rescale the float value
  469. if (expval) {
  470. value /= conv.F;
  471. }
  472. // output the floating part
  473. const size_t start_idx = idx;
  474. idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP);
  475. // output the exponent part
  476. if (minwidth) {
  477. // output the exponential symbol
  478. out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen);
  479. // output the exponent value
  480. idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth-1, FLAGS_ZEROPAD | FLAGS_PLUS);
  481. // might need to right-pad spaces
  482. if (flags & FLAGS_LEFT) {
  483. while (idx - start_idx < width) out(' ', buffer, idx++, maxlen);
  484. }
  485. }
  486. return idx;
  487. }
  488. #endif // PRINTF_SUPPORT_EXPONENTIAL
  489. #endif // PRINTF_SUPPORT_FLOAT
  490. // internal vsnprintf
  491. static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const char* format, va_list va)
  492. {
  493. unsigned int flags, width, precision, n;
  494. size_t idx = 0U;
  495. if (!buffer) {
  496. // use null output function
  497. out = _out_null;
  498. }
  499. while (*format)
  500. {
  501. // format specifier? %[flags][width][.precision][length]
  502. if (*format != '%') {
  503. // no
  504. out(*format, buffer, idx++, maxlen);
  505. format++;
  506. continue;
  507. }
  508. else {
  509. // yes, evaluate it
  510. format++;
  511. }
  512. // evaluate flags
  513. flags = 0U;
  514. do {
  515. switch (*format) {
  516. case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break;
  517. case '-': flags |= FLAGS_LEFT; format++; n = 1U; break;
  518. case '+': flags |= FLAGS_PLUS; format++; n = 1U; break;
  519. case ' ': flags |= FLAGS_SPACE; format++; n = 1U; break;
  520. case '#': flags |= FLAGS_HASH; format++; n = 1U; break;
  521. default : n = 0U; break;
  522. }
  523. } while (n);
  524. // evaluate width field
  525. width = 0U;
  526. if (_is_digit(*format)) {
  527. width = _atoi(&format);
  528. }
  529. else if (*format == '*') {
  530. const int w = va_arg(va, int);
  531. if (w < 0) {
  532. flags |= FLAGS_LEFT; // reverse padding
  533. width = (unsigned int)-w;
  534. }
  535. else {
  536. width = (unsigned int)w;
  537. }
  538. format++;
  539. }
  540. // evaluate precision field
  541. precision = 0U;
  542. if (*format == '.') {
  543. flags |= FLAGS_PRECISION;
  544. format++;
  545. if (_is_digit(*format)) {
  546. precision = _atoi(&format);
  547. }
  548. else if (*format == '*') {
  549. const int prec = (int)va_arg(va, int);
  550. precision = prec > 0 ? (unsigned int)prec : 0U;
  551. format++;
  552. }
  553. }
  554. // evaluate length field
  555. switch (*format) {
  556. case 'l' :
  557. flags |= FLAGS_LONG;
  558. format++;
  559. if (*format == 'l') {
  560. flags |= FLAGS_LONG_LONG;
  561. format++;
  562. }
  563. break;
  564. case 'h' :
  565. flags |= FLAGS_SHORT;
  566. format++;
  567. if (*format == 'h') {
  568. flags |= FLAGS_CHAR;
  569. format++;
  570. }
  571. break;
  572. #if defined(PRINTF_SUPPORT_PTRDIFF_T)
  573. case 't' :
  574. flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
  575. format++;
  576. break;
  577. #endif
  578. case 'j' :
  579. flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
  580. format++;
  581. break;
  582. case 'z' :
  583. flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
  584. format++;
  585. break;
  586. default :
  587. break;
  588. }
  589. // evaluate specifier
  590. switch (*format) {
  591. case 'd' :
  592. case 'i' :
  593. case 'u' :
  594. case 'x' :
  595. case 'X' :
  596. case 'o' :
  597. case 'b' : {
  598. // set the base
  599. unsigned int base;
  600. if (*format == 'x' || *format == 'X') {
  601. base = 16U;
  602. }
  603. else if (*format == 'o') {
  604. base = 8U;
  605. }
  606. else if (*format == 'b') {
  607. base = 2U;
  608. }
  609. else {
  610. base = 10U;
  611. flags &= ~FLAGS_HASH; // no hash for dec format
  612. }
  613. // uppercase
  614. if (*format == 'X') {
  615. flags |= FLAGS_UPPERCASE;
  616. }
  617. // no plus or space flag for u, x, X, o, b
  618. if ((*format != 'i') && (*format != 'd')) {
  619. flags &= ~(FLAGS_PLUS | FLAGS_SPACE);
  620. }
  621. // ignore '0' flag when precision is given
  622. if (flags & FLAGS_PRECISION) {
  623. flags &= ~FLAGS_ZEROPAD;
  624. }
  625. // convert the integer
  626. if ((*format == 'i') || (*format == 'd')) {
  627. // signed
  628. if (flags & FLAGS_LONG_LONG) {
  629. #if defined(PRINTF_SUPPORT_LONG_LONG)
  630. const long long value = va_arg(va, long long);
  631. idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
  632. #endif
  633. }
  634. else if (flags & FLAGS_LONG) {
  635. const long value = va_arg(va, long);
  636. idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
  637. }
  638. else {
  639. const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int);
  640. idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
  641. }
  642. }
  643. else {
  644. // unsigned
  645. if (flags & FLAGS_LONG_LONG) {
  646. #if defined(PRINTF_SUPPORT_LONG_LONG)
  647. idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags);
  648. #endif
  649. }
  650. else if (flags & FLAGS_LONG) {
  651. idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags);
  652. }
  653. else {
  654. const unsigned int value = (flags & FLAGS_CHAR) ? (unsigned char)va_arg(va, unsigned int) : (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(va, unsigned int) : va_arg(va, unsigned int);
  655. idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags);
  656. }
  657. }
  658. format++;
  659. break;
  660. }
  661. #if defined(PRINTF_SUPPORT_FLOAT)
  662. case 'f' :
  663. case 'F' :
  664. if (*format == 'F') flags |= FLAGS_UPPERCASE;
  665. idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
  666. format++;
  667. break;
  668. #if defined(PRINTF_SUPPORT_EXPONENTIAL)
  669. case 'e':
  670. case 'E':
  671. case 'g':
  672. case 'G':
  673. if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP;
  674. if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE;
  675. idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
  676. format++;
  677. break;
  678. #endif // PRINTF_SUPPORT_EXPONENTIAL
  679. #endif // PRINTF_SUPPORT_FLOAT
  680. case 'c' : {
  681. unsigned int l = 1U;
  682. // pre padding
  683. if (!(flags & FLAGS_LEFT)) {
  684. while (l++ < width) {
  685. out(' ', buffer, idx++, maxlen);
  686. }
  687. }
  688. // char output
  689. out((char)va_arg(va, int), buffer, idx++, maxlen);
  690. // post padding
  691. if (flags & FLAGS_LEFT) {
  692. while (l++ < width) {
  693. out(' ', buffer, idx++, maxlen);
  694. }
  695. }
  696. format++;
  697. break;
  698. }
  699. case 's' : {
  700. const char* p = va_arg(va, char*);
  701. unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1);
  702. // pre padding
  703. if (flags & FLAGS_PRECISION) {
  704. l = (l < precision ? l : precision);
  705. }
  706. if (!(flags & FLAGS_LEFT)) {
  707. while (l++ < width) {
  708. out(' ', buffer, idx++, maxlen);
  709. }
  710. }
  711. // string output
  712. while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) {
  713. out(*(p++), buffer, idx++, maxlen);
  714. }
  715. // post padding
  716. if (flags & FLAGS_LEFT) {
  717. while (l++ < width) {
  718. out(' ', buffer, idx++, maxlen);
  719. }
  720. }
  721. format++;
  722. break;
  723. }
  724. case 'p' : {
  725. width = sizeof(void*) * 2U;
  726. flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE;
  727. #if defined(PRINTF_SUPPORT_LONG_LONG)
  728. const bool is_ll = sizeof(uintptr_t) == sizeof(long long);
  729. if (is_ll) {
  730. idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags);
  731. }
  732. else {
  733. #endif
  734. idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags);
  735. #if defined(PRINTF_SUPPORT_LONG_LONG)
  736. }
  737. #endif
  738. format++;
  739. break;
  740. }
  741. case '%' :
  742. out('%', buffer, idx++, maxlen);
  743. format++;
  744. break;
  745. default :
  746. out(*format, buffer, idx++, maxlen);
  747. format++;
  748. break;
  749. }
  750. }
  751. // termination
  752. out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen);
  753. // return written chars without terminating \0
  754. return (int)idx;
  755. }
  756. ///////////////////////////////////////////////////////////////////////////////
  757. int printf_(const char* format, ...)
  758. {
  759. va_list va;
  760. va_start(va, format);
  761. char buffer[1];
  762. const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va);
  763. va_end(va);
  764. return ret;
  765. }
  766. int __wrap_sprintf(char* buffer, const char* format, ...)
  767. {
  768. va_list va;
  769. va_start(va, format);
  770. const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va);
  771. va_end(va);
  772. return ret;
  773. }
  774. int sprintf_(char* buffer, const char* format, ...)
  775. {
  776. va_list va;
  777. va_start(va, format);
  778. const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va);
  779. va_end(va);
  780. return ret;
  781. }
  782. int __wrap_snprintf(char* buffer, size_t count, const char* format, ...)
  783. {
  784. va_list va;
  785. va_start(va, format);
  786. const int ret = _vsnprintf(_out_buffer, buffer, count, format, va);
  787. va_end(va);
  788. return ret;
  789. }
  790. int snprintf_(char* buffer, size_t count, const char* format, ...)
  791. {
  792. va_list va;
  793. va_start(va, format);
  794. const int ret = _vsnprintf(_out_buffer, buffer, count, format, va);
  795. va_end(va);
  796. return ret;
  797. }
  798. int __wrap_vprintf(const char* format, va_list va)
  799. {
  800. char buffer[1];
  801. return _vsnprintf(_out_char, buffer, (size_t)-1, format, va);
  802. }
  803. int vprintf_(const char* format, va_list va)
  804. {
  805. char buffer[1];
  806. return _vsnprintf(_out_char, buffer, (size_t)-1, format, va);
  807. }
  808. int __wrap_vsnprintf(char* buffer, size_t count, const char* format, va_list va)
  809. {
  810. return _vsnprintf(_out_buffer, buffer, count, format, va);
  811. }
  812. int vsnprintf_(char* buffer, size_t count, const char* format, va_list va)
  813. {
  814. return _vsnprintf(_out_buffer, buffer, count, format, va);
  815. }
  816. int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...)
  817. {
  818. va_list va;
  819. va_start(va, format);
  820. const out_fct_wrap_type out_fct_wrap = { out, arg };
  821. const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va);
  822. va_end(va);
  823. return ret;
  824. }
  825. int __wrap_fprintf (FILE *fp, const char *format, va_list va)
  826. {
  827. return -1;
  828. }