4 * This file is part of BeRTOS.
6 * Bertos is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 * As a special exception, you may use this file as part of a free software
21 * library without restriction. Specifically, if other files instantiate
22 * templates or use macros or inline functions from this file, or you compile
23 * this file and link it with other files to produce an executable, this
24 * file does not by itself cause the resulting executable to be covered by
25 * the GNU General Public License. This exception does not however
26 * invalidate any other reasons why the executable file might be covered by
27 * the GNU General Public License.
29 * Copyright 2003, 2004, 2005, 2008 Develer S.r.l. (http://www.develer.com/)
35 * \brief Basic "printf", "sprintf" and "fprintf" formatter.
37 * This module is 100% reentrant and can be adapted to user-defined routines
38 * that needs formatters with special properties like different output
39 * channels or new format specifiers.
41 * To reduce size in applications not using real numbers or long integers
42 * the formatter may be compiled to exclude certain parts. This is
43 * controlled by giving a -D option a compilation time:
46 * -D CONFIG_PRINTF=PRINTF_FULL Full ANSI printf formatter, with some C99 extensions
47 * -D CONFIG_PRINTF=PRINTF_NOFLOAT Exclude support for floats
48 * -D CONFIG_PRINTF=PRINTF_REDUCED Simplified formatter (see below)
49 * -D CONFIG_PRINTF=PRINTF_NOMODIFIERS Exclude "l", "z" and "h" modifiers in reduced version
50 * -D CONFIG_PRINTF=PRINTF_DISABLED No formatter at all
53 * Code size on AVR4 with GCC 3.4.1 (-O2):
54 * \li PRINTF_FULL 2912byte (0xB60)
55 * \li PRINTF_NOFLOAT 1684byte (0x694)
56 * \li PRINTF_REDUCED 924byte (0x39C)
57 * \li PRINTF_NOMODIFIERS 416byte (0x1A0)
59 * Code/data size in words on DSP56K with CodeWarrior 6.0:
60 * \li PRINTF_FULL 1493/45
61 * \li PRINTF_NOFLOAT 795/45
62 * \li PRINTF_REDUCED 482/0
63 * \li PRINTF_NOMODIFIERS 301/0
65 * The reduced version of formatter is suitable when program size is critical
66 * rather than formatting power. This routine uses less than 20 bytes of
67 * stack space which makes it practical even in systems with less than 256
70 * The only formatting specifiers supported by the reduced formatter are:
72 * %% %c %s %d %o %x %X and %hd %ho %hx %hX %ld %lo %lx %lX
75 * It means that real variables are not supported as well as field
76 * width and precision arguments.
82 #include "cfg/cfg_formatwr.h" /* CONFIG_ macros */
83 #include <cfg/debug.h> /* ASSERT */
86 #include <mware/hex.h>
88 #ifndef CONFIG_PRINTF_N_FORMATTER
89 /** Disable the arcane %n formatter. */
90 #define CONFIG_PRINTF_N_FORMATTER 0
93 #ifndef CONFIG_PRINTF_OCTAL_FORMATTER
94 /** Disable the %o formatter. */
95 #define CONFIG_PRINTF_OCTAL_FORMATTER 0
98 /* True if we must keep a count of the number of characters we print. */
99 #define CONFIG_PRINTF_COUNT_CHARS (CONFIG_PRINTF_RETURN_COUNT || CONFIG_PRINTF_N_FORMATTER)
103 #if CONFIG_PRINTF > PRINTF_NOFLOAT
106 /* Maximum precision for floating point values */
107 typedef long double max_float_t;
109 #warning FIXME: be sure to fix buffer size below
110 #if CONFIG_FRMWRI_BUFSIZE
111 #define FRMWRI_BUFSIZE CONFIG_FRMWRI_BUFSIZE
113 /* Conservative estimate. Max float is 3.40282e+038, so %f (but not %e or %g) must have
114 * space for: sign + all 38 digits + '.' + 6 decimal digits (default)
115 * Use a high value to avoid unexpected buffer overflows.
117 #define FRMWRI_BUFSIZE 100
120 #if CONFIG_FRMWRI_BUFSIZE
121 #define FRMWRI_BUFSIZE CONFIG_FRMWRI_BUFSIZE
124 * Conservative estimate. Should be (probably) 12 (which is the size necessary
125 * to represent (2^32-1) in octal plus the sign bit.
127 #define FRMWRI_BUFSIZE 16
131 /* Probably useful for fancy microcontrollers such as the PIC, nobody knows. */
132 #ifndef MEM_ATTRIBUTE
133 #define MEM_ATTRIBUTE
136 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
137 #define IS_SHORT (h_modifier || (sizeof(int) == 2 && !l_modifier))
139 #define IS_SHORT (sizeof(int) == 2)
140 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
143 #if CONFIG_PRINTF > PRINTF_NOFLOAT
145 static char *float_conversion(MEM_ATTRIBUTE max_float_t value,
146 MEM_ATTRIBUTE short nr_of_digits,
147 MEM_ATTRIBUTE char *buf,
148 MEM_ATTRIBUTE char format_flag,
149 MEM_ATTRIBUTE char g_flag,
150 MEM_ATTRIBUTE bool alternate_flag)
152 MEM_ATTRIBUTE char *cp;
153 MEM_ATTRIBUTE char *buf_pointer;
154 MEM_ATTRIBUTE short n, i, dec_point_pos, integral_10_log;
161 while (value >= 1e11) /* To speed up things a bit */
164 integral_10_log += 10;
172 else if (value) /* Not just 0.0 */
174 while (value <= 1e-10) /* To speed up things a bit */
177 integral_10_log -= 10;
187 if (integral_10_log < nr_of_digits && integral_10_log >= -4)
190 nr_of_digits -= integral_10_log;
194 /* %#G - No removal of trailing zeros */
197 /* %G - Removal of trailing zeros */
198 alternate_flag = true;
208 /* Less than one... */
209 if (integral_10_log < 0)
211 *buf_pointer++ = '0';
212 if ((n = nr_of_digits) || alternate_flag)
213 *buf_pointer++ = '.';
215 while (--i > integral_10_log && nr_of_digits)
217 *buf_pointer++ = '0';
220 if (integral_10_log < (-n - 1))
221 /* Nothing more to do */
227 dec_point_pos = - integral_10_log;
232 while (i <= nr_of_digits )
234 value -= (max_float_t)(n = (short)value); /* n=Digit value=Remainder */
235 value *= 10; /* Prepare for next shot */
236 *buf_pointer++ = n + '0';
237 if ( ! i++ && (nr_of_digits || alternate_flag))
238 *buf_pointer++ = '.';
241 /* Rounding possible */
245 cp = buf_pointer - 1;
250 if ( (*cp += n) == ('9' + 1) )
258 } while (cp-- > buf);
267 if (*(cp - 1) == '.')
292 /* %G - Remove trailing zeros */
295 while (*(buf_pointer - 1) == '0')
297 if (*(buf_pointer - 1) == '.')
304 *buf_pointer++ = format_flag;
305 if (integral_10_log < 0)
307 *buf_pointer++ = '-';
308 integral_10_log = -integral_10_log;
311 *buf_pointer++ = '+';
317 *buf_pointer++ = (integral_10_log % 10) + '0';
318 integral_10_log /= 10;
319 } while ( integral_10_log || n < 2 );
320 for ( i = n ; n > 0 ; n-- )
321 *(buf_pointer - 11 - i + n) = *(buf_pointer - n);
324 return (buf_pointer);
327 #endif /* CONFIG_PRINTF > PRINTF_NOFLOAT */
330 * This routine forms the core and entry of the formatter.
332 * The conversion performed conforms to the ANSI specification for "printf".
335 PGM_FUNC(_formatted_write)(const char * PGM_ATTR format,
336 void put_one_char(char, void *),
337 void *secret_pointer,
340 #if CONFIG_PRINTF > PRINTF_REDUCED
341 MEM_ATTRIBUTE static char bad_conversion[] = "???";
342 MEM_ATTRIBUTE static char null_pointer[] = "<NULL>";
344 MEM_ATTRIBUTE int precision;
346 #if CONFIG_PRINTF_COUNT_CHARS
347 MEM_ATTRIBUTE int nr_of_chars;
349 MEM_ATTRIBUTE int field_width;
350 MEM_ATTRIBUTE char format_flag;
351 enum PLUS_SPACE_FLAGS {
352 PSF_NONE, PSF_PLUS, PSF_MINUS
356 #if CONFIG_PRINTF_OCTAL_FORMATTER
360 MEM_ATTRIBUTE struct {
361 enum PLUS_SPACE_FLAGS plus_space_flag : 2;
362 #if CONFIG_PRINTF_OCTAL_FORMATTER
363 enum DIV_FACTOR div_factor : 2;
365 enum DIV_FACTOR div_factor : 1;
367 bool left_adjust : 1;
368 bool l_L_modifier : 1;
370 bool alternate_flag : 1;
371 bool nonzero_value : 1;
377 MEM_ATTRIBUTE unsigned long ulong;
379 #if CONFIG_PRINTF > PRINTF_NOFLOAT
380 MEM_ATTRIBUTE max_float_t fvalue;
383 MEM_ATTRIBUTE char *buf_pointer;
384 MEM_ATTRIBUTE char *ptr;
385 MEM_ATTRIBUTE const char *hex;
386 MEM_ATTRIBUTE char buf[FRMWRI_BUFSIZE];
388 #if CONFIG_PRINTF_COUNT_CHARS
391 for (;;) /* Until full format string read */
393 while ((format_flag = PGM_READ_CHAR(format++)) != '%') /* Until '%' or '\0' */
396 #if CONFIG_PRINTF_RETURN_COUNT
397 return (nr_of_chars);
401 put_one_char(format_flag, secret_pointer);
402 #if CONFIG_PRINTF_COUNT_CHARS
406 if (PGM_READ_CHAR(format) == '%') /* %% prints as % */
409 put_one_char('%', secret_pointer);
410 #if CONFIG_PRINTF_COUNT_CHARS
416 flags.left_adjust = false;
417 flags.alternate_flag = false;
418 flags.plus_space_flag = PSF_NONE;
419 flags.zeropad = false;
421 flags.progmem = false;
423 ptr = buf_pointer = &buf[0];
426 /* check for leading '-', '+', ' ','#' or '0' flags */
429 switch (PGM_READ_CHAR(format))
432 if (flags.plus_space_flag)
435 flags.plus_space_flag = PSF_PLUS;
438 flags.left_adjust = true;
441 flags.alternate_flag = true;
444 flags.zeropad = true;
452 /* Optional field width (may be '*') */
453 if (PGM_READ_CHAR(format) == '*')
455 field_width = va_arg(ap, int);
458 field_width = -field_width;
459 flags.left_adjust = true;
466 while (PGM_READ_CHAR(format) >= '0' && PGM_READ_CHAR(format) <= '9')
467 field_width = field_width * 10 + (PGM_READ_CHAR(format++) - '0');
470 if (flags.left_adjust)
471 flags.zeropad = false;
473 /* Optional precision (or '*') */
474 if (PGM_READ_CHAR(format) == '.')
476 if (PGM_READ_CHAR(++format) == '*')
478 precision = va_arg(ap, int);
484 while (PGM_READ_CHAR(format) >= '0' && PGM_READ_CHAR(format) <= '9')
485 precision = precision * 10 + (PGM_READ_CHAR(format++) - '0');
491 /* At this point, "left_adjust" is nonzero if there was
492 * a sign, "zeropad" is 1 if there was a leading zero
493 * and 0 otherwise, "field_width" and "precision"
494 * contain numbers corresponding to the digit strings
495 * before and after the decimal point, respectively,
496 * and "plus_space_flag" is either 0 (no flag) or
497 * contains a plus or space character. If there was no
498 * decimal point, "precision" will be -1.
501 flags.l_L_modifier = false;
502 flags.h_modifier = false;
504 /* Optional 'l','L','z' or 'h' modifier? */
505 switch (PGM_READ_CHAR(format))
510 flags.l_L_modifier = true;
514 flags.h_modifier = true;
520 * At exit from the following switch, we will emit
521 * the characters starting at "buf_pointer" and
524 switch (format_flag = PGM_READ_CHAR(format++))
526 #if CONFIG_PRINTF_N_FORMATTER
528 if (sizeof(short) != sizeof(int))
530 if (sizeof(int) != sizeof(long))
533 *va_arg(ap, short *) = nr_of_chars;
534 else if (flags.l_L_modifier)
535 *va_arg(ap, long *) = nr_of_chars;
537 *va_arg(ap, int *) = nr_of_chars;
542 *va_arg(ap, short *) = nr_of_chars;
544 *va_arg(ap, int *) = nr_of_chars;
549 if (flags.l_L_modifier)
550 *va_arg(ap, long *) = nr_of_chars;
552 *va_arg(ap, int *) = nr_of_chars;
557 buf[0] = va_arg(ap, int);
561 /* Custom formatter for strings in program memory. */
564 flags.progmem = true;
569 if ( !(buf_pointer = va_arg(ap, char *)) )
570 buf_pointer = null_pointer;
575 * Move `ptr' to the last character of the
576 * string that will be actually printed.
582 for (n=0; pgm_read_char(ptr) && n < precision; n++)
587 for (n=0; *ptr && n < precision; n++)
591 #if CONFIG_PRINTF_OCTAL_FORMATTER
593 if (flags.alternate_flag && !precision)
601 if (format_flag == 'p')
602 #if defined(__AVR__) || defined(__I196__) /* 16bit pointers */
603 ulong = (unsigned long)(unsigned short)va_arg(ap, char *);
604 #else /* 32bit pointers */
605 ulong = (unsigned long)va_arg(ap, char *);
606 #endif /* 32bit pointers */
607 else if (flags.l_L_modifier)
608 ulong = va_arg(ap, unsigned long);
609 else if (flags.h_modifier)
610 ulong = (unsigned long)(unsigned short)va_arg(ap, unsigned int);
612 ulong = va_arg(ap, unsigned int);
615 #if CONFIG_PRINTF_OCTAL_FORMATTER
616 (format_flag == 'o') ? DIV_OCT :
618 (format_flag == 'u') ? DIV_DEC : DIV_HEX;
619 flags.plus_space_flag = PSF_NONE;
620 goto INTEGRAL_CONVERSION;
624 if (flags.l_L_modifier)
625 ulong = (unsigned long)(long)va_arg(ap, long);
627 ulong = (unsigned long)(long)va_arg(ap, int);
630 if ((signed long)ulong < 0)
632 flags.plus_space_flag = PSF_MINUS;
633 ulong = (unsigned long)(-((signed long)ulong));
636 flags.div_factor = DIV_DEC;
638 /* Now convert to digits */
640 ptr = buf_pointer = &buf[FRMWRI_BUFSIZE - 1];
641 flags.nonzero_value = (ulong != 0);
643 /* No char if zero and zero precision */
644 if (precision != 0 || flags.nonzero_value)
646 switch (flags.div_factor)
650 *--buf_pointer = hex[ulong % 10];
656 *--buf_pointer = hex[ulong % 16];
659 #if CONFIG_PRINTF_OCTAL_FORMATTER
662 *--buf_pointer = hex[ulong % 8];
669 /* "precision" takes precedence */
672 precision = field_width - (flags.plus_space_flag != PSF_NONE);
673 while (precision > (int)(ptr - buf_pointer))
674 *--buf_pointer = '0';
676 if (flags.alternate_flag && flags.nonzero_value)
678 if (format_flag == 'x' || format_flag == 'X')
680 *--buf_pointer = format_flag;
681 *--buf_pointer = '0';
683 #if CONFIG_PRINTF_OCTAL_FORMATTER
684 else if ((format_flag == 'o') && (*buf_pointer != '0'))
686 *--buf_pointer = '0';
690 ASSERT(buf_pointer >= buf);
693 #if CONFIG_PRINTF > PRINTF_NOFLOAT
702 goto FLOATING_CONVERSION;
714 if (sizeof(double) != sizeof(max_float_t))
716 fvalue = flags.l_L_modifier ?
717 va_arg(ap,max_float_t) : va_arg(ap,double);
720 fvalue = va_arg(ap,max_float_t);
724 flags.plus_space_flag = PSF_MINUS;
727 ptr = float_conversion (fvalue,
729 buf_pointer += field_width,
732 flags.alternate_flag);
735 precision = field_width - (flags.plus_space_flag != PSF_NONE);
736 while (precision > ptr - buf_pointer)
737 *--buf_pointer = '0';
741 #endif /* CONFIG_PRINTF <= PRINTF_NOFLOAT */
743 case '\0': /* Really bad place to find NUL in */
747 /* Undefined conversion! */
748 ptr = buf_pointer = bad_conversion;
749 ptr += sizeof(bad_conversion) - 1;
755 * This part emittes the formatted string to "put_one_char".
758 /* If field_width == 0 then nothing should be written. */
759 precision = ptr - buf_pointer;
761 if ( precision > field_width)
767 n = field_width - precision - (flags.plus_space_flag != PSF_NONE);
770 /* emit any leading pad characters */
771 if (!flags.left_adjust)
774 put_one_char(' ', secret_pointer);
775 #if CONFIG_PRINTF_COUNT_CHARS
780 /* emit flag characters (if any) */
781 if (flags.plus_space_flag)
783 put_one_char(flags.plus_space_flag == PSF_PLUS ? '+' : '-', secret_pointer);
784 #if CONFIG_PRINTF_COUNT_CHARS
792 while (--precision >= 0)
794 put_one_char(pgm_read_char(buf_pointer++), secret_pointer);
795 #if CONFIG_PRINTF_COUNT_CHARS
801 #endif /* CPU_HARVARD */
803 /* emit the string itself */
804 while (--precision >= 0)
806 put_one_char(*buf_pointer++, secret_pointer);
807 #if CONFIG_PRINTF_COUNT_CHARS
813 /* emit trailing space characters */
814 if (flags.left_adjust)
817 put_one_char(' ', secret_pointer);
818 #if CONFIG_PRINTF_COUNT_CHARS
824 #else /* PRINTF_REDUCED starts here */
826 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
827 bool l_modifier, h_modifier;
828 unsigned long u_val, div_val;
830 unsigned int u_val, div_val;
831 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
834 unsigned int nr_of_chars, base;
839 for (;;) /* Until full format string read */
841 while ((format_flag = PGM_READ_CHAR(format++)) != '%') /* Until '%' or '\0' */
844 return (nr_of_chars);
845 put_one_char(format_flag, secret_pointer);
849 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
851 * Optional 'l', 'z' or 'h' modifiers?
853 l_modifier = h_modifier = false;
854 switch (PGM_READ_CHAR(format))
858 /* for the 'z' modifier, we make this assumption */
859 STATIC_ASSERT(sizeof(size_t) == sizeof(long));
869 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
871 switch (format_flag = PGM_READ_CHAR(format++))
874 format_flag = va_arg(ap, int);
876 put_one_char(format_flag, secret_pointer);
881 ptr = va_arg(ap, char *);
882 while ((format_flag = *ptr++))
884 put_one_char(format_flag, secret_pointer);
894 div_val = 0x40000000;
895 goto CONVERSION_LOOP;
902 div_val = 1000000000;
903 goto CONVERSION_LOOP;
911 div_val = 0x10000000;
914 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
917 if (format_flag == 'd')
918 u_val = (short)va_arg(ap, int);
920 u_val = (unsigned short)va_arg(ap, int);
923 u_val = va_arg(ap, long);
926 if (format_flag == 'd')
927 u_val = va_arg(ap, int);
929 u_val = va_arg(ap, unsigned int);
932 #else /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
933 u_val = va_arg(ap,int);
934 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
935 if (format_flag == 'd')
937 if (((int)u_val) < 0)
940 put_one_char('-', secret_pointer);
944 while (div_val > 1 && div_val > u_val)
950 outChar = (u_val / div_val) + '0';
953 if (format_flag == 'x')
954 outChar += 'a'-'9'-1;
956 outChar += 'A'-'9'-1;
958 put_one_char(outChar, secret_pointer);
965 } /* end switch(format_flag...) */
967 #endif /* CONFIG_PRINTF > PRINTF_REDUCED */
970 #endif /* CONFIG_PRINTF */