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/platform.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, 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, 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), 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), 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++] = 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++] = 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 exp2 = (int) ((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2
494 conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2)
495 // now approximate log10 from the log2 integer part and an expansion of ln around 1.5
496 int expval = (int) (0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168);
497 // now we want to compute 10^expval but we want to be sure it won't overflow
498 exp2 = (int) (expval * 3.321928094887362 + 0.5);
499 const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453;
500 const double z2 = z * z;
501 conv.U = (uint64_t) (exp2 + 1023) << 52U;
502 // compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex
503 conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14)))));
504 // correct for rounding errors
505 if (value < conv.F) {
506 expval--;
507 conv.F /= 10;
508 }
509
510 // the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters
511 unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U;
512
513 // in "%g" mode, "prec" is the number of *significant figures* not decimals
514 if (flags & FLAGS_ADAPT_EXP) {
515 // do we want to fall-back to "%f" mode?
516 if ((value >= 1e-4) && (value < 1e6)) {
517 if ((int) prec > expval) {
518 prec = (unsigned) ((int) prec - expval - 1);
519 } else {
520 prec = 0;
521 }
522 flags |= FLAGS_PRECISION; // make sure _ftoa respects precision
523 // no characters in exponent
524 minwidth = 0U;
525 expval = 0;
526 } else {
527 // we use one sigfig for the whole part
528 if ((prec > 0) && (flags & FLAGS_PRECISION)) {
529 --prec;
530 }
531 }
532 }
533
534 // will everything fit?
535 unsigned int fwidth = width;
536 if (width > minwidth) {
537 // we didn't fall-back so subtract the characters required for the exponent
538 fwidth -= minwidth;
539 } else {
540 // not enough characters, so go back to default sizing
541 fwidth = 0U;
542 }
543 if ((flags & FLAGS_LEFT) && minwidth) {
544 // if we're padding on the right, DON'T pad the floating part
545 fwidth = 0U;
546 }
547
548 // rescale the float value
549 if (expval) {
550 value /= conv.F;
551 }
552
553 // output the floating part
554 const size_t start_idx = idx;
555 idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP);
556
557 // output the exponent part
558 if (minwidth) {
559 // output the exponential symbol
560 out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen);
561 // output the exponent value
562 idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth - 1,
563 FLAGS_ZEROPAD | FLAGS_PLUS);
564 // might need to right-pad spaces
565 if (flags & FLAGS_LEFT) {
566 while (idx - start_idx < width) out(' ', buffer, idx++, maxlen);
567 }
568 }
569 return idx;
570 }
571
572 #endif // PICO_PRINTF_SUPPORT_EXPONENTIAL
573 #endif // PICO_PRINTF_SUPPORT_FLOAT
574
575 // internal vsnprintf
_vsnprintf(out_fct_type out,char * buffer,const size_t maxlen,const char * format,va_list va)576 static int _vsnprintf(out_fct_type out, char *buffer, const size_t maxlen, const char *format, va_list va) {
577 #if !PICO_PRINTF_ALWAYS_INCLUDED
578 lazy_vsnprintf = _vsnprintf;
579 #endif
580 unsigned int flags, width, precision, n;
581 size_t idx = 0U;
582
583 if (!buffer) {
584 // use null output function
585 out = _out_null;
586 }
587
588 while (*format) {
589 // format specifier? %[flags][width][.precision][length]
590 if (*format != '%') {
591 // no
592 out(*format, buffer, idx++, maxlen);
593 format++;
594 continue;
595 } else {
596 // yes, evaluate it
597 format++;
598 }
599
600 // evaluate flags
601 flags = 0U;
602 do {
603 switch (*format) {
604 case '0':
605 flags |= FLAGS_ZEROPAD;
606 format++;
607 n = 1U;
608 break;
609 case '-':
610 flags |= FLAGS_LEFT;
611 format++;
612 n = 1U;
613 break;
614 case '+':
615 flags |= FLAGS_PLUS;
616 format++;
617 n = 1U;
618 break;
619 case ' ':
620 flags |= FLAGS_SPACE;
621 format++;
622 n = 1U;
623 break;
624 case '#':
625 flags |= FLAGS_HASH;
626 format++;
627 n = 1U;
628 break;
629 default :
630 n = 0U;
631 break;
632 }
633 } while (n);
634
635 // evaluate width field
636 width = 0U;
637 if (_is_digit(*format)) {
638 width = _atoi(&format);
639 } else if (*format == '*') {
640 const int w = va_arg(va, int);
641 if (w < 0) {
642 flags |= FLAGS_LEFT; // reverse padding
643 width = (unsigned int) -w;
644 } else {
645 width = (unsigned int) w;
646 }
647 format++;
648 }
649
650 // evaluate precision field
651 precision = 0U;
652 if (*format == '.') {
653 flags |= FLAGS_PRECISION;
654 format++;
655 if (_is_digit(*format)) {
656 precision = _atoi(&format);
657 } else if (*format == '*') {
658 const int prec = (int) va_arg(va, int);
659 precision = prec > 0 ? (unsigned int) prec : 0U;
660 format++;
661 }
662 }
663
664 // evaluate length field
665 switch (*format) {
666 case 'l' :
667 flags |= FLAGS_LONG;
668 format++;
669 if (*format == 'l') {
670 flags |= FLAGS_LONG_LONG;
671 format++;
672 }
673 break;
674 case 'h' :
675 flags |= FLAGS_SHORT;
676 format++;
677 if (*format == 'h') {
678 flags |= FLAGS_CHAR;
679 format++;
680 }
681 break;
682 #if PICO_PRINTF_SUPPORT_PTRDIFF_T
683 case 't' :
684 flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
685 format++;
686 break;
687 #endif
688 case 'j' :
689 flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
690 format++;
691 break;
692 case 'z' :
693 flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
694 format++;
695 break;
696 default :
697 break;
698 }
699
700 // evaluate specifier
701 switch (*format) {
702 case 'd' :
703 case 'i' :
704 case 'u' :
705 case 'x' :
706 case 'X' :
707 case 'o' :
708 case 'b' : {
709 // set the base
710 unsigned int base;
711 if (*format == 'x' || *format == 'X') {
712 base = 16U;
713 } else if (*format == 'o') {
714 base = 8U;
715 } else if (*format == 'b') {
716 base = 2U;
717 } else {
718 base = 10U;
719 flags &= ~FLAGS_HASH; // no hash for dec format
720 }
721 // uppercase
722 if (*format == 'X') {
723 flags |= FLAGS_UPPERCASE;
724 }
725
726 // no plus or space flag for u, x, X, o, b
727 if ((*format != 'i') && (*format != 'd')) {
728 flags &= ~(FLAGS_PLUS | FLAGS_SPACE);
729 }
730
731 // ignore '0' flag when precision is given
732 if (flags & FLAGS_PRECISION) {
733 flags &= ~FLAGS_ZEROPAD;
734 }
735
736 // convert the integer
737 if ((*format == 'i') || (*format == 'd')) {
738 // signed
739 if (flags & FLAGS_LONG_LONG) {
740 #if PICO_PRINTF_SUPPORT_LONG_LONG
741 const long long value = va_arg(va, long long);
742 idx = _ntoa_long_long(out, buffer, idx, maxlen,
743 (unsigned long long) (value > 0 ? value : 0 - value), value < 0, base,
744 precision, width, flags);
745 #endif
746 } else if (flags & FLAGS_LONG) {
747 const long value = va_arg(va, long);
748 idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long) (value > 0 ? value : 0 - value),
749 value < 0, base, precision, width, flags);
750 } else {
751 const int value = (flags & FLAGS_CHAR) ? (char) va_arg(va, int) : (flags & FLAGS_SHORT)
752 ? (short int) va_arg(va, int)
753 : va_arg(va, int);
754 idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int) (value > 0 ? value : 0 - value),
755 value < 0, base, precision, width, flags);
756 }
757 } else {
758 // unsigned
759 if (flags & FLAGS_LONG_LONG) {
760 #if PICO_PRINTF_SUPPORT_LONG_LONG
761 idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base,
762 precision, width, flags);
763 #endif
764 } else if (flags & FLAGS_LONG) {
765 idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision,
766 width, flags);
767 } else {
768 const unsigned int value = (flags & FLAGS_CHAR) ? (unsigned char) va_arg(va, unsigned int)
769 : (flags & FLAGS_SHORT)
770 ? (unsigned short int) va_arg(va,
771 unsigned int)
772 : va_arg(va, unsigned int);
773 idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags);
774 }
775 }
776 format++;
777 break;
778 }
779 case 'f' :
780 case 'F' :
781 #if PICO_PRINTF_SUPPORT_FLOAT
782 if (*format == 'F') flags |= FLAGS_UPPERCASE;
783 idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
784 #else
785 for(int i=0;i<2;i++) out('?', buffer, idx++, maxlen);
786 va_arg(va, double);
787 #endif
788 format++;
789 break;
790 case 'e':
791 case 'E':
792 case 'g':
793 case 'G':
794 #if PICO_PRINTF_SUPPORT_FLOAT && PICO_PRINTF_SUPPORT_EXPONENTIAL
795 if ((*format == 'g') || (*format == 'G')) flags |= FLAGS_ADAPT_EXP;
796 if ((*format == 'E') || (*format == 'G')) flags |= FLAGS_UPPERCASE;
797 idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
798 #else
799 for(int i=0;i<2;i++) out('?', buffer, idx++, maxlen);
800 va_arg(va, double);
801 #endif
802 format++;
803 break;
804 case 'c' : {
805 unsigned int l = 1U;
806 // pre padding
807 if (!(flags & FLAGS_LEFT)) {
808 while (l++ < width) {
809 out(' ', buffer, idx++, maxlen);
810 }
811 }
812 // char output
813 out((char) va_arg(va, int), buffer, idx++, maxlen);
814 // post padding
815 if (flags & FLAGS_LEFT) {
816 while (l++ < width) {
817 out(' ', buffer, idx++, maxlen);
818 }
819 }
820 format++;
821 break;
822 }
823
824 case 's' : {
825 const char *p = va_arg(va, char*);
826 unsigned int l = _strnlen_s(p, precision ? precision : (size_t) -1);
827 // pre padding
828 if (flags & FLAGS_PRECISION) {
829 l = (l < precision ? l : precision);
830 }
831 if (!(flags & FLAGS_LEFT)) {
832 while (l++ < width) {
833 out(' ', buffer, idx++, maxlen);
834 }
835 }
836 // string output
837 while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) {
838 out(*(p++), buffer, idx++, maxlen);
839 }
840 // post padding
841 if (flags & FLAGS_LEFT) {
842 while (l++ < width) {
843 out(' ', buffer, idx++, maxlen);
844 }
845 }
846 format++;
847 break;
848 }
849
850 case 'p' : {
851 width = sizeof(void *) * 2U;
852 flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE;
853 #if PICO_PRINTF_SUPPORT_LONG_LONG
854 const bool is_ll = sizeof(uintptr_t) == sizeof(long long);
855 if (is_ll) {
856 idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t) va_arg(va, void*), false, 16U,
857 precision, width, flags);
858 } else {
859 #endif
860 idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long) ((uintptr_t) va_arg(va, void*)), false,
861 16U, precision, width, flags);
862 #if PICO_PRINTF_SUPPORT_LONG_LONG
863 }
864 #endif
865 format++;
866 break;
867 }
868
869 case '%' :
870 out('%', buffer, idx++, maxlen);
871 format++;
872 break;
873
874 default :
875 out(*format, buffer, idx++, maxlen);
876 format++;
877 break;
878 }
879 }
880
881 // termination
882 out((char) 0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen);
883
884 // return written chars without terminating \0
885 return (int) idx;
886 }
887
888
889 ///////////////////////////////////////////////////////////////////////////////
890
WRAPPER_FUNC(sprintf)891 int WRAPPER_FUNC(sprintf)(char *buffer, const char *format, ...) {
892 va_list va;
893 va_start(va, format);
894 const int ret = _vsnprintf(_out_buffer, buffer, (size_t) -1, format, va);
895 va_end(va);
896 return ret;
897 }
898
WRAPPER_FUNC(snprintf)899 int WRAPPER_FUNC(snprintf)(char *buffer, size_t count, const char *format, ...) {
900 va_list va;
901 va_start(va, format);
902 const int ret = _vsnprintf(_out_buffer, buffer, count, format, va);
903 va_end(va);
904 return ret;
905 }
906
WRAPPER_FUNC(vsnprintf)907 int WRAPPER_FUNC(vsnprintf)(char *buffer, size_t count, const char *format, va_list va) {
908 return _vsnprintf(_out_buffer, buffer, count, format, va);
909 }
910
vfctprintf(void (* out)(char character,void * arg),void * arg,const char * format,va_list va)911 int vfctprintf(void (*out)(char character, void *arg), void *arg, const char *format, va_list va) {
912 const out_fct_wrap_type out_fct_wrap = {out, arg};
913 return _vsnprintf(_out_fct, (char *) (uintptr_t) &out_fct_wrap, (size_t) -1, format, va);
914 }
915
916 #if PICO_PRINTF_PICO
917 #if !PICO_PRINTF_ALWAYS_INCLUDED
weak_raw_printf(const char * fmt,...)918 bool weak_raw_printf(const char *fmt, ...) {
919 va_list va;
920 va_start(va, fmt);
921 bool rc = weak_raw_vprintf(fmt, va);
922 va_end(va);
923 return rc;
924 }
925
weak_raw_vprintf(const char * fmt,va_list args)926 bool weak_raw_vprintf(const char *fmt, va_list args) {
927 if (lazy_vsnprintf) {
928 char buffer[1];
929 lazy_vsnprintf(_out_char, buffer, (size_t) -1, fmt, args);
930 return true;
931 } else {
932 puts(fmt);
933 return false;
934 }
935 }
936 #endif
937 #endif
938