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 #if CONFIG_FRMWRI_BUFSIZE
110 #define FRMWRI_BUFSIZE CONFIG_FRMWRI_BUFSIZE
112 /* Conservative estimate. Max float is 3.40282e+038, so %f (but not %e or %g) must have
113 * space for: sign + all 38 digits + '.' + 6 decimal digits (default)
114 * Use a high value to avoid unexpected buffer overflows.
116 #define FRMWRI_BUFSIZE 134
119 #if CONFIG_FRMWRI_BUFSIZE
120 #define FRMWRI_BUFSIZE CONFIG_FRMWRI_BUFSIZE
123 * Conservative estimate. Should be (probably) 12 (which is the size necessary
124 * to represent (2^32-1) in octal plus the sign bit.
126 #define FRMWRI_BUFSIZE 16
130 /* Probably useful for fancy microcontrollers such as the PIC, nobody knows. */
131 #ifndef MEM_ATTRIBUTE
132 #define MEM_ATTRIBUTE
135 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
136 #define IS_SHORT (h_modifier || (sizeof(int) == 2 && !l_modifier))
138 #define IS_SHORT (sizeof(int) == 2)
139 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
142 #if CONFIG_PRINTF > PRINTF_NOFLOAT
144 static char *float_conversion(MEM_ATTRIBUTE max_float_t value,
145 MEM_ATTRIBUTE short nr_of_digits,
146 MEM_ATTRIBUTE char *buf,
147 MEM_ATTRIBUTE char format_flag,
148 MEM_ATTRIBUTE char g_flag,
149 MEM_ATTRIBUTE bool alternate_flag)
151 MEM_ATTRIBUTE char *cp;
152 MEM_ATTRIBUTE char *buf_pointer;
153 MEM_ATTRIBUTE short n, i, dec_point_pos, integral_10_log;
160 while (value >= 1e11) /* To speed up things a bit */
163 integral_10_log += 10;
171 else if (value) /* Not just 0.0 */
173 while (value <= 1e-10) /* To speed up things a bit */
176 integral_10_log -= 10;
186 if (integral_10_log < nr_of_digits && integral_10_log >= -4)
189 nr_of_digits -= integral_10_log;
193 /* %#G - No removal of trailing zeros */
196 /* %G - Removal of trailing zeros */
197 alternate_flag = true;
207 /* Less than one... */
208 if (integral_10_log < 0)
210 *buf_pointer++ = '0';
211 if ((n = nr_of_digits) || alternate_flag)
212 *buf_pointer++ = '.';
214 while (--i > integral_10_log && nr_of_digits)
216 *buf_pointer++ = '0';
219 if (integral_10_log < (-n - 1))
220 /* Nothing more to do */
226 dec_point_pos = - integral_10_log;
231 while (i <= nr_of_digits )
233 value -= (max_float_t)(n = (short)value); /* n=Digit value=Remainder */
234 value *= 10; /* Prepare for next shot */
235 *buf_pointer++ = n + '0';
236 if ( ! i++ && (nr_of_digits || alternate_flag))
237 *buf_pointer++ = '.';
240 /* Rounding possible */
244 cp = buf_pointer - 1;
249 if ( (*cp += n) == ('9' + 1) )
257 } while (cp-- > buf);
266 if (*(cp - 1) == '.')
291 /* %G - Remove trailing zeros */
294 while (*(buf_pointer - 1) == '0')
296 if (*(buf_pointer - 1) == '.')
303 *buf_pointer++ = format_flag;
304 if (integral_10_log < 0)
306 *buf_pointer++ = '-';
307 integral_10_log = -integral_10_log;
310 *buf_pointer++ = '+';
316 *buf_pointer++ = (integral_10_log % 10) + '0';
317 integral_10_log /= 10;
318 } while ( integral_10_log || n < 2 );
319 for ( i = n ; n > 0 ; n-- )
320 *(buf_pointer - 11 - i + n) = *(buf_pointer - n);
323 return (buf_pointer);
326 #endif /* CONFIG_PRINTF > PRINTF_NOFLOAT */
329 * This routine forms the core and entry of the formatter.
331 * The conversion performed conforms to the ANSI specification for "printf".
334 PGM_FUNC(_formatted_write)(const char * PGM_ATTR format,
335 void put_one_char(char, void *),
336 void *secret_pointer,
339 #if CONFIG_PRINTF > PRINTF_REDUCED
340 MEM_ATTRIBUTE static char bad_conversion[] = "???";
341 MEM_ATTRIBUTE static char null_pointer[] = "<NULL>";
343 MEM_ATTRIBUTE int precision;
345 #if CONFIG_PRINTF_COUNT_CHARS
346 MEM_ATTRIBUTE int nr_of_chars;
348 MEM_ATTRIBUTE int field_width;
349 MEM_ATTRIBUTE char format_flag;
350 enum PLUS_SPACE_FLAGS {
351 PSF_NONE, PSF_PLUS, PSF_MINUS
355 #if CONFIG_PRINTF_OCTAL_FORMATTER
359 MEM_ATTRIBUTE struct {
360 enum PLUS_SPACE_FLAGS plus_space_flag : 2;
361 #if CONFIG_PRINTF_OCTAL_FORMATTER
362 enum DIV_FACTOR div_factor : 2;
364 enum DIV_FACTOR div_factor : 1;
366 bool left_adjust : 1;
367 bool l_L_modifier : 1;
369 bool alternate_flag : 1;
370 bool nonzero_value : 1;
376 MEM_ATTRIBUTE unsigned long ulong;
378 #if CONFIG_PRINTF > PRINTF_NOFLOAT
379 MEM_ATTRIBUTE max_float_t fvalue;
382 MEM_ATTRIBUTE char *buf_pointer;
383 MEM_ATTRIBUTE char *ptr;
384 MEM_ATTRIBUTE const char *hex;
385 MEM_ATTRIBUTE char buf[FRMWRI_BUFSIZE];
387 #if CONFIG_PRINTF_COUNT_CHARS
390 for (;;) /* Until full format string read */
392 while ((format_flag = PGM_READ_CHAR(format++)) != '%') /* Until '%' or '\0' */
395 #if CONFIG_PRINTF_RETURN_COUNT
396 return (nr_of_chars);
400 put_one_char(format_flag, secret_pointer);
401 #if CONFIG_PRINTF_COUNT_CHARS
405 if (PGM_READ_CHAR(format) == '%') /* %% prints as % */
408 put_one_char('%', secret_pointer);
409 #if CONFIG_PRINTF_COUNT_CHARS
415 flags.left_adjust = false;
416 flags.alternate_flag = false;
417 flags.plus_space_flag = PSF_NONE;
418 flags.zeropad = false;
420 flags.progmem = false;
422 ptr = buf_pointer = &buf[0];
425 /* check for leading '-', '+', ' ','#' or '0' flags */
428 switch (PGM_READ_CHAR(format))
431 if (flags.plus_space_flag)
434 flags.plus_space_flag = PSF_PLUS;
437 flags.left_adjust = true;
440 flags.alternate_flag = true;
443 flags.zeropad = true;
451 /* Optional field width (may be '*') */
452 if (PGM_READ_CHAR(format) == '*')
454 field_width = va_arg(ap, int);
457 field_width = -field_width;
458 flags.left_adjust = true;
465 while (PGM_READ_CHAR(format) >= '0' && PGM_READ_CHAR(format) <= '9')
466 field_width = field_width * 10 + (PGM_READ_CHAR(format++) - '0');
469 if (flags.left_adjust)
470 flags.zeropad = false;
472 /* Optional precision (or '*') */
473 if (PGM_READ_CHAR(format) == '.')
475 if (PGM_READ_CHAR(++format) == '*')
477 precision = va_arg(ap, int);
483 while (PGM_READ_CHAR(format) >= '0' && PGM_READ_CHAR(format) <= '9')
484 precision = precision * 10 + (PGM_READ_CHAR(format++) - '0');
490 /* At this point, "left_adjust" is nonzero if there was
491 * a sign, "zeropad" is 1 if there was a leading zero
492 * and 0 otherwise, "field_width" and "precision"
493 * contain numbers corresponding to the digit strings
494 * before and after the decimal point, respectively,
495 * and "plus_space_flag" is either 0 (no flag) or
496 * contains a plus or space character. If there was no
497 * decimal point, "precision" will be -1.
500 flags.l_L_modifier = false;
501 flags.h_modifier = false;
503 /* Optional 'l','L','z' or 'h' modifier? */
504 switch (PGM_READ_CHAR(format))
509 flags.l_L_modifier = true;
513 flags.h_modifier = true;
519 * At exit from the following switch, we will emit
520 * the characters starting at "buf_pointer" and
523 switch (format_flag = PGM_READ_CHAR(format++))
525 #if CONFIG_PRINTF_N_FORMATTER
527 if (sizeof(short) != sizeof(int))
529 if (sizeof(int) != sizeof(long))
532 *va_arg(ap, short *) = nr_of_chars;
533 else if (flags.l_L_modifier)
534 *va_arg(ap, long *) = nr_of_chars;
536 *va_arg(ap, int *) = nr_of_chars;
541 *va_arg(ap, short *) = nr_of_chars;
543 *va_arg(ap, int *) = nr_of_chars;
548 if (flags.l_L_modifier)
549 *va_arg(ap, long *) = nr_of_chars;
551 *va_arg(ap, int *) = nr_of_chars;
556 buf[0] = va_arg(ap, int);
560 /* Custom formatter for strings in program memory. */
563 flags.progmem = true;
568 if ( !(buf_pointer = va_arg(ap, char *)) )
569 buf_pointer = null_pointer;
574 * Move `ptr' to the last character of the
575 * string that will be actually printed.
581 for (n=0; pgm_read_char(ptr) && n < precision; n++)
586 for (n=0; *ptr && n < precision; n++)
590 #if CONFIG_PRINTF_OCTAL_FORMATTER
592 if (flags.alternate_flag && !precision)
600 if (format_flag == 'p')
601 #if defined(__AVR__) || defined(__I196__) /* 16bit pointers */
602 ulong = (unsigned long)(unsigned short)va_arg(ap, char *);
603 #else /* 32bit pointers */
604 ulong = (unsigned long)va_arg(ap, char *);
605 #endif /* 32bit pointers */
606 else if (flags.l_L_modifier)
607 ulong = va_arg(ap, unsigned long);
608 else if (flags.h_modifier)
609 ulong = (unsigned long)(unsigned short)va_arg(ap, unsigned int);
611 ulong = va_arg(ap, unsigned int);
614 #if CONFIG_PRINTF_OCTAL_FORMATTER
615 (format_flag == 'o') ? DIV_OCT :
617 (format_flag == 'u') ? DIV_DEC : DIV_HEX;
618 flags.plus_space_flag = PSF_NONE;
619 goto INTEGRAL_CONVERSION;
623 if (flags.l_L_modifier)
624 ulong = (unsigned long)(long)va_arg(ap, long);
626 ulong = (unsigned long)(long)va_arg(ap, int);
629 if ((signed long)ulong < 0)
631 flags.plus_space_flag = PSF_MINUS;
632 ulong = (unsigned long)(-((signed long)ulong));
635 flags.div_factor = DIV_DEC;
637 /* Now convert to digits */
639 ptr = buf_pointer = &buf[FRMWRI_BUFSIZE - 1];
640 flags.nonzero_value = (ulong != 0);
642 /* No char if zero and zero precision */
643 if (precision != 0 || flags.nonzero_value)
645 switch (flags.div_factor)
649 *--buf_pointer = hex[ulong % 10];
655 *--buf_pointer = hex[ulong % 16];
658 #if CONFIG_PRINTF_OCTAL_FORMATTER
661 *--buf_pointer = hex[ulong % 8];
668 /* "precision" takes precedence */
671 precision = field_width - (flags.plus_space_flag != PSF_NONE);
672 while (precision > (int)(ptr - buf_pointer))
673 *--buf_pointer = '0';
675 if (flags.alternate_flag && flags.nonzero_value)
677 if (format_flag == 'x' || format_flag == 'X')
679 *--buf_pointer = format_flag;
680 *--buf_pointer = '0';
682 #if CONFIG_PRINTF_OCTAL_FORMATTER
683 else if ((format_flag == 'o') && (*buf_pointer != '0'))
685 *--buf_pointer = '0';
689 ASSERT(buf_pointer >= buf);
692 #if CONFIG_PRINTF > PRINTF_NOFLOAT
701 goto FLOATING_CONVERSION;
713 if (sizeof(double) != sizeof(max_float_t))
715 fvalue = flags.l_L_modifier ?
716 va_arg(ap,max_float_t) : va_arg(ap,double);
719 fvalue = va_arg(ap,max_float_t);
723 flags.plus_space_flag = PSF_MINUS;
726 ptr = float_conversion (fvalue,
728 buf_pointer += field_width,
731 flags.alternate_flag);
734 precision = field_width - (flags.plus_space_flag != PSF_NONE);
735 while (precision > ptr - buf_pointer)
736 *--buf_pointer = '0';
740 #endif /* CONFIG_PRINTF <= PRINTF_NOFLOAT */
742 case '\0': /* Really bad place to find NUL in */
746 /* Undefined conversion! */
747 ptr = buf_pointer = bad_conversion;
748 ptr += sizeof(bad_conversion) - 1;
754 * This part emittes the formatted string to "put_one_char".
757 /* If field_width == 0 then nothing should be written. */
758 precision = ptr - buf_pointer;
760 if ( precision > field_width)
766 n = field_width - precision - (flags.plus_space_flag != PSF_NONE);
769 /* emit any leading pad characters */
770 if (!flags.left_adjust)
773 put_one_char(' ', secret_pointer);
774 #if CONFIG_PRINTF_COUNT_CHARS
779 /* emit flag characters (if any) */
780 if (flags.plus_space_flag)
782 put_one_char(flags.plus_space_flag == PSF_PLUS ? '+' : '-', secret_pointer);
783 #if CONFIG_PRINTF_COUNT_CHARS
791 while (--precision >= 0)
793 put_one_char(pgm_read_char(buf_pointer++), secret_pointer);
794 #if CONFIG_PRINTF_COUNT_CHARS
800 #endif /* CPU_HARVARD */
802 /* emit the string itself */
803 while (--precision >= 0)
805 put_one_char(*buf_pointer++, secret_pointer);
806 #if CONFIG_PRINTF_COUNT_CHARS
812 /* emit trailing space characters */
813 if (flags.left_adjust)
816 put_one_char(' ', secret_pointer);
817 #if CONFIG_PRINTF_COUNT_CHARS
823 #else /* PRINTF_REDUCED starts here */
825 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
826 bool l_modifier, h_modifier;
827 unsigned long u_val, div_val;
829 unsigned int u_val, div_val;
830 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
833 unsigned int nr_of_chars, base;
838 for (;;) /* Until full format string read */
840 while ((format_flag = PGM_READ_CHAR(format++)) != '%') /* Until '%' or '\0' */
843 return (nr_of_chars);
844 put_one_char(format_flag, secret_pointer);
848 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
850 * Optional 'l', 'z' or 'h' modifiers?
852 l_modifier = h_modifier = false;
853 switch (PGM_READ_CHAR(format))
857 /* for the 'z' modifier, we make this assumption */
858 STATIC_ASSERT(sizeof(size_t) == sizeof(long));
868 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
870 switch (format_flag = PGM_READ_CHAR(format++))
873 format_flag = va_arg(ap, int);
875 put_one_char(format_flag, secret_pointer);
880 ptr = va_arg(ap, char *);
881 while ((format_flag = *ptr++))
883 put_one_char(format_flag, secret_pointer);
893 div_val = 0x40000000;
894 goto CONVERSION_LOOP;
901 div_val = 1000000000;
902 goto CONVERSION_LOOP;
910 div_val = 0x10000000;
913 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
916 if (format_flag == 'd')
917 u_val = (short)va_arg(ap, int);
919 u_val = (unsigned short)va_arg(ap, int);
922 u_val = va_arg(ap, long);
925 if (format_flag == 'd')
926 u_val = va_arg(ap, int);
928 u_val = va_arg(ap, unsigned int);
931 #else /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
932 u_val = va_arg(ap,int);
933 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
934 if (format_flag == 'd')
936 if (((int)u_val) < 0)
939 put_one_char('-', secret_pointer);
943 while (div_val > 1 && div_val > u_val)
949 outChar = (u_val / div_val) + '0';
952 if (format_flag == 'x')
953 outChar += 'a'-'9'-1;
955 outChar += 'A'-'9'-1;
957 put_one_char(outChar, secret_pointer);
964 } /* end switch(format_flag...) */
966 #endif /* CONFIG_PRINTF > PRINTF_REDUCED */
969 #endif /* CONFIG_PRINTF */