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