printf_tiny.c 31 KB

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