ARM application development SDK for MNT ZZ9000 graphics and coprocessor card for classic Amiga computers.
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.

printf.c 27KB

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