printf.c 9.85 KB
Newer Older
1
#include <stdint.h>
2
#include <string.h>
Damien's avatar
Damien committed
3
#include <stdarg.h>
4

Damien's avatar
Damien committed
5
#include "std.h"
Damien's avatar
Damien committed
6
#include "misc.h"
mux's avatar
mux committed
7
8
#include "systick.h"
#include "mpconfig.h"
9
#include "qstr.h"
mux's avatar
mux committed
10
#include "obj.h"
Damien's avatar
Damien committed
11
#include "lcd.h"
12
#include "usart.h"
Damien's avatar
Damien committed
13
#include "usb.h"
14
15
16
#if MICROPY_ENABLE_FLOAT
#include "format-float.h"
#endif
Damien's avatar
Damien committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

#define PF_FLAG_LEFT_ADJUST (0x01)
#define PF_FLAG_SHOW_SIGN   (0x02)
#define PF_FLAG_SPACE_SIGN  (0x04)
#define PF_FLAG_NO_TRAILZ   (0x08)
#define PF_FLAG_ZERO_PAD    (0x10)

// tricky; we compute pad string by: pad_chars + (flags & PF_FLAG_ZERO_PAD)
#define PF_PAD_SIZE PF_FLAG_ZERO_PAD
static const char *pad_chars = "                0000000000000000";

typedef struct _pfenv_t {
    void *data;
    void (*print_strn)(void *, const char *str, unsigned int len);
} pfenv_t;

static void print_str_dummy(void *data, const char *str, unsigned int len) {
}

36
const pfenv_t pfenv_dummy = {0, print_str_dummy};
Damien's avatar
Damien committed
37

38
static int pfenv_print_strn(const pfenv_t *pfenv, const char *str, unsigned int len, int flags, int width) {
Damien's avatar
Damien committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
    int pad = width - len;
    if (pad > 0 && (flags & PF_FLAG_LEFT_ADJUST) == 0) {
        while (pad > 0) {
            int p = pad;
            if (p > PF_PAD_SIZE)
                p = PF_PAD_SIZE;
            pfenv->print_strn(pfenv->data, pad_chars + (flags & PF_FLAG_ZERO_PAD), p);
            pad -= p;
        }
    }
    pfenv->print_strn(pfenv->data, str, len);
    while (pad > 0) {
        int p = pad;
        if (p > PF_PAD_SIZE)
            p = PF_PAD_SIZE;
        pfenv->print_strn(pfenv->data, pad_chars, p);
        pad -= p;
    }
    return len;
}

// enough room for 32 signed number
#define INT_BUF_SIZE (12)

63
static int pfenv_print_int(const pfenv_t *pfenv, unsigned int x, int sgn, int base, int base_char, int flags, int width) {
Damien's avatar
Damien committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
    char sign = 0;
    if (sgn) {
        if ((int)x < 0) {
            sign = '-';
            x = -x;
        } else if (flags & PF_FLAG_SHOW_SIGN) {
            sign = '+';
        } else if (flags & PF_FLAG_SPACE_SIGN) {
            sign = ' ';
        }
    }

    char buf[INT_BUF_SIZE];
    char *b = buf + INT_BUF_SIZE;

    if (x == 0) {
        *(--b) = '0';
    } else {
        do {
            int c = x % base;
            x /= base;
            if (c >= 10) {
                c += base_char - 10;
            } else {
                c += '0';
            }
            *(--b) = c;
        } while (b > buf && x != 0);
    }

    if (b > buf && sign != 0) {
        *(--b) = sign;
    }

    return pfenv_print_strn(pfenv, b, buf + INT_BUF_SIZE - b, flags, width);
}

101
void pfenv_prints(const pfenv_t *pfenv, const char *str) {
Damien's avatar
Damien committed
102
103
104
    pfenv->print_strn(pfenv->data, str, strlen(str));
}

