rt_vsnprintf_std.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  1. /*
  2. * Copyright (c) 2006-2024, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2021-11-27 Meco Man porting for rt_vsnprintf as the fully functional version
  9. * 2024-11-19 Meco Man move to klibc
  10. */
  11. /**
  12. * @author (c) Eyal Rozenberg <eyalroz1@gmx.com>
  13. * 2021-2022, Haifa, Palestine/Israel
  14. * @author (c) Marco Paland (info@paland.com)
  15. * 2014-2019, PALANDesign Hannover, Germany
  16. *
  17. * @note Others have made smaller contributions to this file: see the
  18. * contributors page at https://github.com/eyalroz/printf/graphs/contributors
  19. * or ask one of the authors. The original code for exponential specifiers was
  20. * contributed by Martijn Jasperse <m.jasperse@gmail.com>.
  21. *
  22. * @brief Small stand-alone implementation of the printf family of functions
  23. * (`(v)printf`, `(v)s(n)printf` etc., geared towards use on embedded systems with
  24. * a very limited resources.
  25. *
  26. * @note the implementations are thread-safe; re-entrant; use no functions from
  27. * the standard library; and do not dynamically allocate any memory.
  28. *
  29. * @license The MIT License (MIT)
  30. *
  31. * Permission is hereby granted, free of charge, to any person obtaining a copy
  32. * of this software and associated documentation files (the "Software"), to deal
  33. * in the Software without restriction, including without limitation the rights
  34. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  35. * copies of the Software, and to permit persons to whom the Software is
  36. * furnished to do so, subject to the following conditions:
  37. *
  38. * The above copyright notice and this permission notice shall be included in
  39. * all copies or substantial portions of the Software.
  40. *
  41. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  42. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  43. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  44. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  45. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  46. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  47. * THE SOFTWARE.
  48. */
  49. #include <rtthread.h>
  50. #include <stdio.h>
  51. #include <stdint.h>
  52. #include <limits.h>
  53. #include <stdbool.h>
  54. // 'ntoa' conversion buffer size, this must be big enough to hold one converted
  55. // numeric number including padded zeros (dynamically created on stack)
  56. #ifndef RT_KLIBC_USING_VSNPRINTF_INTEGER_BUFFER_SIZE
  57. #define RT_KLIBC_USING_VSNPRINTF_INTEGER_BUFFER_SIZE 32
  58. #endif
  59. // size of the fixed (on-stack) buffer for printing individual decimal numbers.
  60. // this must be big enough to hold one converted floating-point value including
  61. // padded zeros.
  62. #ifndef RT_KLIBC_USING_VSNPRINTF_DECIMAL_BUFFER_SIZE
  63. #define RT_KLIBC_USING_VSNPRINTF_DECIMAL_BUFFER_SIZE 32
  64. #endif
  65. // Support for the decimal notation floating point conversion specifiers (%f, %F)
  66. #ifndef RT_KLIBC_USING_VSNPRINTF_DECIMAL_SPECIFIERS
  67. #define RT_KLIBC_USING_VSNPRINTF_DECIMAL_SPECIFIERS
  68. #endif
  69. // Support for the exponential notation floating point conversion specifiers (%e, %g, %E, %G)
  70. #ifndef RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS
  71. #define RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS
  72. #endif
  73. // Support for the length write-back specifier (%n)
  74. #ifndef RT_KLIBC_USING_VSNPRINTF_WRITEBACK_SPECIFIER
  75. #define RT_KLIBC_USING_VSNPRINTF_WRITEBACK_SPECIFIER
  76. #endif
  77. // Default precision for the floating point conversion specifiers (the C standard sets this at 6)
  78. #ifndef RT_KLIBC_USING_VSNPRINTF_FLOAT_PRECISION
  79. #define RT_KLIBC_USING_VSNPRINTF_FLOAT_PRECISION 6
  80. #endif
  81. // According to the C languages standard, printf() and related functions must be able to print any
  82. // integral number in floating-point notation, regardless of length, when using the %f specifier -
  83. // possibly hundreds of characters, potentially overflowing your buffers. In this implementation,
  84. // all values beyond this threshold are switched to exponential notation.
  85. #ifndef RT_KLIBC_USING_VSNPRINTF_MAX_INTEGRAL_DIGITS_FOR_DECIMAL
  86. #define RT_KLIBC_USING_VSNPRINTF_MAX_INTEGRAL_DIGITS_FOR_DECIMAL 9
  87. #endif
  88. // Support for the long long integral types (with the ll, z and t length modifiers for specifiers
  89. // %d,%i,%o,%x,%X,%u, and with the %p specifier). Note: 'L' (long double) is not supported.
  90. #ifndef RT_KLIBC_USING_VSNPRINTF_LONGLONG
  91. #define RT_KLIBC_USING_VSNPRINTF_LONGLONG
  92. #endif
  93. // The number of terms in a Taylor series expansion of log_10(x) to
  94. // use for approximation - including the power-zero term (i.e. the
  95. // value at the point of expansion).
  96. #ifndef RT_KLIBC_USING_VSNPRINTF_LOG10_TAYLOR_TERMS
  97. #define RT_KLIBC_USING_VSNPRINTF_LOG10_TAYLOR_TERMS 4
  98. #endif
  99. // Be extra-safe, and don't assume format specifiers are completed correctly
  100. // before the format string end.
  101. #if !defined(RT_KLIBC_USING_VSNPRINTF_CHECK_NUL_IN_FORMAT_SPECIFIER) || defined(RT_USING_DEBUG)
  102. #define RT_KLIBC_USING_VSNPRINTF_CHECK_NUL_IN_FORMAT_SPECIFIER
  103. #endif
  104. #if RT_KLIBC_USING_VSNPRINTF_LOG10_TAYLOR_TERMS <= 1
  105. #error "At least one non-constant Taylor expansion is necessary for the log10() calculation"
  106. #endif
  107. ///////////////////////////////////////////////////////////////////////////////
  108. #define PRINTF_PREFER_DECIMAL false
  109. #define PRINTF_PREFER_EXPONENTIAL true
  110. // The following will convert the number-of-digits into an exponential-notation literal
  111. #define PRINTF_CONCATENATE(s1, s2) s1##s2
  112. #define PRINTF_EXPAND_THEN_CONCATENATE(s1, s2) PRINTF_CONCATENATE(s1, s2)
  113. #define PRINTF_FLOAT_NOTATION_THRESHOLD PRINTF_EXPAND_THEN_CONCATENATE(1e,RT_KLIBC_USING_VSNPRINTF_MAX_INTEGRAL_DIGITS_FOR_DECIMAL)
  114. // internal flag definitions
  115. #define FLAGS_ZEROPAD (1U << 0U)
  116. #define FLAGS_LEFT (1U << 1U)
  117. #define FLAGS_PLUS (1U << 2U)
  118. #define FLAGS_SPACE (1U << 3U)
  119. #define FLAGS_HASH (1U << 4U)
  120. #define FLAGS_UPPERCASE (1U << 5U)
  121. #define FLAGS_CHAR (1U << 6U)
  122. #define FLAGS_SHORT (1U << 7U)
  123. #define FLAGS_INT (1U << 8U)
  124. // Only used with RT_KLIBC_USING_VSNPRINTF_MSVC_STYLE_INTEGER_SPECIFIERS
  125. #define FLAGS_LONG (1U << 9U)
  126. #define FLAGS_LONG_LONG (1U << 10U)
  127. #define FLAGS_PRECISION (1U << 11U)
  128. #define FLAGS_ADAPT_EXP (1U << 12U)
  129. #define FLAGS_POINTER (1U << 13U)
  130. // Note: Similar, but not identical, effect as FLAGS_HASH
  131. #define FLAGS_SIGNED (1U << 14U)
  132. // Only used with RT_KLIBC_USING_VSNPRINTF_MSVC_STYLE_INTEGER_SPECIFIERS
  133. #ifdef RT_KLIBC_USING_VSNPRINTF_MSVC_STYLE_INTEGER_SPECIFIERS
  134. #define FLAGS_INT8 FLAGS_CHAR
  135. #if (SHRT_MAX == 32767LL)
  136. #define FLAGS_INT16 FLAGS_SHORT
  137. #elif (INT_MAX == 32767LL)
  138. #define FLAGS_INT16 FLAGS_INT
  139. #elif (LONG_MAX == 32767LL)
  140. #define FLAGS_INT16 FLAGS_LONG
  141. #elif (LLONG_MAX == 32767LL)
  142. #define FLAGS_INT16 FLAGS_LONG_LONG
  143. #else
  144. #error "No basic integer type has a size of 16 bits exactly"
  145. #endif
  146. #if (SHRT_MAX == 2147483647LL)
  147. #define FLAGS_INT32 FLAGS_SHORT
  148. #elif (INT_MAX == 2147483647LL)
  149. #define FLAGS_INT32 FLAGS_INT
  150. #elif (LONG_MAX == 2147483647LL)
  151. #define FLAGS_INT32 FLAGS_LONG
  152. #elif (LLONG_MAX == 2147483647LL)
  153. #define FLAGS_INT32 FLAGS_LONG_LONG
  154. #else
  155. #error "No basic integer type has a size of 32 bits exactly"
  156. #endif
  157. #if (SHRT_MAX == 9223372036854775807LL)
  158. #define FLAGS_INT64 FLAGS_SHORT
  159. #elif (INT_MAX == 9223372036854775807LL)
  160. #define FLAGS_INT64 FLAGS_INT
  161. #elif (LONG_MAX == 9223372036854775807LL)
  162. #define FLAGS_INT64 FLAGS_LONG
  163. #elif (LLONG_MAX == 9223372036854775807LL)
  164. #define FLAGS_INT64 FLAGS_LONG_LONG
  165. #else
  166. #error "No basic integer type has a size of 64 bits exactly"
  167. #endif
  168. #endif // RT_KLIBC_USING_VSNPRINTF_MSVC_STYLE_INTEGER_SPECIFIERS
  169. typedef unsigned int printf_flags_t;
  170. #define BASE_BINARY 2
  171. #define BASE_OCTAL 8
  172. #define BASE_DECIMAL 10
  173. #define BASE_HEX 16
  174. typedef uint8_t numeric_base_t;
  175. #ifdef RT_KLIBC_USING_VSNPRINTF_LONGLONG
  176. typedef unsigned long long printf_unsigned_value_t;
  177. typedef long long printf_signed_value_t;
  178. #else
  179. typedef unsigned long printf_unsigned_value_t;
  180. typedef long printf_signed_value_t;
  181. #endif
  182. // The printf()-family functions return an `int`; it is therefore
  183. // unnecessary/inappropriate to use size_t - often larger than int
  184. // in practice - for non-negative related values, such as widths,
  185. // precisions, offsets into buffers used for printing and the sizes
  186. // of these buffers. instead, we use:
  187. typedef unsigned int printf_size_t;
  188. #define PRINTF_MAX_POSSIBLE_BUFFER_SIZE INT_MAX
  189. // If we were to nitpick, this would actually be INT_MAX + 1,
  190. // since INT_MAX is the maximum return value, which excludes the
  191. // trailing '\0'.
  192. #if defined(RT_KLIBC_USING_VSNPRINTF_DECIMAL_SPECIFIERS) || defined(RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS)
  193. #include <float.h>
  194. #if FLT_RADIX != 2
  195. // cppcheck-suppress preprocessorErrorDirective
  196. #error "Non-binary-radix floating-point types are unsupported."
  197. #endif
  198. #if DBL_MANT_DIG == 24
  199. #define DOUBLE_SIZE_IN_BITS 32
  200. typedef uint32_t double_uint_t;
  201. #define DOUBLE_EXPONENT_MASK 0xFFU
  202. #define DOUBLE_BASE_EXPONENT 127
  203. #define DOUBLE_MAX_SUBNORMAL_EXPONENT_OF_10 -38
  204. #define DOUBLE_MAX_SUBNORMAL_POWER_OF_10 1e-38
  205. #elif DBL_MANT_DIG == 53
  206. #define DOUBLE_SIZE_IN_BITS 64
  207. typedef uint64_t double_uint_t;
  208. #define DOUBLE_EXPONENT_MASK 0x7FFU
  209. #define DOUBLE_BASE_EXPONENT 1023
  210. #define DOUBLE_MAX_SUBNORMAL_EXPONENT_OF_10 -308
  211. #define DOUBLE_MAX_SUBNORMAL_POWER_OF_10 ((double)1e-308L)
  212. #else
  213. #error "Unsupported double type configuration"
  214. #endif
  215. #define DOUBLE_STORED_MANTISSA_BITS (DBL_MANT_DIG - 1)
  216. typedef union {
  217. double_uint_t U;
  218. double F;
  219. } double_with_bit_access;
  220. // This is unnecessary in C99, since compound initializers can be used,
  221. // but:
  222. // 1. Some compilers are finicky about this;
  223. // 2. Some people may want to convert this to C89;
  224. // 3. If you try to use it as C++, only C++20 supports compound literals
  225. static inline double_with_bit_access get_bit_access(double x)
  226. {
  227. double_with_bit_access dwba;
  228. dwba.F = x;
  229. return dwba;
  230. }
  231. static inline int get_sign_bit(double x)
  232. {
  233. // The sign is stored in the highest bit
  234. return (int) (get_bit_access(x).U >> (DOUBLE_SIZE_IN_BITS - 1));
  235. }
  236. static inline int get_exp2(double_with_bit_access x)
  237. {
  238. // The exponent in an IEEE-754 floating-point number occupies a contiguous
  239. // sequence of bits (e.g. 52..62 for 64-bit doubles), but with a non-trivial representation: An
  240. // unsigned offset from some negative value (with the extremal offset values reserved for
  241. // special use).
  242. return (int)((x.U >> DOUBLE_STORED_MANTISSA_BITS ) & DOUBLE_EXPONENT_MASK) - DOUBLE_BASE_EXPONENT;
  243. }
  244. #define PRINTF_ABS(_x) ( (_x) > 0 ? (_x) : -(_x) )
  245. #endif // (RT_KLIBC_USING_VSNPRINTF_DECIMAL_SPECIFIERS || RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS)
  246. // Note in particular the behavior here on LONG_MIN or LLONG_MIN; it is valid
  247. // and well-defined, but if you're not careful you can easily trigger undefined
  248. // behavior with -LONG_MIN or -LLONG_MIN
  249. #define ABS_FOR_PRINTING(_x) ((printf_unsigned_value_t) ( (_x) > 0 ? (_x) : -((printf_signed_value_t)_x) ))
  250. // wrapper (used as buffer) for output function type
  251. //
  252. // One of the following must hold:
  253. // 1. max_chars is 0
  254. // 2. buffer is non-null
  255. // 3. function is non-null
  256. //
  257. // ... otherwise bad things will happen.
  258. typedef struct {
  259. void (*function)(char c, void* extra_arg);
  260. void* extra_function_arg;
  261. char* buffer;
  262. printf_size_t pos;
  263. printf_size_t max_chars;
  264. } output_gadget_t;
  265. // Note: This function currently assumes it is not passed a '\0' c,
  266. // or alternatively, that '\0' can be passed to the function in the output
  267. // gadget. The former assumption holds within the printf library. It also
  268. // assumes that the output gadget has been properly initialized.
  269. static inline void putchar_via_gadget(output_gadget_t* gadget, char c)
  270. {
  271. printf_size_t write_pos = gadget->pos++;
  272. // We're _always_ increasing pos, so as to count how may characters
  273. // _would_ have been written if not for the max_chars limitation
  274. if (write_pos >= gadget->max_chars) {
  275. return;
  276. }
  277. if (gadget->function != NULL) {
  278. // No check for c == '\0' .
  279. gadget->function(c, gadget->extra_function_arg);
  280. }
  281. else {
  282. // it must be the case that gadget->buffer != NULL , due to the constraint
  283. // on output_gadget_t ; and note we're relying on write_pos being non-negative.
  284. gadget->buffer[write_pos] = c;
  285. }
  286. }
  287. // Possibly-write the string-terminating '\0' character
  288. static inline void append_termination_with_gadget(output_gadget_t* gadget)
  289. {
  290. if (gadget->function != NULL || gadget->max_chars == 0) {
  291. return;
  292. }
  293. if (gadget->buffer == NULL) {
  294. return;
  295. }
  296. printf_size_t null_char_pos = gadget->pos < gadget->max_chars ? gadget->pos : gadget->max_chars - 1;
  297. gadget->buffer[null_char_pos] = '\0';
  298. }
  299. static inline output_gadget_t discarding_gadget(void)
  300. {
  301. output_gadget_t gadget;
  302. gadget.function = NULL;
  303. gadget.extra_function_arg = NULL;
  304. gadget.buffer = NULL;
  305. gadget.pos = 0;
  306. gadget.max_chars = 0;
  307. return gadget;
  308. }
  309. static inline output_gadget_t buffer_gadget(char* buffer, size_t buffer_size)
  310. {
  311. printf_size_t usable_buffer_size = (buffer_size > PRINTF_MAX_POSSIBLE_BUFFER_SIZE) ?
  312. PRINTF_MAX_POSSIBLE_BUFFER_SIZE : (printf_size_t) buffer_size;
  313. output_gadget_t result = discarding_gadget();
  314. if (buffer != NULL) {
  315. result.buffer = buffer;
  316. result.max_chars = usable_buffer_size;
  317. }
  318. return result;
  319. }
  320. // internal secure strlen
  321. // @return The length of the string (excluding the terminating 0) limited by 'maxsize'
  322. // @note strlen uses size_t, but wes only use this function with printf_size_t
  323. // variables - hence the signature.
  324. static inline printf_size_t strnlen_s_(const char* str, printf_size_t maxsize)
  325. {
  326. const char* s;
  327. for (s = str; *s && maxsize--; ++s);
  328. return (printf_size_t)(s - str);
  329. }
  330. // internal test if char is a digit (0-9)
  331. // @return true if char is a digit
  332. static inline bool is_digit_(char ch)
  333. {
  334. return (ch >= '0') && (ch <= '9');
  335. }
  336. // internal ASCII string to printf_size_t conversion
  337. static printf_size_t atou_(const char** str)
  338. {
  339. printf_size_t i = 0U;
  340. while (is_digit_(**str)) {
  341. i = i * 10U + (printf_size_t)(*((*str)++) - '0');
  342. }
  343. return i;
  344. }
  345. // output the specified string in reverse, taking care of any zero-padding
  346. static void out_rev_(output_gadget_t* output, const char* buf, printf_size_t len, printf_size_t width, printf_flags_t flags)
  347. {
  348. const printf_size_t start_pos = output->pos;
  349. // pad spaces up to given width
  350. if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) {
  351. for (printf_size_t i = len; i < width; i++) {
  352. putchar_via_gadget(output, ' ');
  353. }
  354. }
  355. // reverse string
  356. while (len) {
  357. putchar_via_gadget(output, buf[--len]);
  358. }
  359. // append pad spaces up to given width
  360. if (flags & FLAGS_LEFT) {
  361. while (output->pos - start_pos < width) {
  362. putchar_via_gadget(output, ' ');
  363. }
  364. }
  365. }
  366. // Invoked by print_integer after the actual number has been printed, performing necessary
  367. // work on the number's prefix (as the number is initially printed in reverse order)
  368. static void print_integer_finalization(output_gadget_t* output, char* buf, printf_size_t len, bool negative, numeric_base_t base, printf_size_t precision, printf_size_t width, printf_flags_t flags)
  369. {
  370. printf_size_t unpadded_len = len;
  371. // pad with leading zeros
  372. {
  373. if (!(flags & FLAGS_LEFT)) {
  374. if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {
  375. width--;
  376. }
  377. while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < RT_KLIBC_USING_VSNPRINTF_INTEGER_BUFFER_SIZE)) {
  378. buf[len++] = '0';
  379. }
  380. }
  381. while ((len < precision) && (len < RT_KLIBC_USING_VSNPRINTF_INTEGER_BUFFER_SIZE)) {
  382. buf[len++] = '0';
  383. }
  384. if (base == BASE_OCTAL && (len > unpadded_len)) {
  385. // Since we've written some zeros, we've satisfied the alternative format leading space requirement
  386. flags &= ~FLAGS_HASH;
  387. }
  388. }
  389. // handle hash
  390. if (flags & (FLAGS_HASH | FLAGS_POINTER)) {
  391. if (!(flags & FLAGS_PRECISION) && len && ((len == precision) || (len == width))) {
  392. // Let's take back some padding digits to fit in what will eventually
  393. // be the format-specific prefix
  394. if (unpadded_len < len) {
  395. len--; // This should suffice for BASE_OCTAL
  396. }
  397. if (len && (base == BASE_HEX || base == BASE_BINARY) && (unpadded_len < len)) {
  398. len--; // ... and an extra one for 0x or 0b
  399. }
  400. }
  401. if ((base == BASE_HEX) && !(flags & FLAGS_UPPERCASE) && (len < RT_KLIBC_USING_VSNPRINTF_INTEGER_BUFFER_SIZE)) {
  402. buf[len++] = 'x';
  403. }
  404. else if ((base == BASE_HEX) && (flags & FLAGS_UPPERCASE) && (len < RT_KLIBC_USING_VSNPRINTF_INTEGER_BUFFER_SIZE)) {
  405. buf[len++] = 'X';
  406. }
  407. else if ((base == BASE_BINARY) && (len < RT_KLIBC_USING_VSNPRINTF_INTEGER_BUFFER_SIZE)) {
  408. buf[len++] = 'b';
  409. }
  410. if (len < RT_KLIBC_USING_VSNPRINTF_INTEGER_BUFFER_SIZE) {
  411. buf[len++] = '0';
  412. }
  413. }
  414. if (len < RT_KLIBC_USING_VSNPRINTF_INTEGER_BUFFER_SIZE) {
  415. if (negative) {
  416. buf[len++] = '-';
  417. }
  418. else if (flags & FLAGS_PLUS) {
  419. buf[len++] = '+'; // ignore the space if the '+' exists
  420. }
  421. else if (flags & FLAGS_SPACE) {
  422. buf[len++] = ' ';
  423. }
  424. }
  425. out_rev_(output, buf, len, width, flags);
  426. }
  427. // An internal itoa-like function
  428. static void print_integer(output_gadget_t* output, printf_unsigned_value_t value, bool negative, numeric_base_t base, printf_size_t precision, printf_size_t width, printf_flags_t flags)
  429. {
  430. char buf[RT_KLIBC_USING_VSNPRINTF_INTEGER_BUFFER_SIZE];
  431. printf_size_t len = 0U;
  432. if (!value) {
  433. if ( !(flags & FLAGS_PRECISION) ) {
  434. buf[len++] = '0';
  435. flags &= ~FLAGS_HASH;
  436. // We drop this flag this since either the alternative and regular modes of the specifier
  437. // don't differ on 0 values, or (in the case of octal) we've already provided the special
  438. // handling for this mode.
  439. }
  440. else if (base == BASE_HEX) {
  441. flags &= ~FLAGS_HASH;
  442. // We drop this flag this since either the alternative and regular modes of the specifier
  443. // don't differ on 0 values
  444. }
  445. }
  446. else {
  447. do {
  448. const char digit = (char)(value % base);
  449. buf[len++] = (char)(digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10);
  450. value /= base;
  451. } while (value && (len < RT_KLIBC_USING_VSNPRINTF_INTEGER_BUFFER_SIZE));
  452. }
  453. print_integer_finalization(output, buf, len, negative, base, precision, width, flags);
  454. }
  455. #if defined(RT_KLIBC_USING_VSNPRINTF_DECIMAL_SPECIFIERS) || defined(RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS)
  456. // Stores a fixed-precision representation of a double relative
  457. // to a fixed precision (which cannot be determined by examining this structure)
  458. struct double_components {
  459. int_fast64_t integral;
  460. int_fast64_t fractional;
  461. // ... truncation of the actual fractional part of the double value, scaled
  462. // by the precision value
  463. bool is_negative;
  464. };
  465. #define NUM_DECIMAL_DIGITS_IN_INT64_T 18
  466. #define PRINTF_MAX_PRECOMPUTED_POWER_OF_10 NUM_DECIMAL_DIGITS_IN_INT64_T
  467. static const double powers_of_10[NUM_DECIMAL_DIGITS_IN_INT64_T] = {
  468. 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08,
  469. 1e09, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17
  470. };
  471. #define PRINTF_MAX_SUPPORTED_PRECISION NUM_DECIMAL_DIGITS_IN_INT64_T - 1
  472. // Break up a double number - which is known to be a finite non-negative number -
  473. // into its base-10 parts: integral - before the decimal point, and fractional - after it.
  474. // Taken the precision into account, but does not change it even internally.
  475. static struct double_components get_components(double number, printf_size_t precision)
  476. {
  477. struct double_components number_;
  478. number_.is_negative = get_sign_bit(number);
  479. double abs_number = (number_.is_negative) ? -number : number;
  480. number_.integral = (int_fast64_t)abs_number;
  481. double remainder = (abs_number - (double) number_.integral) * powers_of_10[precision];
  482. number_.fractional = (int_fast64_t)remainder;
  483. remainder -= (double) number_.fractional;
  484. if (remainder > 0.5) {
  485. ++number_.fractional;
  486. // handle rollover, e.g. case 0.99 with precision 1 is 1.0
  487. if ((double) number_.fractional >= powers_of_10[precision]) {
  488. number_.fractional = 0;
  489. ++number_.integral;
  490. }
  491. }
  492. else if ((remainder == 0.5) && ((number_.fractional == 0U) || (number_.fractional & 1U))) {
  493. // if halfway, round up if odd OR if last digit is 0
  494. ++number_.fractional;
  495. }
  496. if (precision == 0U) {
  497. remainder = abs_number - (double) number_.integral;
  498. if ((!(remainder < 0.5) || (remainder > 0.5)) && (number_.integral & 1)) {
  499. // exactly 0.5 and ODD, then round up
  500. // 1.5 -> 2, but 2.5 -> 2
  501. ++number_.integral;
  502. }
  503. }
  504. return number_;
  505. }
  506. #ifdef RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS
  507. struct scaling_factor {
  508. double raw_factor;
  509. bool multiply; // if true, need to multiply by raw_factor; otherwise need to divide by it
  510. };
  511. static double apply_scaling(double num, struct scaling_factor normalization)
  512. {
  513. return normalization.multiply ? num * normalization.raw_factor : num / normalization.raw_factor;
  514. }
  515. static double unapply_scaling(double normalized, struct scaling_factor normalization)
  516. {
  517. #if defined(__GNUC__) && !defined(__clang__) && !defined(__ARMCC_VERSION) /* GCC */
  518. // accounting for a static analysis bug in GCC 6.x and earlier
  519. #pragma GCC diagnostic push
  520. #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
  521. #endif
  522. return normalization.multiply ? normalized / normalization.raw_factor : normalized * normalization.raw_factor;
  523. #if defined(__GNUC__) && !defined(__clang__) && !defined(__ARMCC_VERSION) /* GCC */
  524. #pragma GCC diagnostic pop
  525. #endif
  526. }
  527. static struct scaling_factor update_normalization(struct scaling_factor sf, double extra_multiplicative_factor)
  528. {
  529. struct scaling_factor result;
  530. if (sf.multiply) {
  531. result.multiply = true;
  532. result.raw_factor = sf.raw_factor * extra_multiplicative_factor;
  533. }
  534. else {
  535. int factor_exp2 = get_exp2(get_bit_access(sf.raw_factor));
  536. int extra_factor_exp2 = get_exp2(get_bit_access(extra_multiplicative_factor));
  537. // Divide the larger-exponent raw raw_factor by the smaller
  538. if (PRINTF_ABS(factor_exp2) > PRINTF_ABS(extra_factor_exp2)) {
  539. result.multiply = false;
  540. result.raw_factor = sf.raw_factor / extra_multiplicative_factor;
  541. }
  542. else {
  543. result.multiply = true;
  544. result.raw_factor = extra_multiplicative_factor / sf.raw_factor;
  545. }
  546. }
  547. return result;
  548. }
  549. static struct double_components get_normalized_components(bool negative, printf_size_t precision, double non_normalized, struct scaling_factor normalization, int floored_exp10)
  550. {
  551. struct double_components components;
  552. components.is_negative = negative;
  553. double scaled = apply_scaling(non_normalized, normalization);
  554. bool close_to_representation_extremum = ( (-floored_exp10 + (int) precision) >= DBL_MAX_10_EXP - 1 );
  555. if (close_to_representation_extremum) {
  556. // We can't have a normalization factor which also accounts for the precision, i.e. moves
  557. // some decimal digits into the mantissa, since it's unrepresentable, or nearly unrepresentable.
  558. // So, we'll give up early on getting extra precision...
  559. return get_components(negative ? -scaled : scaled, precision);
  560. }
  561. components.integral = (int_fast64_t) scaled;
  562. double remainder = non_normalized - unapply_scaling((double) components.integral, normalization);
  563. double prec_power_of_10 = powers_of_10[precision];
  564. struct scaling_factor account_for_precision = update_normalization(normalization, prec_power_of_10);
  565. double scaled_remainder = apply_scaling(remainder, account_for_precision);
  566. double rounding_threshold = 0.5;
  567. components.fractional = (int_fast64_t) scaled_remainder; // when precision == 0, the assigned value should be 0
  568. scaled_remainder -= (double) components.fractional; //when precision == 0, this will not change scaled_remainder
  569. components.fractional += (scaled_remainder >= rounding_threshold);
  570. if (scaled_remainder == rounding_threshold) {
  571. // banker's rounding: Round towards the even number (making the mean error 0)
  572. components.fractional &= ~((int_fast64_t) 0x1);
  573. }
  574. // handle rollover, e.g. the case of 0.99 with precision 1 becoming (0,100),
  575. // and must then be corrected into (1, 0).
  576. // Note: for precision = 0, this will "translate" the rounding effect from
  577. // the fractional part to the integral part where it should actually be
  578. // felt (as prec_power_of_10 is 1)
  579. if ((double) components.fractional >= prec_power_of_10) {
  580. components.fractional = 0;
  581. ++components.integral;
  582. }
  583. return components;
  584. }
  585. #endif // RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS
  586. static void print_broken_up_decimal(
  587. struct double_components number_, output_gadget_t* output, printf_size_t precision,
  588. printf_size_t width, printf_flags_t flags, char *buf, printf_size_t len)
  589. {
  590. if (precision != 0U) {
  591. // do fractional part, as an unsigned number
  592. printf_size_t count = precision;
  593. // %g/%G mandates we skip the trailing 0 digits...
  594. if ((flags & FLAGS_ADAPT_EXP) && !(flags & FLAGS_HASH) && (number_.fractional > 0)) {
  595. while(true) {
  596. int_fast64_t digit = number_.fractional % 10U;
  597. if (digit != 0) {
  598. break;
  599. }
  600. --count;
  601. number_.fractional /= 10U;
  602. }
  603. // ... and even the decimal point if there are no
  604. // non-zero fractional part digits (see below)
  605. }
  606. if (number_.fractional > 0 || !(flags & FLAGS_ADAPT_EXP) || (flags & FLAGS_HASH) ) {
  607. while (len < RT_KLIBC_USING_VSNPRINTF_DECIMAL_BUFFER_SIZE) {
  608. --count;
  609. buf[len++] = (char)('0' + number_.fractional % 10U);
  610. if (!(number_.fractional /= 10U)) {
  611. break;
  612. }
  613. }
  614. // add extra 0s
  615. while ((len < RT_KLIBC_USING_VSNPRINTF_DECIMAL_BUFFER_SIZE) && (count > 0U)) {
  616. buf[len++] = '0';
  617. --count;
  618. }
  619. if (len < RT_KLIBC_USING_VSNPRINTF_DECIMAL_BUFFER_SIZE) {
  620. buf[len++] = '.';
  621. }
  622. }
  623. }
  624. else {
  625. if ((flags & FLAGS_HASH) && (len < RT_KLIBC_USING_VSNPRINTF_DECIMAL_BUFFER_SIZE)) {
  626. buf[len++] = '.';
  627. }
  628. }
  629. // Write the integer part of the number (it comes after the fractional
  630. // since the character order is reversed)
  631. while (len < RT_KLIBC_USING_VSNPRINTF_DECIMAL_BUFFER_SIZE) {
  632. buf[len++] = (char)('0' + (number_.integral % 10));
  633. if (!(number_.integral /= 10)) {
  634. break;
  635. }
  636. }
  637. // pad leading zeros
  638. if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) {
  639. if (width && (number_.is_negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {
  640. width--;
  641. }
  642. while ((len < width) && (len < RT_KLIBC_USING_VSNPRINTF_DECIMAL_BUFFER_SIZE)) {
  643. buf[len++] = '0';
  644. }
  645. }
  646. if (len < RT_KLIBC_USING_VSNPRINTF_DECIMAL_BUFFER_SIZE) {
  647. if (number_.is_negative) {
  648. buf[len++] = '-';
  649. }
  650. else if (flags & FLAGS_PLUS) {
  651. buf[len++] = '+'; // ignore the space if the '+' exists
  652. }
  653. else if (flags & FLAGS_SPACE) {
  654. buf[len++] = ' ';
  655. }
  656. }
  657. out_rev_(output, buf, len, width, flags);
  658. }
  659. // internal ftoa for fixed decimal floating point
  660. static void print_decimal_number(output_gadget_t* output, double number, printf_size_t precision, printf_size_t width, printf_flags_t flags, char* buf, printf_size_t len)
  661. {
  662. struct double_components value_ = get_components(number, precision);
  663. print_broken_up_decimal(value_, output, precision, width, flags, buf, len);
  664. }
  665. #ifdef RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS
  666. // A floor function - but one which only works for numbers whose
  667. // floor value is representable by an int.
  668. static int bastardized_floor(double x)
  669. {
  670. if (x >= 0) { return (int) x; }
  671. int n = (int) x;
  672. return ( ((double) n) == x ) ? n : n-1;
  673. }
  674. // Computes the base-10 logarithm of the input number - which must be an actual
  675. // positive number (not infinity or NaN, nor a sub-normal)
  676. static double log10_of_positive(double positive_number)
  677. {
  678. // The implementation follows David Gay (https://www.ampl.com/netlib/fp/dtoa.c).
  679. //
  680. // Since log_10 ( M * 2^x ) = log_10(M) + x , we can separate the components of
  681. // our input number, and need only solve log_10(M) for M between 1 and 2 (as
  682. // the base-2 mantissa is always 1-point-something). In that limited range, a
  683. // Taylor series expansion of log10(x) should serve us well enough; and we'll
  684. // take the mid-point, 1.5, as the point of expansion.
  685. double_with_bit_access dwba = get_bit_access(positive_number);
  686. // based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c)
  687. int exp2 = get_exp2(dwba);
  688. // drop the exponent, so dwba.F comes into the range [1,2)
  689. dwba.U = (dwba.U & (((double_uint_t) (1) << DOUBLE_STORED_MANTISSA_BITS) - 1U)) |
  690. ((double_uint_t) DOUBLE_BASE_EXPONENT << DOUBLE_STORED_MANTISSA_BITS);
  691. double z = (dwba.F - 1.5);
  692. return (
  693. // Taylor expansion around 1.5:
  694. 0.1760912590556812420 // Expansion term 0: ln(1.5) / ln(10)
  695. + z * 0.2895296546021678851 // Expansion term 1: (M - 1.5) * 2/3 / ln(10)
  696. #if RT_KLIBC_USING_VSNPRINTF_LOG10_TAYLOR_TERMS > 2
  697. - z*z * 0.0965098848673892950 // Expansion term 2: (M - 1.5)^2 * 2/9 / ln(10)
  698. #if RT_KLIBC_USING_VSNPRINTF_LOG10_TAYLOR_TERMS > 3
  699. + z*z*z * 0.0428932821632841311 // Expansion term 2: (M - 1.5)^3 * 8/81 / ln(10)
  700. #endif
  701. #endif
  702. // exact log_2 of the exponent x, with logarithm base change
  703. + exp2 * 0.30102999566398119521 // = exp2 * log_10(2) = exp2 * ln(2)/ln(10)
  704. );
  705. }
  706. static double pow10_of_int(int floored_exp10)
  707. {
  708. // A crude hack for avoiding undesired behavior with barely-normal or slightly-subnormal values.
  709. if (floored_exp10 == DOUBLE_MAX_SUBNORMAL_EXPONENT_OF_10) {
  710. return DOUBLE_MAX_SUBNORMAL_POWER_OF_10;
  711. }
  712. // Compute 10^(floored_exp10) but (try to) make sure that doesn't overflow
  713. double_with_bit_access dwba;
  714. int exp2 = bastardized_floor(floored_exp10 * 3.321928094887362 + 0.5);
  715. const double z = floored_exp10 * 2.302585092994046 - exp2 * 0.6931471805599453;
  716. const double z2 = z * z;
  717. dwba.U = ((double_uint_t)(exp2) + DOUBLE_BASE_EXPONENT) << DOUBLE_STORED_MANTISSA_BITS;
  718. // compute exp(z) using continued fractions,
  719. // see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex
  720. dwba.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14)))));
  721. return dwba.F;
  722. }
  723. static void print_exponential_number(output_gadget_t* output, double number, printf_size_t precision, printf_size_t width, printf_flags_t flags, char* buf, printf_size_t len)
  724. {
  725. const bool negative = get_sign_bit(number);
  726. // This number will decrease gradually (by factors of 10) as we "extract" the exponent out of it
  727. double abs_number = negative ? -number : number;
  728. int floored_exp10;
  729. bool abs_exp10_covered_by_powers_table;
  730. struct scaling_factor normalization;
  731. // Determine the decimal exponent
  732. if (abs_number == 0.0) {
  733. // TODO: This is a special-case for 0.0 (and -0.0); but proper handling is required for denormals more generally.
  734. floored_exp10 = 0; // ... and no need to set a normalization factor or check the powers table
  735. }
  736. else {
  737. double exp10 = log10_of_positive(abs_number);
  738. floored_exp10 = bastardized_floor(exp10);
  739. double p10 = pow10_of_int(floored_exp10);
  740. // correct for rounding errors
  741. if (abs_number < p10) {
  742. floored_exp10--;
  743. p10 /= 10;
  744. }
  745. abs_exp10_covered_by_powers_table = PRINTF_ABS(floored_exp10) < PRINTF_MAX_PRECOMPUTED_POWER_OF_10;
  746. normalization.raw_factor = abs_exp10_covered_by_powers_table ? powers_of_10[PRINTF_ABS(floored_exp10)] : p10;
  747. }
  748. // We now begin accounting for the widths of the two parts of our printed field:
  749. // the decimal part after decimal exponent extraction, and the base-10 exponent part.
  750. // For both of these, the value of 0 has a special meaning, but not the same one:
  751. // a 0 exponent-part width means "don't print the exponent"; a 0 decimal-part width
  752. // means "use as many characters as necessary".
  753. bool fall_back_to_decimal_only_mode = false;
  754. if (flags & FLAGS_ADAPT_EXP) {
  755. int required_significant_digits = (precision == 0) ? 1 : (int) precision;
  756. // Should we want to fall-back to "%f" mode, and only print the decimal part?
  757. fall_back_to_decimal_only_mode = (floored_exp10 >= -4 && floored_exp10 < required_significant_digits);
  758. // Now, let's adjust the precision
  759. // This also decided how we adjust the precision value - as in "%g" mode,
  760. // "precision" is the number of _significant digits_, and this is when we "translate"
  761. // the precision value to an actual number of decimal digits.
  762. int precision_ = fall_back_to_decimal_only_mode ?
  763. (int) precision - 1 - floored_exp10 :
  764. (int) precision - 1; // the presence of the exponent ensures only one significant digit comes before the decimal point
  765. precision = (precision_ > 0 ? (unsigned) precision_ : 0U);
  766. flags |= FLAGS_PRECISION; // make sure print_broken_up_decimal respects our choice above
  767. }
  768. normalization.multiply = (floored_exp10 < 0 && abs_exp10_covered_by_powers_table);
  769. bool should_skip_normalization = (fall_back_to_decimal_only_mode || floored_exp10 == 0);
  770. struct double_components decimal_part_components =
  771. should_skip_normalization ?
  772. get_components(negative ? -abs_number : abs_number, precision) :
  773. get_normalized_components(negative, precision, abs_number, normalization, floored_exp10);
  774. // Account for roll-over, e.g. rounding from 9.99 to 100.0 - which effects
  775. // the exponent and may require additional tweaking of the parts
  776. if (fall_back_to_decimal_only_mode) {
  777. if ((flags & FLAGS_ADAPT_EXP) && floored_exp10 >= -1 && decimal_part_components.integral == powers_of_10[floored_exp10 + 1]) {
  778. floored_exp10++; // Not strictly necessary, since floored_exp10 is no longer really used
  779. precision--;
  780. // ... and it should already be the case that decimal_part_components.fractional == 0
  781. }
  782. // TODO: What about rollover strictly within the fractional part?
  783. }
  784. else {
  785. if (decimal_part_components.integral >= 10) {
  786. floored_exp10++;
  787. decimal_part_components.integral = 1;
  788. decimal_part_components.fractional = 0;
  789. }
  790. }
  791. // the floored_exp10 format is "E%+03d" and largest possible floored_exp10 value for a 64-bit double
  792. // is "307" (for 2^1023), so we set aside 4-5 characters overall
  793. printf_size_t exp10_part_width = fall_back_to_decimal_only_mode ? 0U : (PRINTF_ABS(floored_exp10) < 100) ? 4U : 5U;
  794. printf_size_t decimal_part_width =
  795. ((flags & FLAGS_LEFT) && exp10_part_width) ?
  796. // We're padding on the right, so the width constraint is the exponent part's
  797. // problem, not the decimal part's, so we'll use as many characters as we need:
  798. 0U :
  799. // We're padding on the left; so the width constraint is the decimal part's
  800. // problem. Well, can both the decimal part and the exponent part fit within our overall width?
  801. ((width > exp10_part_width) ?
  802. // Yes, so we limit our decimal part's width.
  803. // (Note this is trivially valid even if we've fallen back to "%f" mode)
  804. width - exp10_part_width :
  805. // No; we just give up on any restriction on the decimal part and use as many
  806. // characters as we need
  807. 0U);
  808. const printf_size_t printed_exponential_start_pos = output->pos;
  809. print_broken_up_decimal(decimal_part_components, output, precision, decimal_part_width, flags, buf, len);
  810. if (! fall_back_to_decimal_only_mode) {
  811. putchar_via_gadget(output, (flags & FLAGS_UPPERCASE) ? 'E' : 'e');
  812. print_integer(output,
  813. ABS_FOR_PRINTING(floored_exp10),
  814. floored_exp10 < 0, 10, 0, exp10_part_width - 1,
  815. FLAGS_ZEROPAD | FLAGS_PLUS);
  816. if (flags & FLAGS_LEFT) {
  817. // We need to right-pad with spaces to meet the width requirement
  818. while (output->pos - printed_exponential_start_pos < width) {
  819. putchar_via_gadget(output, ' ');
  820. }
  821. }
  822. }
  823. }
  824. #endif // RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS
  825. static void print_floating_point(output_gadget_t* output, double value, printf_size_t precision, printf_size_t width, printf_flags_t flags, bool prefer_exponential)
  826. {
  827. char buf[RT_KLIBC_USING_VSNPRINTF_DECIMAL_BUFFER_SIZE];
  828. printf_size_t len = 0U;
  829. // test for special values
  830. if (value != value) {
  831. out_rev_(output, "nan", 3, width, flags);
  832. return;
  833. }
  834. if (value < -DBL_MAX) {
  835. out_rev_(output, "fni-", 4, width, flags);
  836. return;
  837. }
  838. if (value > DBL_MAX) {
  839. out_rev_(output, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags);
  840. return;
  841. }
  842. if (!prefer_exponential &&
  843. ((value > PRINTF_FLOAT_NOTATION_THRESHOLD) || (value < -PRINTF_FLOAT_NOTATION_THRESHOLD))) {
  844. // The required behavior of standard printf is to print _every_ integral-part digit -- which could mean
  845. // printing hundreds of characters, overflowing any fixed internal buffer and necessitating a more complicated
  846. // implementation.
  847. #ifdef RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS
  848. print_exponential_number(output, value, precision, width, flags, buf, len);
  849. #endif
  850. return;
  851. }
  852. // set default precision, if not set explicitly
  853. if (!(flags & FLAGS_PRECISION)) {
  854. precision = RT_KLIBC_USING_VSNPRINTF_FLOAT_PRECISION;
  855. }
  856. // limit precision so that our integer holding the fractional part does not overflow
  857. while ((len < RT_KLIBC_USING_VSNPRINTF_DECIMAL_BUFFER_SIZE) && (precision > PRINTF_MAX_SUPPORTED_PRECISION)) {
  858. buf[len++] = '0'; // This respects the precision in terms of result length only
  859. precision--;
  860. }
  861. #ifdef RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS
  862. if (prefer_exponential)
  863. print_exponential_number(output, value, precision, width, flags, buf, len);
  864. else
  865. #endif
  866. print_decimal_number(output, value, precision, width, flags, buf, len);
  867. }
  868. #endif // (RT_KLIBC_USING_VSNPRINTF_DECIMAL_SPECIFIERS || RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS)
  869. // Advances the format pointer past the flags, and returns the parsed flags
  870. // due to the characters passed
  871. static printf_flags_t parse_flags(const char** format)
  872. {
  873. printf_flags_t flags = 0U;
  874. do {
  875. switch (**format) {
  876. case '0': flags |= FLAGS_ZEROPAD; (*format)++; break;
  877. case '-': flags |= FLAGS_LEFT; (*format)++; break;
  878. case '+': flags |= FLAGS_PLUS; (*format)++; break;
  879. case ' ': flags |= FLAGS_SPACE; (*format)++; break;
  880. case '#': flags |= FLAGS_HASH; (*format)++; break;
  881. default : return flags;
  882. }
  883. } while (true);
  884. }
  885. static inline void format_string_loop(output_gadget_t* output, const char* format, va_list args)
  886. {
  887. #ifdef RT_KLIBC_USING_VSNPRINTF_CHECK_NUL_IN_FORMAT_SPECIFIER
  888. #define ADVANCE_IN_FORMAT_STRING(cptr_) do { (cptr_)++; if (!*(cptr_)) return; } while(0)
  889. #else
  890. #define ADVANCE_IN_FORMAT_STRING(cptr_) (cptr_)++
  891. #endif
  892. while (*format)
  893. {
  894. if (*format != '%') {
  895. // A regular content character
  896. putchar_via_gadget(output, *format);
  897. format++;
  898. continue;
  899. }
  900. // We're parsing a format specifier: %[flags][width][.precision][length]
  901. ADVANCE_IN_FORMAT_STRING(format);
  902. printf_flags_t flags = parse_flags(&format);
  903. // evaluate width field
  904. printf_size_t width = 0U;
  905. if (is_digit_(*format)) {
  906. width = (printf_size_t) atou_(&format);
  907. }
  908. else if (*format == '*') {
  909. const int w = va_arg(args, int);
  910. if (w < 0) {
  911. flags |= FLAGS_LEFT; // reverse padding
  912. width = (printf_size_t)-w;
  913. }
  914. else {
  915. width = (printf_size_t)w;
  916. }
  917. ADVANCE_IN_FORMAT_STRING(format);
  918. }
  919. // evaluate precision field
  920. printf_size_t precision = 0U;
  921. if (*format == '.') {
  922. flags |= FLAGS_PRECISION;
  923. ADVANCE_IN_FORMAT_STRING(format);
  924. if (is_digit_(*format)) {
  925. precision = (printf_size_t) atou_(&format);
  926. }
  927. else if (*format == '*') {
  928. const int precision_ = va_arg(args, int);
  929. precision = precision_ > 0 ? (printf_size_t) precision_ : 0U;
  930. ADVANCE_IN_FORMAT_STRING(format);
  931. }
  932. }
  933. // evaluate length field
  934. switch (*format) {
  935. #ifdef RT_KLIBC_USING_VSNPRINTF_MSVC_STYLE_INTEGER_SPECIFIERS
  936. case 'I' : {
  937. ADVANCE_IN_FORMAT_STRING(format);
  938. // Greedily parse for size in bits: 8, 16, 32 or 64
  939. switch(*format) {
  940. case '8': flags |= FLAGS_INT8;
  941. ADVANCE_IN_FORMAT_STRING(format);
  942. break;
  943. case '1':
  944. ADVANCE_IN_FORMAT_STRING(format);
  945. if (*format == '6') { format++; flags |= FLAGS_INT16; }
  946. break;
  947. case '3':
  948. ADVANCE_IN_FORMAT_STRING(format);
  949. if (*format == '2') { ADVANCE_IN_FORMAT_STRING(format); flags |= FLAGS_INT32; }
  950. break;
  951. case '6':
  952. ADVANCE_IN_FORMAT_STRING(format);
  953. if (*format == '4') { ADVANCE_IN_FORMAT_STRING(format); flags |= FLAGS_INT64; }
  954. break;
  955. default: break;
  956. }
  957. break;
  958. }
  959. #endif
  960. case 'l' :
  961. flags |= FLAGS_LONG;
  962. ADVANCE_IN_FORMAT_STRING(format);
  963. if (*format == 'l') {
  964. flags |= FLAGS_LONG_LONG;
  965. ADVANCE_IN_FORMAT_STRING(format);
  966. }
  967. break;
  968. case 'h' :
  969. flags |= FLAGS_SHORT;
  970. ADVANCE_IN_FORMAT_STRING(format);
  971. if (*format == 'h') {
  972. flags |= FLAGS_CHAR;
  973. ADVANCE_IN_FORMAT_STRING(format);
  974. }
  975. break;
  976. case 't' :
  977. flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
  978. ADVANCE_IN_FORMAT_STRING(format);
  979. break;
  980. case 'j' :
  981. flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
  982. ADVANCE_IN_FORMAT_STRING(format);
  983. break;
  984. case 'z' :
  985. flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
  986. ADVANCE_IN_FORMAT_STRING(format);
  987. break;
  988. default:
  989. break;
  990. }
  991. // evaluate specifier
  992. switch (*format) {
  993. case 'd' :
  994. case 'i' :
  995. case 'u' :
  996. case 'x' :
  997. case 'X' :
  998. case 'o' :
  999. case 'b' : {
  1000. if (*format == 'd' || *format == 'i') {
  1001. flags |= FLAGS_SIGNED;
  1002. }
  1003. numeric_base_t base;
  1004. if (*format == 'x' || *format == 'X') {
  1005. base = BASE_HEX;
  1006. }
  1007. else if (*format == 'o') {
  1008. base = BASE_OCTAL;
  1009. }
  1010. else if (*format == 'b') {
  1011. base = BASE_BINARY;
  1012. }
  1013. else {
  1014. base = BASE_DECIMAL;
  1015. flags &= ~FLAGS_HASH; // decimal integers have no alternative presentation
  1016. }
  1017. if (*format == 'X') {
  1018. flags |= FLAGS_UPPERCASE;
  1019. }
  1020. format++;
  1021. // ignore '0' flag when precision is given
  1022. if (flags & FLAGS_PRECISION) {
  1023. flags &= ~FLAGS_ZEROPAD;
  1024. }
  1025. if (flags & FLAGS_SIGNED) {
  1026. // A signed specifier: d, i or possibly I + bit size if enabled
  1027. if (flags & FLAGS_LONG_LONG) {
  1028. #ifdef RT_KLIBC_USING_VSNPRINTF_LONGLONG
  1029. const long long value = va_arg(args, long long);
  1030. print_integer(output, ABS_FOR_PRINTING(value), value < 0, base, precision, width, flags);
  1031. #endif
  1032. }
  1033. else if (flags & FLAGS_LONG) {
  1034. const long value = va_arg(args, long);
  1035. print_integer(output, ABS_FOR_PRINTING(value), value < 0, base, precision, width, flags);
  1036. }
  1037. else {
  1038. // We never try to interpret the argument as something potentially-smaller than int,
  1039. // due to integer promotion rules: Even if the user passed a short int, short unsigned
  1040. // etc. - these will come in after promotion, as int's (or unsigned for the case of
  1041. // short unsigned when it has the same size as int)
  1042. const int value =
  1043. (flags & FLAGS_CHAR) ? (signed char) va_arg(args, int) :
  1044. (flags & FLAGS_SHORT) ? (short int) va_arg(args, int) :
  1045. va_arg(args, int);
  1046. print_integer(output, ABS_FOR_PRINTING(value), value < 0, base, precision, width, flags);
  1047. }
  1048. }
  1049. else {
  1050. // An unsigned specifier: u, x, X, o, b
  1051. flags &= ~(FLAGS_PLUS | FLAGS_SPACE);
  1052. if (flags & FLAGS_LONG_LONG) {
  1053. #ifdef RT_KLIBC_USING_VSNPRINTF_LONGLONG
  1054. print_integer(output, (printf_unsigned_value_t) va_arg(args, unsigned long long), false, base, precision, width, flags);
  1055. #endif
  1056. }
  1057. else if (flags & FLAGS_LONG) {
  1058. print_integer(output, (printf_unsigned_value_t) va_arg(args, unsigned long), false, base, precision, width, flags);
  1059. }
  1060. else {
  1061. const unsigned int value =
  1062. (flags & FLAGS_CHAR) ? (unsigned char)va_arg(args, unsigned int) :
  1063. (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(args, unsigned int) :
  1064. va_arg(args, unsigned int);
  1065. print_integer(output, (printf_unsigned_value_t) value, false, base, precision, width, flags);
  1066. }
  1067. }
  1068. break;
  1069. }
  1070. #ifdef RT_KLIBC_USING_VSNPRINTF_DECIMAL_SPECIFIERS
  1071. case 'f' :
  1072. case 'F' :
  1073. if (*format == 'F') flags |= FLAGS_UPPERCASE;
  1074. print_floating_point(output, va_arg(args, double), precision, width, flags, PRINTF_PREFER_DECIMAL);
  1075. format++;
  1076. break;
  1077. #endif
  1078. #ifdef RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS
  1079. case 'e':
  1080. case 'E':
  1081. case 'g':
  1082. case 'G':
  1083. if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP;
  1084. if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE;
  1085. print_floating_point(output, va_arg(args, double), precision, width, flags, PRINTF_PREFER_EXPONENTIAL);
  1086. format++;
  1087. break;
  1088. #endif // RT_KLIBC_USING_VSNPRINTF_EXPONENTIAL_SPECIFIERS
  1089. case 'c' : {
  1090. printf_size_t l = 1U;
  1091. // pre padding
  1092. if (!(flags & FLAGS_LEFT)) {
  1093. while (l++ < width) {
  1094. putchar_via_gadget(output, ' ');
  1095. }
  1096. }
  1097. // char output
  1098. putchar_via_gadget(output, (char) va_arg(args, int) );
  1099. // post padding
  1100. if (flags & FLAGS_LEFT) {
  1101. while (l++ < width) {
  1102. putchar_via_gadget(output, ' ');
  1103. }
  1104. }
  1105. format++;
  1106. break;
  1107. }
  1108. case 's' : {
  1109. const char* p = va_arg(args, char*);
  1110. if (p == NULL) {
  1111. out_rev_(output, ")llun(", 6, width, flags);
  1112. }
  1113. else {
  1114. printf_size_t l = strnlen_s_(p, precision ? precision : PRINTF_MAX_POSSIBLE_BUFFER_SIZE);
  1115. // pre padding
  1116. if (flags & FLAGS_PRECISION) {
  1117. l = (l < precision ? l : precision);
  1118. }
  1119. if (!(flags & FLAGS_LEFT)) {
  1120. while (l++ < width) {
  1121. putchar_via_gadget(output, ' ');
  1122. }
  1123. }
  1124. // string output
  1125. while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision)) {
  1126. putchar_via_gadget(output, *(p++));
  1127. --precision;
  1128. }
  1129. // post padding
  1130. if (flags & FLAGS_LEFT) {
  1131. while (l++ < width) {
  1132. putchar_via_gadget(output, ' ');
  1133. }
  1134. }
  1135. }
  1136. format++;
  1137. break;
  1138. }
  1139. case 'p' : {
  1140. width = sizeof(void*) * 2U + 2; // 2 hex chars per byte + the "0x" prefix
  1141. flags |= FLAGS_ZEROPAD | FLAGS_POINTER;
  1142. uintptr_t value = (uintptr_t)va_arg(args, void*);
  1143. (value == (uintptr_t) NULL) ?
  1144. out_rev_(output, ")lin(", 5, width, flags) :
  1145. print_integer(output, (printf_unsigned_value_t) value, false, BASE_HEX, precision, width, flags);
  1146. format++;
  1147. break;
  1148. }
  1149. case '%' :
  1150. putchar_via_gadget(output, '%');
  1151. format++;
  1152. break;
  1153. // Many people prefer to disable support for %n, as it lets the caller
  1154. // engineer a write to an arbitrary location, of a value the caller
  1155. // effectively controls - which could be a security concern in some cases.
  1156. #ifdef RT_KLIBC_USING_VSNPRINTF_WRITEBACK_SPECIFIER
  1157. case 'n' : {
  1158. if (flags & FLAGS_CHAR) *(va_arg(args, char*)) = (char) output->pos;
  1159. else if (flags & FLAGS_SHORT) *(va_arg(args, short*)) = (short) output->pos;
  1160. else if (flags & FLAGS_LONG) *(va_arg(args, long*)) = (long) output->pos;
  1161. #ifdef RT_KLIBC_USING_VSNPRINTF_LONGLONG
  1162. else if (flags & FLAGS_LONG_LONG) *(va_arg(args, long long*)) = (long long int) output->pos;
  1163. #endif // RT_KLIBC_USING_VSNPRINTF_LONGLONG
  1164. else *(va_arg(args, int*)) = (int) output->pos;
  1165. format++;
  1166. break;
  1167. }
  1168. #endif // RT_KLIBC_USING_VSNPRINTF_WRITEBACK_SPECIFIER
  1169. default :
  1170. putchar_via_gadget(output, *format);
  1171. format++;
  1172. break;
  1173. }
  1174. }
  1175. }
  1176. // internal vsnprintf - used for implementing _all library functions
  1177. static int vsnprintf_impl(output_gadget_t* output, const char* format, va_list args)
  1178. {
  1179. // Note: The library only calls vsnprintf_impl() with output->pos being 0. However, it is
  1180. // possible to call this function with a non-zero pos value for some "remedial printing".
  1181. format_string_loop(output, format, args);
  1182. // termination
  1183. append_termination_with_gadget(output);
  1184. // return written chars without terminating \0
  1185. return (int)output->pos;
  1186. }
  1187. ///////////////////////////////////////////////////////////////////////////////
  1188. /**
  1189. * @brief This function will fill a formatted string to buffer.
  1190. *
  1191. * @param buf is the buffer to save formatted string.
  1192. *
  1193. * @param size is the size of buffer.
  1194. *
  1195. * @param fmt is the format parameters.
  1196. *
  1197. * @param args is a list of variable parameters.
  1198. *
  1199. * @return The number of characters actually written to buffer.
  1200. */
  1201. int rt_vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
  1202. {
  1203. output_gadget_t gadget = buffer_gadget(buf, size);
  1204. return vsnprintf_impl(&gadget, fmt, args);
  1205. }