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