blob: 51c16f4e3d299611014eef75473ea4170670fd32 [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
Damien George2cae0f62015-05-28 13:54:56 +0000123// Our mp_vprintf function below does not support the '#' format modifier to
124// print the prefix of a non-base-10 number, so we don't need code for this.
125#define SUPPORT_INT_BASE_PREFIX (0)
126
127// This function is used exclusively by mp_vprintf to format ints.
Damien George7f9d1d62015-04-09 23:56:15 +0100128// It needs to be a separate function to mp_print_mp_int, since converting to a mp_int looses the MSB.
Damien George2cae0f62015-05-28 13:54:56 +0000129STATIC int 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) {
Damien George7f9d1d62015-04-09 23:56:15 +0100130 char sign = 0;
131 if (sgn) {
132 if ((mp_int_t)x < 0) {
133 sign = '-';
134 x = -x;
135 } else if (flags & PF_FLAG_SHOW_SIGN) {
136 sign = '+';
137 } else if (flags & PF_FLAG_SPACE_SIGN) {
138 sign = ' ';
139 }
140 }
141
142 char buf[INT_BUF_SIZE];
143 char *b = buf + INT_BUF_SIZE;
144
145 if (x == 0) {
146 *(--b) = '0';
147 } else {
148 do {
149 int c = x % base;
150 x /= base;
151 if (c >= 10) {
152 c += base_char - 10;
153 } else {
154 c += '0';
155 }
156 *(--b) = c;
157 } while (b > buf && x != 0);
158 }
159
Damien George2cae0f62015-05-28 13:54:56 +0000160 #if SUPPORT_INT_BASE_PREFIX
Damien George7f9d1d62015-04-09 23:56:15 +0100161 char prefix_char = '\0';
162
163 if (flags & PF_FLAG_SHOW_PREFIX) {
164 if (base == 2) {
165 prefix_char = base_char + 'b' - 'a';
166 } else if (base == 8) {
167 prefix_char = base_char + 'o' - 'a';
168 } else if (base == 16) {
169 prefix_char = base_char + 'x' - 'a';
170 }
171 }
Damien George2cae0f62015-05-28 13:54:56 +0000172 #endif
Damien George7f9d1d62015-04-09 23:56:15 +0100173
174 int len = 0;
175 if (flags & PF_FLAG_PAD_AFTER_SIGN) {
176 if (sign) {
177 len += mp_print_strn(print, &sign, 1, flags, fill, 1);
178 width--;
179 }
Damien George2cae0f62015-05-28 13:54:56 +0000180 #if SUPPORT_INT_BASE_PREFIX
Damien George7f9d1d62015-04-09 23:56:15 +0100181 if (prefix_char) {
182 len += mp_print_strn(print, "0", 1, flags, fill, 1);
183 len += mp_print_strn(print, &prefix_char, 1, flags, fill, 1);
184 width -= 2;
185 }
Damien George2cae0f62015-05-28 13:54:56 +0000186 #endif
Damien George7f9d1d62015-04-09 23:56:15 +0100187 } else {
Damien George2cae0f62015-05-28 13:54:56 +0000188 #if SUPPORT_INT_BASE_PREFIX
Damien George7f9d1d62015-04-09 23:56:15 +0100189 if (prefix_char && b > &buf[1]) {
190 *(--b) = prefix_char;
191 *(--b) = '0';
192 }
Damien George2cae0f62015-05-28 13:54:56 +0000193 #endif
Damien George7f9d1d62015-04-09 23:56:15 +0100194 if (sign && b > buf) {
195 *(--b) = sign;
196 }
197 }
198
199 len += mp_print_strn(print, b, buf + INT_BUF_SIZE - b, flags, fill, width);
200 return len;
201}
202
203int 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) {
204 if (!MP_OBJ_IS_INT(x)) {
205 // This will convert booleans to int, or raise an error for
206 // non-integer types.
207 x = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int(x));
208 }
209
210 if ((flags & (PF_FLAG_LEFT_ADJUST | PF_FLAG_CENTER_ADJUST)) == 0 && fill == '0') {
211 if (prec > width) {
212 width = prec;
213 }
214 prec = 0;
215 }
216 char prefix_buf[4];
217 char *prefix = prefix_buf;
218
219 if (mp_obj_int_is_positive(x)) {
220 if (flags & PF_FLAG_SHOW_SIGN) {
221 *prefix++ = '+';
222 } else if (flags & PF_FLAG_SPACE_SIGN) {
223 *prefix++ = ' ';
224 }
225 }
226
227 if (flags & PF_FLAG_SHOW_PREFIX) {
228 if (base == 2) {
229 *prefix++ = '0';
230 *prefix++ = base_char + 'b' - 'a';
231 } else if (base == 8) {
232 *prefix++ = '0';
233 if (flags & PF_FLAG_SHOW_OCTAL_LETTER) {
234 *prefix++ = base_char + 'o' - 'a';
235 }
236 } else if (base == 16) {
237 *prefix++ = '0';
238 *prefix++ = base_char + 'x' - 'a';
239 }
240 }
241 *prefix = '\0';
242 int prefix_len = prefix - prefix_buf;
243 prefix = prefix_buf;
244
245 char comma = '\0';
246 if (flags & PF_FLAG_SHOW_COMMA) {
247 comma = ',';
248 }
249
250 // The size of this buffer is rather arbitrary. If it's not large
251 // enough, a dynamic one will be allocated.
252 char stack_buf[sizeof(mp_int_t) * 4];
253 char *buf = stack_buf;
254 mp_uint_t buf_size = sizeof(stack_buf);
255 mp_uint_t fmt_size = 0;
256 char *str;
257
258 if (prec > 1) {
259 flags |= PF_FLAG_PAD_AFTER_SIGN;
260 }
261 char sign = '\0';
262 if (flags & PF_FLAG_PAD_AFTER_SIGN) {
263 // We add the pad in this function, so since the pad goes after
264 // the sign & prefix, we format without a prefix
265 str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size,
266 x, base, NULL, base_char, comma);
267 if (*str == '-') {
268 sign = *str++;
269 fmt_size--;
270 }
271 } else {
272 str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size,
273 x, base, prefix, base_char, comma);
274 }
275
276 int spaces_before = 0;
277 int spaces_after = 0;
278
279 if (prec > 1) {
280 // If prec was specified, then prec specifies the width to zero-pad the
281 // the number to. This zero-padded number then gets left or right
282 // aligned in width characters.
283
284 int prec_width = fmt_size; // The digits
285 if (prec_width < prec) {
286 prec_width = prec;
287 }
288 if (flags & PF_FLAG_PAD_AFTER_SIGN) {
289 if (sign) {
290 prec_width++;
291 }
292 prec_width += prefix_len;
293 }
294 if (prec_width < width) {
295 if (flags & PF_FLAG_LEFT_ADJUST) {
296 spaces_after = width - prec_width;
297 } else {
298 spaces_before = width - prec_width;
299 }
300 }
301 fill = '0';
302 flags &= ~PF_FLAG_LEFT_ADJUST;
303 }
304
305 int len = 0;
306 if (spaces_before) {
307 len += mp_print_strn(print, "", 0, 0, ' ', spaces_before);
308 }
309 if (flags & PF_FLAG_PAD_AFTER_SIGN) {
310 // pad after sign implies pad after prefix as well.
311 if (sign) {
312 len += mp_print_strn(print, &sign, 1, 0, 0, 1);
313 width--;
314 }
315 if (prefix_len) {
316 len += mp_print_strn(print, prefix, prefix_len, 0, 0, 1);
317 width -= prefix_len;
318 }
319 }
320 if (prec > 1) {
321 width = prec;
322 }
323
324 len += mp_print_strn(print, str, fmt_size, flags, fill, width);
325
326 if (spaces_after) {
327 len += mp_print_strn(print, "", 0, 0, ' ', spaces_after);
328 }
329
330 if (buf != stack_buf) {
331 m_del(char, buf, buf_size);
332 }
333 return len;
334}
335
336#if MICROPY_PY_BUILTINS_FLOAT
337int mp_print_float(const mp_print_t *print, mp_float_t f, char fmt, int flags, char fill, int width, int prec) {
338 char buf[32];
339 char sign = '\0';
340 int chrs = 0;
341
342 if (flags & PF_FLAG_SHOW_SIGN) {
343 sign = '+';
344 }
345 else
346 if (flags & PF_FLAG_SPACE_SIGN) {
347 sign = ' ';
348 }
Damien George7f9d1d62015-04-09 23:56:15 +0100349
stijn861670b2015-05-16 10:54:19 +0200350 int len = mp_format_float(f, buf, sizeof(buf), fmt, prec, sign);
Damien George7f9d1d62015-04-09 23:56:15 +0100351 if (len < 0) {
352 len = 0;
353 }
stijn861670b2015-05-16 10:54:19 +0200354
Damien George7f9d1d62015-04-09 23:56:15 +0100355 char *s = buf;
356
357 if ((flags & PF_FLAG_ADD_PERCENT) && (size_t)(len + 1) < sizeof(buf)) {
358 buf[len++] = '%';
359 buf[len] = '\0';
360 }
361
362 // buf[0] < '0' returns true if the first character is space, + or -
363 if ((flags & PF_FLAG_PAD_AFTER_SIGN) && buf[0] < '0') {
364 // We have a sign character
365 s++;
366 if (*s <= '9' || (flags & PF_FLAG_PAD_NAN_INF)) {
367 // We have a number, or we have a inf/nan and PAD_NAN_INF is set
368 // With '{:06e}'.format(float('-inf')) you get '-00inf'
369 chrs += mp_print_strn(print, &buf[0], 1, 0, 0, 1);
370 width--;
371 len--;
372 }
373 }
374
375 if (*s > 'A' && (flags & PF_FLAG_PAD_NAN_INF) == 0) {
376 // We have one of the inf or nan variants, suppress zero fill.
377 // With printf, if you use: printf("%06e", -inf) then you get " -inf"
378 // so suppress the zero fill.
379 fill = ' ';
380 }
381 chrs += mp_print_strn(print, s, len, flags, fill, width);
382
383 return chrs;
384}
385#endif
386
387int mp_printf(const mp_print_t *print, const char *fmt, ...) {
388 va_list ap;
389 va_start(ap, fmt);
390 int ret = mp_vprintf(print, fmt, ap);
391 va_end(ap);
392 return ret;
393}
394
395int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) {
396 int chrs = 0;
397 for (;;) {
398 {
399 const char *f = fmt;
400 while (*f != '\0' && *f != '%') {
401 ++f; // XXX UTF8 advance char
402 }
403 if (f > fmt) {
404 print->print_strn(print->data, fmt, f - fmt);
405 chrs += f - fmt;
406 fmt = f;
407 }
408 }
409
410 if (*fmt == '\0') {
411 break;
412 }
413
414 // move past % character
415 ++fmt;
416
417 // parse flags, if they exist
418 int flags = 0;
419 char fill = ' ';
420 while (*fmt != '\0') {
421 if (*fmt == '-') flags |= PF_FLAG_LEFT_ADJUST;
422 else if (*fmt == '+') flags |= PF_FLAG_SHOW_SIGN;
423 else if (*fmt == ' ') flags |= PF_FLAG_SPACE_SIGN;
424 else if (*fmt == '!') flags |= PF_FLAG_NO_TRAILZ;
425 else if (*fmt == '0') {
426 flags |= PF_FLAG_PAD_AFTER_SIGN;
427 fill = '0';
428 } else break;
429 ++fmt;
430 }
431
432 // parse width, if it exists
433 int width = 0;
434 for (; '0' <= *fmt && *fmt <= '9'; ++fmt) {
435 width = width * 10 + *fmt - '0';
436 }
437
438 // parse precision, if it exists
439 int prec = -1;
440 if (*fmt == '.') {
441 ++fmt;
442 if (*fmt == '*') {
443 ++fmt;
444 prec = va_arg(args, int);
445 } else {
446 prec = 0;
447 for (; '0' <= *fmt && *fmt <= '9'; ++fmt) {
448 prec = prec * 10 + *fmt - '0';
449 }
450 }
451 if (prec < 0) {
452 prec = 0;
453 }
454 }
455
456 // parse long specifiers (current not used)
457 //bool long_arg = false;
458 if (*fmt == 'l') {
459 ++fmt;
460 //long_arg = true;
461 }
462
463 if (*fmt == '\0') {
464 break;
465 }
466
467 switch (*fmt) {
468 case 'b':
469 if (va_arg(args, int)) {
470 chrs += mp_print_strn(print, "true", 4, flags, fill, width);
471 } else {
472 chrs += mp_print_strn(print, "false", 5, flags, fill, width);
473 }
474 break;
475 case 'c':
476 {
477 char str = va_arg(args, int);
478 chrs += mp_print_strn(print, &str, 1, flags, fill, width);
479 break;
480 }
Damien George044c4732015-04-11 13:03:37 +0100481 case 'q':
482 {
483 qstr qst = va_arg(args, qstr);
484 mp_uint_t len;
485 const char *str = (const char*)qstr_data(qst, &len);
486 if (prec < 0) {
487 prec = len;
488 }
489 chrs += mp_print_strn(print, str, prec, flags, fill, width);
490 break;
491 }
Damien George7f9d1d62015-04-09 23:56:15 +0100492 case 's':
493 {
494 const char *str = va_arg(args, const char*);
495 if (str) {
496 if (prec < 0) {
497 prec = strlen(str);
498 }
499 chrs += mp_print_strn(print, str, prec, flags, fill, width);
500 } else {
501 chrs += mp_print_strn(print, "(null)", 6, flags, fill, width);
502 }
503 break;
504 }
505 case 'u':
506 chrs += mp_print_int(print, va_arg(args, int), 0, 10, 'a', flags, fill, width);
507 break;
508 case 'd':
509 chrs += mp_print_int(print, va_arg(args, int), 1, 10, 'a', flags, fill, width);
510 break;
511 case 'x':
512 chrs += mp_print_int(print, va_arg(args, int), 0, 16, 'a', flags, fill, width);
513 break;
514 case 'X':
515 chrs += mp_print_int(print, va_arg(args, int), 0, 16, 'A', flags, fill, width);
516 break;
517 case 'p':
518 case 'P': // don't bother to handle upcase for 'P'
519 chrs += mp_print_int(print, va_arg(args, unsigned int), 0, 16, 'a', flags, fill, width);
520 break;
521#if MICROPY_PY_BUILTINS_FLOAT
522 case 'e':
523 case 'E':
524 case 'f':
525 case 'F':
526 case 'g':
527 case 'G':
528 {
529#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
530 mp_float_t f = va_arg(args, double);
531 chrs += mp_print_float(print, f, *fmt, flags, fill, width, prec);
532#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
533 // Currently mp_print_float uses snprintf, but snprintf
534 // itself may be implemented in terms of mp_vprintf() for
535 // some ports. So, for extra caution, this case is handled
536 // with assert below. Note that currently ports which
537 // use MICROPY_FLOAT_IMPL_DOUBLE, don't call mp_vprintf()
538 // with float format specifier at all.
539 // TODO: resolve this completely
540 assert(0);
541//#error Calling mp_print_float with double not supported from within printf
542#else
543#error Unknown MICROPY FLOAT IMPL
544#endif
545 break;
546 }
547#endif
548 default:
549 print->print_strn(print->data, fmt, 1);
550 chrs += 1;
551 break;
552 }
553 ++fmt;
554 }
555 return chrs;
556}