You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

987 lines
29 KiB

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