blob: 78a0b7aa557c234cbba5e638ee7940b3728bf7e0 [file] [log] [blame]
Damien George7f9d1d62015-04-09 23:56:15 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013-2015 Damien P. George
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
27#include <assert.h>
28#include <stdarg.h>
29#include <stdint.h>
30#include <stdio.h>
31#include <string.h>
32
33#include "py/mpprint.h"
34#include "py/obj.h"
35#include "py/objint.h"
36#include "py/runtime.h"
37
Damien George7f9d1d62015-04-09 23:56:15 +010038#if MICROPY_PY_BUILTINS_FLOAT
39#include "py/formatfloat.h"
40#endif
41
42static const char pad_spaces[] = " ";
43static const char pad_zeroes[] = "0000000000000000";
44
45STATIC void plat_print_strn(void *env, const char *str, mp_uint_t len) {
46 (void)env;
47 MP_PLAT_PRINT_STRN(str, len);
48}
49
50const mp_print_t mp_plat_print = {NULL, plat_print_strn};
51
52int mp_print_str(const mp_print_t *print, const char *str) {
53 mp_uint_t len = strlen(str);
54 if (len) {
55 print->print_strn(print->data, str, len);
56 }
57 return len;
58}
59
60int mp_print_strn(const mp_print_t *print, const char *str, mp_uint_t len, int flags, char fill, int width) {
61 int left_pad = 0;
62 int right_pad = 0;
63 int pad = width - len;
64 int pad_size;
65 int total_chars_printed = 0;
66 const char *pad_chars;
67
68 if (!fill || fill == ' ') {
69 pad_chars = pad_spaces;
70 pad_size = sizeof(pad_spaces) - 1;
71 } else if (fill == '0') {
72 pad_chars = pad_zeroes;
73 pad_size = sizeof(pad_zeroes) - 1;
74 } else {
75 // Other pad characters are fairly unusual, so we'll take the hit
76 // and output them 1 at a time.
77 pad_chars = &fill;
78 pad_size = 1;
79 }
80
81 if (flags & PF_FLAG_CENTER_ADJUST) {
82 left_pad = pad / 2;
83 right_pad = pad - left_pad;
84 } else if (flags & PF_FLAG_LEFT_ADJUST) {
85 right_pad = pad;
86 } else {
87 left_pad = pad;
88 }
89
90 if (left_pad > 0) {
91 total_chars_printed += left_pad;
92 while (left_pad > 0) {
93 int p = left_pad;
94 if (p > pad_size) {
95 p = pad_size;
96 }
97 print->print_strn(print->data, pad_chars, p);
98 left_pad -= p;
99 }
100 }
101 if (len) {
102 print->print_strn(print->data, str, len);
103 total_chars_printed += len;
104 }
105 if (right_pad > 0) {
106 total_chars_printed += right_pad;
107 while (right_pad > 0) {
108 int p = right_pad;
109 if (p > pad_size) {
110 p = pad_size;
111 }
112 print->print_strn(print->data, pad_chars, p);
113 right_pad -= p;
114 }
115 }
116 return total_chars_printed;
117}
118
119// 32-bits is 10 digits, add 3 for commas, 1 for sign, 1 for terminating null
120// We can use 16 characters for 32-bit and 32 characters for 64-bit
121#define INT_BUF_SIZE (sizeof(mp_int_t) * 4)
122
123// This function is used by stmhal port to implement printf.
124// It needs to be a separate function to mp_print_mp_int, since converting to a mp_int looses the MSB.
125int mp_print_int(const mp_print_t *print, mp_uint_t x, int sgn, int base, int base_char, int flags, char fill, int width) {
126 char sign = 0;
127 if (sgn) {
128 if ((mp_int_t)x < 0) {
129 sign = '-';
130 x = -x;
131 } else if (flags & PF_FLAG_SHOW_SIGN) {
132 sign = '+';
133 } else if (flags & PF_FLAG_SPACE_SIGN) {
134 sign = ' ';
135 }
136 }
137
138 char buf[INT_BUF_SIZE];
139 char *b = buf + INT_BUF_SIZE;
140
141 if (x == 0) {
142 *(--b) = '0';
143 } else {
144 do {
145 int c = x % base;
146 x /= base;
147 if (c >= 10) {
148 c += base_char - 10;
149 } else {
150 c += '0';
151 }
152 *(--b) = c;
153 } while (b > buf && x != 0);
154 }
155
156 char prefix_char = '\0';
157
158 if (flags & PF_FLAG_SHOW_PREFIX) {
159 if (base == 2) {
160 prefix_char = base_char + 'b' - 'a';
161 } else if (base == 8) {
162 prefix_char = base_char + 'o' - 'a';
163 } else if (base == 16) {
164 prefix_char = base_char + 'x' - 'a';
165 }
166 }
167
168 int len = 0;
169 if (flags & PF_FLAG_PAD_AFTER_SIGN) {
170 if (sign) {
171 len += mp_print_strn(print, &sign, 1, flags, fill, 1);
172 width--;
173 }
174 if (prefix_char) {
175 len += mp_print_strn(print, "0", 1, flags, fill, 1);
176 len += mp_print_strn(print, &prefix_char, 1, flags, fill, 1);
177 width -= 2;
178 }
179 } else {
180 if (prefix_char && b > &buf[1]) {
181 *(--b) = prefix_char;
182 *(--b) = '0';
183 }
184 if (sign && b > buf) {
185 *(--b) = sign;
186 }
187 }
188
189 len += mp_print_strn(print, b, buf + INT_BUF_SIZE - b, flags, fill, width);
190 return len;
191}
192
193int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, int base, int base_char, int flags, char fill, int width, int prec) {
194 if (!MP_OBJ_IS_INT(x)) {
195 // This will convert booleans to int, or raise an error for
196 // non-integer types.
197 x = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int(x));
198 }
199
200 if ((flags & (PF_FLAG_LEFT_ADJUST | PF_FLAG_CENTER_ADJUST)) == 0 && fill == '0') {
201 if (prec > width) {
202 width = prec;
203 }
204 prec = 0;
205 }
206 char prefix_buf[4];
207 char *prefix = prefix_buf;
208
209 if (mp_obj_int_is_positive(x)) {
210 if (flags & PF_FLAG_SHOW_SIGN) {
211 *prefix++ = '+';
212 } else if (flags & PF_FLAG_SPACE_SIGN) {
213 *prefix++ = ' ';
214 }
215 }
216
217 if (flags & PF_FLAG_SHOW_PREFIX) {
218 if (base == 2) {
219 *prefix++ = '0';
220 *prefix++ = base_char + 'b' - 'a';
221 } else if (base == 8) {
222 *prefix++ = '0';
223 if (flags & PF_FLAG_SHOW_OCTAL_LETTER) {
224 *prefix++ = base_char + 'o' - 'a';
225 }
226 } else if (base == 16) {
227 *prefix++ = '0';
228 *prefix++ = base_char + 'x' - 'a';
229 }
230 }
231 *prefix = '\0';
232 int prefix_len = prefix - prefix_buf;
233 prefix = prefix_buf;
234
235 char comma = '\0';
236 if (flags & PF_FLAG_SHOW_COMMA) {
237 comma = ',';
238 }
239
240 // The size of this buffer is rather arbitrary. If it's not large
241 // enough, a dynamic one will be allocated.
242 char stack_buf[sizeof(mp_int_t) * 4];
243 char *buf = stack_buf;
244 mp_uint_t buf_size = sizeof(stack_buf);
245 mp_uint_t fmt_size = 0;
246 char *str;
247
248 if (prec > 1) {
249 flags |= PF_FLAG_PAD_AFTER_SIGN;
250 }
251 char sign = '\0';
252 if (flags & PF_FLAG_PAD_AFTER_SIGN) {
253 // We add the pad in this function, so since the pad goes after
254 // the sign & prefix, we format without a prefix
255 str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size,
256 x, base, NULL, base_char, comma);
257 if (*str == '-') {
258 sign = *str++;
259 fmt_size--;
260 }
261 } else {
262 str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size,
263 x, base, prefix, base_char, comma);
264 }
265
266 int spaces_before = 0;
267 int spaces_after = 0;
268
269 if (prec > 1) {
270 // If prec was specified, then prec specifies the width to zero-pad the
271 // the number to. This zero-padded number then gets left or right
272 // aligned in width characters.
273
274 int prec_width = fmt_size; // The digits
275 if (prec_width < prec) {
276 prec_width = prec;
277 }
278 if (flags & PF_FLAG_PAD_AFTER_SIGN) {
279 if (sign) {
280 prec_width++;
281 }
282 prec_width += prefix_len;
283 }
284 if (prec_width < width) {
285 if (flags & PF_FLAG_LEFT_ADJUST) {
286 spaces_after = width - prec_width;
287 } else {
288 spaces_before = width - prec_width;
289 }
290 }
291 fill = '0';
292 flags &= ~PF_FLAG_LEFT_ADJUST;
293 }
294
295 int len = 0;
296 if (spaces_before) {
297 len += mp_print_strn(print, "", 0, 0, ' ', spaces_before);
298 }
299 if (flags & PF_FLAG_PAD_AFTER_SIGN) {
300 // pad after sign implies pad after prefix as well.
301 if (sign) {
302 len += mp_print_strn(print, &sign, 1, 0, 0, 1);
303 width--;
304 }
305 if (prefix_len) {
306 len += mp_print_strn(print, prefix, prefix_len, 0, 0, 1);
307 width -= prefix_len;
308 }
309 }
310 if (prec > 1) {
311 width = prec;
312 }
313
314 len += mp_print_strn(print, str, fmt_size, flags, fill, width);
315
316 if (spaces_after) {
317 len += mp_print_strn(print, "", 0, 0, ' ', spaces_after);
318 }
319
320 if (buf != stack_buf) {
321 m_del(char, buf, buf_size);
322 }
323 return len;
324}
325
326#if MICROPY_PY_BUILTINS_FLOAT
327int mp_print_float(const mp_print_t *print, mp_float_t f, char fmt, int flags, char fill, int width, int prec) {
328 char buf[32];
329 char sign = '\0';
330 int chrs = 0;
331
332 if (flags & PF_FLAG_SHOW_SIGN) {
333 sign = '+';
334 }
335 else
336 if (flags & PF_FLAG_SPACE_SIGN) {
337 sign = ' ';
338 }
Damien George7f9d1d62015-04-09 23:56:15 +0100339
stijn861670b2015-05-16 10:54:19 +0200340 int len = mp_format_float(f, buf, sizeof(buf), fmt, prec, sign);
Damien George7f9d1d62015-04-09 23:56:15 +0100341 if (len < 0) {
342 len = 0;
343 }
stijn861670b2015-05-16 10:54:19 +0200344
Damien George7f9d1d62015-04-09 23:56:15 +0100345 char *s = buf;
346
347 if ((flags & PF_FLAG_ADD_PERCENT) && (size_t)(len + 1) < sizeof(buf)) {
348 buf[len++] = '%';
349 buf[len] = '\0';
350 }
351
352 // buf[0] < '0' returns true if the first character is space, + or -
353 if ((flags & PF_FLAG_PAD_AFTER_SIGN) && buf[0] < '0') {
354 // We have a sign character
355 s++;
356 if (*s <= '9' || (flags & PF_FLAG_PAD_NAN_INF)) {
357 // We have a number, or we have a inf/nan and PAD_NAN_INF is set
358 // With '{:06e}'.format(float('-inf')) you get '-00inf'
359 chrs += mp_print_strn(print, &buf[0], 1, 0, 0, 1);
360 width--;
361 len--;
362 }
363 }
364
365 if (*s > 'A' && (flags & PF_FLAG_PAD_NAN_INF) == 0) {
366 // We have one of the inf or nan variants, suppress zero fill.
367 // With printf, if you use: printf("%06e", -inf) then you get " -inf"
368 // so suppress the zero fill.
369 fill = ' ';
370 }
371 chrs += mp_print_strn(print, s, len, flags, fill, width);
372
373 return chrs;
374}
375#endif
376
377int mp_printf(const mp_print_t *print, const char *fmt, ...) {
378 va_list ap;
379 va_start(ap, fmt);
380 int ret = mp_vprintf(print, fmt, ap);
381 va_end(ap);
382 return ret;
383}
384
385int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) {
386 int chrs = 0;
387 for (;;) {
388 {
389 const char *f = fmt;
390 while (*f != '\0' && *f != '%') {
391 ++f; // XXX UTF8 advance char
392 }
393 if (f > fmt) {
394 print->print_strn(print->data, fmt, f - fmt);
395 chrs += f - fmt;
396 fmt = f;
397 }
398 }
399
400 if (*fmt == '\0') {
401 break;
402 }
403
404 // move past % character
405 ++fmt;
406
407 // parse flags, if they exist
408 int flags = 0;
409 char fill = ' ';
410 while (*fmt != '\0') {
411 if (*fmt == '-') flags |= PF_FLAG_LEFT_ADJUST;
412 else if (*fmt == '+') flags |= PF_FLAG_SHOW_SIGN;
413 else if (*fmt == ' ') flags |= PF_FLAG_SPACE_SIGN;
414 else if (*fmt == '!') flags |= PF_FLAG_NO_TRAILZ;
415 else if (*fmt == '0') {
416 flags |= PF_FLAG_PAD_AFTER_SIGN;
417 fill = '0';
418 } else break;
419 ++fmt;
420 }
421
422 // parse width, if it exists
423 int width = 0;
424 for (; '0' <= *fmt && *fmt <= '9'; ++fmt) {
425 width = width * 10 + *fmt - '0';
426 }
427
428 // parse precision, if it exists
429 int prec = -1;
430 if (*fmt == '.') {
431 ++fmt;
432 if (*fmt == '*') {
433 ++fmt;
434 prec = va_arg(args, int);
435 } else {
436 prec = 0;
437 for (; '0' <= *fmt && *fmt <= '9'; ++fmt) {
438 prec = prec * 10 + *fmt - '0';
439 }
440 }
441 if (prec < 0) {
442 prec = 0;
443 }
444 }
445
446 // parse long specifiers (current not used)
447 //bool long_arg = false;
448 if (*fmt == 'l') {
449 ++fmt;
450 //long_arg = true;
451 }
452
453 if (*fmt == '\0') {
454 break;
455 }
456
457 switch (*fmt) {
458 case 'b':
459 if (va_arg(args, int)) {
460 chrs += mp_print_strn(print, "true", 4, flags, fill, width);
461 } else {
462 chrs += mp_print_strn(print, "false", 5, flags, fill, width);
463 }
464 break;
465 case 'c':
466 {
467 char str = va_arg(args, int);
468 chrs += mp_print_strn(print, &str, 1, flags, fill, width);
469 break;
470 }
Damien George044c4732015-04-11 13:03:37 +0100471 case 'q':
472 {
473 qstr qst = va_arg(args, qstr);
474 mp_uint_t len;
475 const char *str = (const char*)qstr_data(qst, &len);
476 if (prec < 0) {
477 prec = len;
478 }
479 chrs += mp_print_strn(print, str, prec, flags, fill, width);
480 break;
481 }
Damien George7f9d1d62015-04-09 23:56:15 +0100482 case 's':
483 {
484 const char *str = va_arg(args, const char*);
485 if (str) {
486 if (prec < 0) {
487 prec = strlen(str);
488 }
489 chrs += mp_print_strn(print, str, prec, flags, fill, width);
490 } else {
491 chrs += mp_print_strn(print, "(null)", 6, flags, fill, width);
492 }
493 break;
494 }
495 case 'u':
496 chrs += mp_print_int(print, va_arg(args, int), 0, 10, 'a', flags, fill, width);
497 break;
498 case 'd':
499 chrs += mp_print_int(print, va_arg(args, int), 1, 10, 'a', flags, fill, width);
500 break;
501 case 'x':
502 chrs += mp_print_int(print, va_arg(args, int), 0, 16, 'a', flags, fill, width);
503 break;
504 case 'X':
505 chrs += mp_print_int(print, va_arg(args, int), 0, 16, 'A', flags, fill, width);
506 break;
507 case 'p':
508 case 'P': // don't bother to handle upcase for 'P'
509 chrs += mp_print_int(print, va_arg(args, unsigned int), 0, 16, 'a', flags, fill, width);
510 break;
511#if MICROPY_PY_BUILTINS_FLOAT
512 case 'e':
513 case 'E':
514 case 'f':
515 case 'F':
516 case 'g':
517 case 'G':
518 {
519#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
520 mp_float_t f = va_arg(args, double);
521 chrs += mp_print_float(print, f, *fmt, flags, fill, width, prec);
522#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
523 // Currently mp_print_float uses snprintf, but snprintf
524 // itself may be implemented in terms of mp_vprintf() for
525 // some ports. So, for extra caution, this case is handled
526 // with assert below. Note that currently ports which
527 // use MICROPY_FLOAT_IMPL_DOUBLE, don't call mp_vprintf()
528 // with float format specifier at all.
529 // TODO: resolve this completely
530 assert(0);
531//#error Calling mp_print_float with double not supported from within printf
532#else
533#error Unknown MICROPY FLOAT IMPL
534#endif
535 break;
536 }
537#endif
538 default:
539 print->print_strn(print->data, fmt, 1);
540 chrs += 1;
541 break;
542 }
543 ++fmt;
544 }
545 return chrs;
546}