105
int pfenv_printf(const pfenv_t *pfenv, const char *fmt, va_list args) {
Damien's avatar
Damien committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
    int chrs = 0;
    for (;;) {
        {
            const char *f = fmt;
            while (*f != '\0' && *f != '%') {
                ++f; // XXX UTF8 advance char
            }
            if (f > fmt) {
                pfenv->print_strn(pfenv->data, fmt, f - fmt);
                chrs += f - fmt;
                fmt = f;
            }
        }

        if (*fmt == '\0') {
            break;
        }

        // move past % character
        ++fmt;

        // parse flags, if they exist
        int flags = 0;
        while (*fmt != '\0') {
            if (*fmt == '-') flags |= PF_FLAG_LEFT_ADJUST;
            else if (*fmt == '+') flags |= PF_FLAG_SHOW_SIGN;
            else if (*fmt == ' ') flags |= PF_FLAG_SPACE_SIGN;
            else if (*fmt == '!') flags |= PF_FLAG_NO_TRAILZ;
            else if (*fmt == '0') flags |= PF_FLAG_ZERO_PAD;
            else break;
            ++fmt;
        }

        // parse width, if it exists
        int width = 0;
        for (; '0' <= *fmt && *fmt <= '9'; ++fmt) {
            width = width * 10 + *fmt - '0';
        }

        // parse precision, if it exists
        int prec = -1;
        if (*fmt == '.') {
            ++fmt;
            if (*fmt == '*') {
                ++fmt;
                prec = va_arg(args, int);
            } else {
                prec = 0;
                for (; '0' <= *fmt && *fmt <= '9'; ++fmt) {
                    prec = prec * 10 + *fmt - '0';
                }
            }
            if (prec < 0) {
                prec = 0;
            }
        }

        // parse long specifiers (current not used)
        //bool long_arg = false;
        if (*fmt == 'l') {
            ++fmt;
            //long_arg = true;
        }

        if (*fmt == '\0') {
            break;
        }

        switch (*fmt) {
            case 'b':
                if (va_arg(args, int)) {
                    chrs += pfenv_print_strn(pfenv, "true", 4, flags, width);
                } else {
                    chrs += pfenv_print_strn(pfenv, "false", 5, flags, width);
                }
                break;
            case 'c':
            {
                char str = va_arg(args, int);
                chrs += pfenv_print_strn(pfenv, &str, 1, flags, width);
                break;
            }
            case 's':
            {
                const char *str = va_arg(args, const char*);
                if (str) {
                    if (prec < 0) {
                        prec = strlen(str);
                    }
                    chrs += pfenv_print_strn(pfenv, str, prec, flags, width);
                } else {
                    chrs += pfenv_print_strn(pfenv, "(null)", 6, flags, width);
                }
                break;
            }
            case 'u':
                chrs += pfenv_print_int(pfenv, va_arg(args, int), 0, 10, 'a', flags, width);
                break;
            case 'd':
                chrs += pfenv_print_int(pfenv, va_arg(args, int), 1, 10, 'a', flags, width);
                break;
            case 'x':
            case 'p': // ?
                chrs += pfenv_print_int(pfenv, va_arg(args, int), 0, 16, 'a', flags, width);
                break;
            case 'X':
            case 'P': // ?
                chrs += pfenv_print_int(pfenv, va_arg(args, int), 0, 16, 'A', flags, width);
                break;
215
#if MICROPY_ENABLE_FLOAT
216
217
218
219
            case 'e':
            case 'E':
            case 'f':
            case 'F':
220
            case 'g':
221
            case 'G':
222
            {
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
                char buf[32];
                char sign = '\0';

                if (flags & PF_FLAG_SHOW_SIGN) {
                    sign = '+';
                }
                else
                if (flags & PF_FLAG_SPACE_SIGN) {
                    sign = ' ';
                }
                float f = va_arg(args, double);
                int len = format_float(f, buf, sizeof(buf), *fmt, prec, sign);
                char *s = buf;

                // buf[0] < '0' returns true if the first character is space, + or -
                // buf[1] < '9' matches a digit, and doesn't match when we get back +nan or +inf
                if (buf[0] < '0' && buf[1] <= '9' && (flags & PF_FLAG_ZERO_PAD)) {
                    chrs += pfenv_print_strn(pfenv, &buf[0], 1, 0, 1);
                    s++;
                    width--;
                    len--;
                }
                if (*s < '0' || *s >= '9') {
                    // For inf or nan, we don't want to zero pad.
                    flags &= ~PF_FLAG_ZERO_PAD;
248
                }
249
                chrs += pfenv_print_strn(pfenv, s, len, flags, width); 
250
251
                break;
            }
252
#endif
Damien's avatar
Damien committed
253
254
255
256
257
258
259
260
261
262
            default:
                pfenv->print_strn(pfenv->data, fmt, 1);
                chrs += 1;
                break;
        }
        ++fmt;
    }
    return chrs;
}

