printf.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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 <string.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. #ifdef __PRINT_ALIGNED_32BIT__
  496. volatile uint32_t *ap_addr;
  497. volatile uint32_t ap_value;
  498. uint32_t d1,d2;
  499. uint64_t value;
  500. double f64;
  501. #endif
  502. if (!buffer) {
  503. // use null output function
  504. out = _out_null;
  505. }
  506. while (*format)
  507. {
  508. // format specifier? %[flags][width][.precision][length]
  509. if (*format != '%') {
  510. // no
  511. out(*format, buffer, idx++, maxlen);
  512. format++;
  513. continue;
  514. }
  515. else {
  516. // yes, evaluate it
  517. format++;
  518. }
  519. // evaluate flags
  520. flags = 0U;
  521. do {
  522. switch (*format) {
  523. case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break;
  524. case '-': flags |= FLAGS_LEFT; format++; n = 1U; break;
  525. case '+': flags |= FLAGS_PLUS; format++; n = 1U; break;
  526. case ' ': flags |= FLAGS_SPACE; format++; n = 1U; break;
  527. case '#': flags |= FLAGS_HASH; format++; n = 1U; break;
  528. default : n = 0U; break;
  529. }
  530. } while (n);
  531. // evaluate width field
  532. width = 0U;
  533. if (_is_digit(*format)) {
  534. width = _atoi(&format);
  535. }
  536. else if (*format == '*') {
  537. const int w = va_arg(va, int);
  538. if (w < 0) {
  539. flags |= FLAGS_LEFT; // reverse padding
  540. width = (unsigned int)-w;
  541. }
  542. else {
  543. width = (unsigned int)w;
  544. }
  545. format++;
  546. }
  547. // evaluate precision field
  548. precision = 0U;
  549. if (*format == '.') {
  550. flags |= FLAGS_PRECISION;
  551. format++;
  552. if (_is_digit(*format)) {
  553. precision = _atoi(&format);
  554. }
  555. else if (*format == '*') {
  556. const int prec = (int)va_arg(va, int);
  557. precision = prec > 0 ? (unsigned int)prec : 0U;
  558. format++;
  559. }
  560. }
  561. // evaluate length field
  562. switch (*format) {
  563. case 'l' :
  564. flags |= FLAGS_LONG;
  565. format++;
  566. if (*format == 'l') {
  567. flags |= FLAGS_LONG_LONG;
  568. format++;
  569. }
  570. break;
  571. case 'h' :
  572. flags |= FLAGS_SHORT;
  573. format++;
  574. if (*format == 'h') {
  575. flags |= FLAGS_CHAR;
  576. format++;
  577. }
  578. break;
  579. #if defined(PRINTF_SUPPORT_PTRDIFF_T)
  580. case 't' :
  581. flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
  582. format++;
  583. break;
  584. #endif
  585. case 'j' :
  586. flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
  587. format++;
  588. break;
  589. case 'z' :
  590. flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
  591. format++;
  592. break;
  593. default :
  594. break;
  595. }
  596. // evaluate specifier
  597. switch (*format) {
  598. case 'd' :
  599. case 'i' :
  600. case 'u' :
  601. case 'x' :
  602. case 'X' :
  603. case 'o' :
  604. case 'b' : {
  605. // set the base
  606. unsigned int base;
  607. if (*format == 'x' || *format == 'X') {
  608. base = 16U;
  609. }
  610. else if (*format == 'o') {
  611. base = 8U;
  612. }
  613. else if (*format == 'b') {
  614. base = 2U;
  615. }
  616. else {
  617. base = 10U;
  618. flags &= ~FLAGS_HASH; // no hash for dec format
  619. }
  620. // uppercase
  621. if (*format == 'X') {
  622. flags |= FLAGS_UPPERCASE;
  623. }
  624. // no plus or space flag for u, x, X, o, b
  625. if ((*format != 'i') && (*format != 'd')) {
  626. flags &= ~(FLAGS_PLUS | FLAGS_SPACE);
  627. }
  628. // ignore '0' flag when precision is given
  629. if (flags & FLAGS_PRECISION) {
  630. flags &= ~FLAGS_ZEROPAD;
  631. }
  632. // convert the integer
  633. if ((*format == 'i') || (*format == 'd')) {
  634. // signed
  635. if (flags & FLAGS_LONG_LONG) {
  636. #if defined(PRINTF_SUPPORT_LONG_LONG)
  637. #ifdef __PRINT_ALIGNED_32BIT__
  638. ap_addr = (uint32_t *)&va;
  639. ap_value = (*ap_addr);
  640. if (!(ap_value & 0x07))
  641. {
  642. d1 = va_arg(va, uint32_t);
  643. }
  644. d1 = va_arg(va, uint32_t);
  645. d2 = va_arg(va, uint32_t);
  646. long long value2 = d2;
  647. value2 = (value2 << 32) | d1;
  648. #else
  649. const long long value2 = va_arg(va, long long);
  650. #endif
  651. idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value2 > 0 ? value2 : 0 - value2), value2 < 0, base, precision, width, flags);
  652. #endif
  653. }
  654. else if (flags & FLAGS_LONG) {
  655. const long value = va_arg(va, long);
  656. idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
  657. }
  658. else {
  659. const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int);
  660. idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
  661. }
  662. }
  663. else {
  664. // unsigned
  665. if (flags & FLAGS_LONG_LONG) {
  666. #if defined(PRINTF_SUPPORT_LONG_LONG)
  667. #ifdef __PRINT_ALIGNED_32BIT__
  668. ap_addr = (uint32_t *)&va;
  669. ap_value = (*ap_addr);
  670. if (!(ap_value & 0x07))
  671. {
  672. d1 = va_arg(va, uint32_t);
  673. }
  674. d1 = va_arg(va, uint32_t);
  675. d2 = va_arg(va, uint32_t);
  676. value = d2;
  677. value = (value << 32) | d1;
  678. idx = _ntoa_long_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags);
  679. #else
  680. idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags);
  681. #endif
  682. #endif
  683. }
  684. else if (flags & FLAGS_LONG) {
  685. idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags);
  686. }
  687. else {
  688. 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);
  689. idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags);
  690. }
  691. }
  692. format++;
  693. break;
  694. }
  695. #if defined(PRINTF_SUPPORT_FLOAT)
  696. case 'f' :
  697. case 'F' :
  698. if (*format == 'F') flags |= FLAGS_UPPERCASE;
  699. #ifdef __PRINT_ALIGNED_32BIT__
  700. ap_addr = (uint32_t *)&va;
  701. ap_value = (*ap_addr);
  702. if (!(ap_value & 0x07))
  703. {
  704. d1 = va_arg(va, uint32_t);
  705. }
  706. d1 = va_arg(va, uint32_t);
  707. d2 = va_arg(va, uint32_t);
  708. value = d2;
  709. value = (value << 32) | d1;
  710. memcpy(&f64, &value, 8);
  711. idx = _ftoa(out, buffer, idx, maxlen, f64, precision, width, flags);
  712. #else
  713. idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
  714. #endif
  715. format++;
  716. break;
  717. #if defined(PRINTF_SUPPORT_EXPONENTIAL)
  718. case 'e':
  719. case 'E':
  720. case 'g':
  721. case 'G':
  722. if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP;
  723. if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE;
  724. #ifdef __PRINT_ALIGNED_32BIT__
  725. ap_addr = (uint32_t *)&va;
  726. ap_value = (*ap_addr);
  727. if (!(ap_value & 0x07))
  728. {
  729. d1 = va_arg(va, uint32_t);
  730. }
  731. d1 = va_arg(va, uint32_t);
  732. d2 = va_arg(va, uint32_t);
  733. value = d2;
  734. value = (value << 32) | d1;
  735. memcpy(&f64, &value, 8);
  736. idx = _etoa(out, buffer, idx, maxlen, f64, precision, width, flags);
  737. #else
  738. idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
  739. #endif
  740. format++;
  741. break;
  742. #endif // PRINTF_SUPPORT_EXPONENTIAL
  743. #endif // PRINTF_SUPPORT_FLOAT
  744. case 'c' : {
  745. unsigned int l = 1U;
  746. // pre padding
  747. if (!(flags & FLAGS_LEFT)) {
  748. while (l++ < width) {
  749. out(' ', buffer, idx++, maxlen);
  750. }
  751. }
  752. // char output
  753. out((char)va_arg(va, int), buffer, idx++, maxlen);
  754. // post padding
  755. if (flags & FLAGS_LEFT) {
  756. while (l++ < width) {
  757. out(' ', buffer, idx++, maxlen);
  758. }
  759. }
  760. format++;
  761. break;
  762. }
  763. case 's' : {
  764. const char* p = va_arg(va, char*);
  765. unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1);
  766. // pre padding
  767. if (flags & FLAGS_PRECISION) {
  768. l = (l < precision ? l : precision);
  769. }
  770. if (!(flags & FLAGS_LEFT)) {
  771. while (l++ < width) {
  772. out(' ', buffer, idx++, maxlen);
  773. }
  774. }
  775. // string output
  776. while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) {
  777. out(*(p++), buffer, idx++, maxlen);
  778. }
  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 'p' : {
  789. width = sizeof(void*) * 2U;
  790. flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE;
  791. #if defined(PRINTF_SUPPORT_LONG_LONG)
  792. const bool is_ll = sizeof(uintptr_t) == sizeof(long long);
  793. if (is_ll) {
  794. idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags);
  795. }
  796. else {
  797. #endif
  798. idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags);
  799. #if defined(PRINTF_SUPPORT_LONG_LONG)
  800. }
  801. #endif
  802. format++;
  803. break;
  804. }
  805. case '%' :
  806. out('%', buffer, idx++, maxlen);
  807. format++;
  808. break;
  809. default :
  810. out(*format, buffer, idx++, maxlen);
  811. format++;
  812. break;
  813. }
  814. }
  815. // termination
  816. out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen);
  817. // return written chars without terminating \0
  818. return (int)idx;
  819. }
  820. ///////////////////////////////////////////////////////////////////////////////
  821. int printf_(const char* format, ...)
  822. {
  823. va_list va;
  824. va_start(va, format);
  825. char buffer[1];
  826. const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va);
  827. va_end(va);
  828. return ret;
  829. }
  830. int sprintf_(char* buffer, const char* format, ...)
  831. {
  832. va_list va;
  833. va_start(va, format);
  834. const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va);
  835. va_end(va);
  836. return ret;
  837. }
  838. int snprintf_(char* buffer, size_t count, const char* format, ...)
  839. {
  840. va_list va;
  841. va_start(va, format);
  842. const int ret = _vsnprintf(_out_buffer, buffer, count, format, va);
  843. va_end(va);
  844. return ret;
  845. }
  846. int vprintf_(const char* format, va_list va)
  847. {
  848. char buffer[1];
  849. return _vsnprintf(_out_char, buffer, (size_t)-1, format, va);
  850. }
  851. int vsnprintf_(char* buffer, size_t count, const char* format, va_list va)
  852. {
  853. return _vsnprintf(_out_buffer, buffer, count, format, va);
  854. }
  855. int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...)
  856. {
  857. va_list va;
  858. va_start(va, format);
  859. const out_fct_wrap_type out_fct_wrap = { out, arg };
  860. const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va);
  861. va_end(va);
  862. return ret;
  863. }