+/rtos

git clone https://git.julia.blue/+/rtos

Vivek MalneediMerge branch 'master' of github.com:EE445M-Sp20/lab-6-vm22967_jbr2558021d2d4

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