263
void stdout_print_strn(void *data, const char *str, unsigned int len) {
264
265
    // send stdout to USART, USB CDC VCP, and LCD if nothing else
    bool any = false;
266

267
268
    if (pyb_usart_global_debug != PYB_USART_NONE) {
        usart_tx_strn_cooked(pyb_usart_global_debug, str, len);
269
270
        any = true;
    }
Damien's avatar
Damien committed
271
    if (usb_vcp_is_enabled()) {
272
        usb_vcp_send_strn_cooked(str, len);
273
274
275
        any = true;
    }
    if (!any) {
mux's avatar
mux committed
276
#if MICROPY_HW_HAS_LCD
Damien's avatar
Damien committed
277
        lcd_print_strn(str, len);
mux's avatar
mux committed
278
#endif
Damien's avatar
Damien committed
279
    }
Damien's avatar
Damien committed
280
281
}

282
static const pfenv_t pfenv_stdout = {0, stdout_print_strn};
Damien's avatar
Damien committed
283
284

int printf(const char *fmt, ...) {
Damien's avatar
Damien committed
285
286
287
288
289
290
291
292
293
    va_list ap;
    va_start(ap, fmt);
    int ret = pfenv_printf(&pfenv_stdout, fmt, ap);
    va_end(ap);
    return ret;
}

int vprintf(const char *fmt, va_list ap) {
    return pfenv_printf(&pfenv_stdout, fmt, ap);
Damien's avatar
Damien committed
294
295
}

296
297
298
299
300
301
302
303
304
305
306
#if MICROPY_DEBUG_PRINTERS
int DEBUG_printf(const char *fmt, ...) {
    (void)stream;
    va_list ap;
    va_start(ap, fmt);
    int ret = pfenv_printf(&pfenv_stdout, fmt, ap);
    va_end(ap);
    return ret;
}
#endif

Damien's avatar
Damien committed
307
308
309
// need this because gcc optimises printf("%c", c) -> putchar(c), and printf("a") -> putchar('a')
int putchar(int c) {
    char chr = c;
310
    stdout_print_strn(0, &chr, 1);
Damien's avatar
Damien committed
311
312
313
314
315
    return chr;
}

// need this because gcc optimises printf("string\n") -> puts("string")
int puts(const char *s) {
316
    stdout_print_strn(0, s, strlen(s));
Damien's avatar
Damien committed
317
    char chr = '\n';
318
    stdout_print_strn(0, &chr, 1);
Damien's avatar
Damien committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
    return 1;
}

typedef struct _strn_pfenv_t {
    char *cur;
    size_t remain;
} strn_pfenv_t;

void strn_print_strn(void *data, const char *str, unsigned int len) {
    strn_pfenv_t *strn_pfenv = data;
    if (len > strn_pfenv->remain) {
        len = strn_pfenv->remain;
    }
    memcpy(strn_pfenv->cur, str, len);
    strn_pfenv->cur += len;
    strn_pfenv->remain -= len;
}

Damien's avatar
Damien committed
337
int vsnprintf(char *str, size_t size, const char *fmt, va_list ap) {
Damien's avatar
Damien committed
338
339
340
341
342
343
    strn_pfenv_t strn_pfenv;
    strn_pfenv.cur = str;
    strn_pfenv.remain = size;
    pfenv_t pfenv;
    pfenv.data = &strn_pfenv;
    pfenv.print_strn = strn_print_strn;
Damien's avatar
Damien committed
344
    int len = pfenv_printf(&pfenv, fmt, ap);
Damien's avatar
Damien committed
345
346
347
348
349
350
351
352
353
354
    // add terminating null byte
    if (size > 0) {
        if (strn_pfenv.remain == 0) {
            strn_pfenv.cur[-1] = 0;
        } else {
            strn_pfenv.cur[0] = 0;
        }
    }
    return len;
}
Damien's avatar
Damien committed
355
356
357
358
359
360
361
362

int snprintf(char *str, size_t size, const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    int ret = vsnprintf(str, size, fmt, ap);
    va_end(ap);
    return ret;
}