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 /*bernie: save some memory, who cares about floats with lots of decimals? */
110 #define FRMWRI_BUFSIZE 134
111 #warning FIXME:134 is too much, the code must be fixed to have a lower precision limit
114 * Conservative estimate. Should be (probably) 12 (which is the size necessary
115 * to represent (2^32-1) in octal plus the sign bit.
117 #define FRMWRI_BUFSIZE 16
120 /* Probably useful for fancy microcontrollers such as the PIC, nobody knows. */
121 #ifndef MEM_ATTRIBUTE
122 #define MEM_ATTRIBUTE
125 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
126 #define IS_SHORT (h_modifier || (sizeof(int) == 2 && !l_modifier))
128 #define IS_SHORT (sizeof(int) == 2)
129 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
132 #if CONFIG_PRINTF > PRINTF_NOFLOAT
134 static char *float_conversion(MEM_ATTRIBUTE max_float_t value,
135 MEM_ATTRIBUTE short nr_of_digits,
136 MEM_ATTRIBUTE char *buf,
137 MEM_ATTRIBUTE char format_flag,
138 MEM_ATTRIBUTE char g_flag,
139 MEM_ATTRIBUTE bool alternate_flag)
141 MEM_ATTRIBUTE char *cp;
142 MEM_ATTRIBUTE char *buf_pointer;
143 MEM_ATTRIBUTE short n, i, dec_point_pos, integral_10_log;
150 while (value >= 1e11) /* To speed up things a bit */
153 integral_10_log += 10;
161 else if (value) /* Not just 0.0 */
163 while (value <= 1e-10) /* To speed up things a bit */
166 integral_10_log -= 10;
176 if (integral_10_log < nr_of_digits && integral_10_log >= -4)
179 nr_of_digits -= integral_10_log;
183 /* %#G - No removal of trailing zeros */
186 /* %G - Removal of trailing zeros */
187 alternate_flag = true;
197 /* Less than one... */
198 if (integral_10_log < 0)
200 *buf_pointer++ = '0';
201 if ((n = nr_of_digits) || alternate_flag)
202 *buf_pointer++ = '.';
204 while (--i > integral_10_log && nr_of_digits)
206 *buf_pointer++ = '0';
209 if (integral_10_log < (-n - 1))
210 /* Nothing more to do */
216 dec_point_pos = - integral_10_log;
221 while (i <= nr_of_digits )
223 value -= (max_float_t)(n = (short)value); /* n=Digit value=Remainder */
224 value *= 10; /* Prepare for next shot */
225 *buf_pointer++ = n + '0';
226 if ( ! i++ && (nr_of_digits || alternate_flag))
227 *buf_pointer++ = '.';
230 /* Rounding possible */
234 cp = buf_pointer - 1;
239 if ( (*cp += n) == ('9' + 1) )
247 } while (cp-- > buf);
256 if (*(cp - 1) == '.')
281 /* %G - Remove trailing zeros */
284 while (*(buf_pointer - 1) == '0')
286 if (*(buf_pointer - 1) == '.')
293 *buf_pointer++ = format_flag;
294 if (integral_10_log < 0)
296 *buf_pointer++ = '-';
297 integral_10_log = -integral_10_log;
300 *buf_pointer++ = '+';
306 *buf_pointer++ = (integral_10_log % 10) + '0';
307 integral_10_log /= 10;
308 } while ( integral_10_log || n < 2 );
309 for ( i = n ; n > 0 ; n-- )
310 *(buf_pointer - 11 - i + n) = *(buf_pointer - n);
313 return (buf_pointer);
316 #endif /* CONFIG_PRINTF > PRINTF_NOFLOAT */
319 * This routine forms the core and entry of the formatter.
321 * The conversion performed conforms to the ANSI specification for "printf".
324 PGM_FUNC(_formatted_write)(const char * PGM_ATTR format,
325 void put_one_char(char, void *),
326 void *secret_pointer,
329 #if CONFIG_PRINTF > PRINTF_REDUCED
330 MEM_ATTRIBUTE static char bad_conversion[] = "???";
331 MEM_ATTRIBUTE static char null_pointer[] = "<NULL>";
333 MEM_ATTRIBUTE int precision;
335 #if CONFIG_PRINTF_COUNT_CHARS
336 MEM_ATTRIBUTE int nr_of_chars;
338 MEM_ATTRIBUTE int field_width;
339 MEM_ATTRIBUTE char format_flag;
340 enum PLUS_SPACE_FLAGS {
341 PSF_NONE, PSF_PLUS, PSF_MINUS
345 #if CONFIG_PRINTF_OCTAL_FORMATTER
349 MEM_ATTRIBUTE struct {
350 enum PLUS_SPACE_FLAGS plus_space_flag : 2;
351 #if CONFIG_PRINTF_OCTAL_FORMATTER
352 enum DIV_FACTOR div_factor : 2;
354 enum DIV_FACTOR div_factor : 1;
356 bool left_adjust : 1;
357 bool l_L_modifier : 1;
359 bool alternate_flag : 1;
360 bool nonzero_value : 1;
366 MEM_ATTRIBUTE unsigned long ulong;
368 #if CONFIG_PRINTF > PRINTF_NOFLOAT
369 MEM_ATTRIBUTE max_float_t fvalue;
372 MEM_ATTRIBUTE char *buf_pointer;
373 MEM_ATTRIBUTE char *ptr;
374 MEM_ATTRIBUTE const char *hex;
375 MEM_ATTRIBUTE char buf[FRMWRI_BUFSIZE];
377 #if CONFIG_PRINTF_COUNT_CHARS
380 for (;;) /* Until full format string read */
382 while ((format_flag = PGM_READ_CHAR(format++)) != '%') /* Until '%' or '\0' */
385 #if CONFIG_PRINTF_RETURN_COUNT
386 return (nr_of_chars);
390 put_one_char(format_flag, secret_pointer);
391 #if CONFIG_PRINTF_COUNT_CHARS
395 if (PGM_READ_CHAR(format) == '%') /* %% prints as % */
398 put_one_char('%', secret_pointer);
399 #if CONFIG_PRINTF_COUNT_CHARS
405 flags.left_adjust = false;
406 flags.alternate_flag = false;
407 flags.plus_space_flag = PSF_NONE;
408 flags.zeropad = false;
410 flags.progmem = false;
412 ptr = buf_pointer = &buf[0];
415 /* check for leading '-', '+', ' ','#' or '0' flags */
418 switch (PGM_READ_CHAR(format))
421 if (flags.plus_space_flag)
424 flags.plus_space_flag = PSF_PLUS;
427 flags.left_adjust = true;
430 flags.alternate_flag = true;
433 flags.zeropad = true;
441 /* Optional field width (may be '*') */
442 if (PGM_READ_CHAR(format) == '*')
444 field_width = va_arg(ap, int);
447 field_width = -field_width;
448 flags.left_adjust = true;
455 while (PGM_READ_CHAR(format) >= '0' && PGM_READ_CHAR(format) <= '9')
456 field_width = field_width * 10 + (PGM_READ_CHAR(format++) - '0');
459 if (flags.left_adjust)
460 flags.zeropad = false;
462 /* Optional precision (or '*') */
463 if (PGM_READ_CHAR(format) == '.')
465 if (PGM_READ_CHAR(++format) == '*')
467 precision = va_arg(ap, int);
473 while (PGM_READ_CHAR(format) >= '0' && PGM_READ_CHAR(format) <= '9')
474 precision = precision * 10 + (PGM_READ_CHAR(format++) - '0');
480 /* At this point, "left_adjust" is nonzero if there was
481 * a sign, "zeropad" is 1 if there was a leading zero
482 * and 0 otherwise, "field_width" and "precision"
483 * contain numbers corresponding to the digit strings
484 * before and after the decimal point, respectively,
485 * and "plus_space_flag" is either 0 (no flag) or
486 * contains a plus or space character. If there was no
487 * decimal point, "precision" will be -1.
490 flags.l_L_modifier = false;
491 flags.h_modifier = false;
493 /* Optional 'l','L','z' or 'h' modifier? */
494 switch (PGM_READ_CHAR(format))
499 flags.l_L_modifier = true;
503 flags.h_modifier = true;
509 * At exit from the following switch, we will emit
510 * the characters starting at "buf_pointer" and
513 switch (format_flag = PGM_READ_CHAR(format++))
515 #if CONFIG_PRINTF_N_FORMATTER
517 if (sizeof(short) != sizeof(int))
519 if (sizeof(int) != sizeof(long))
522 *va_arg(ap, short *) = nr_of_chars;
523 else if (flags.l_L_modifier)
524 *va_arg(ap, long *) = nr_of_chars;
526 *va_arg(ap, int *) = nr_of_chars;
531 *va_arg(ap, short *) = nr_of_chars;
533 *va_arg(ap, int *) = nr_of_chars;
538 if (flags.l_L_modifier)
539 *va_arg(ap, long *) = nr_of_chars;
541 *va_arg(ap, int *) = nr_of_chars;
546 buf[0] = va_arg(ap, int);
550 /* Custom formatter for strings in program memory. */
553 flags.progmem = true;
558 if ( !(buf_pointer = va_arg(ap, char *)) )
559 buf_pointer = null_pointer;
564 * Move `ptr' to the last character of the
565 * string that will be actually printed.
571 for (n=0; pgm_read_char(ptr) && n < precision; n++)
576 for (n=0; *ptr && n < precision; n++)
580 #if CONFIG_PRINTF_OCTAL_FORMATTER
582 if (flags.alternate_flag && !precision)
590 if (format_flag == 'p')
591 #if defined(__AVR__) || defined(__I196__) /* 16bit pointers */
592 ulong = (unsigned long)(unsigned short)va_arg(ap, char *);
593 #else /* 32bit pointers */
594 ulong = (unsigned long)va_arg(ap, char *);
595 #endif /* 32bit pointers */
596 else if (flags.l_L_modifier)
597 ulong = va_arg(ap, unsigned long);
598 else if (flags.h_modifier)
599 ulong = (unsigned long)(unsigned short)va_arg(ap, unsigned int);
601 ulong = va_arg(ap, unsigned int);
604 #if CONFIG_PRINTF_OCTAL_FORMATTER
605 (format_flag == 'o') ? DIV_OCT :
607 (format_flag == 'u') ? DIV_DEC : DIV_HEX;
608 flags.plus_space_flag = PSF_NONE;
609 goto INTEGRAL_CONVERSION;
613 if (flags.l_L_modifier)
614 ulong = (unsigned long)(long)va_arg(ap, long);
616 ulong = (unsigned long)(long)va_arg(ap, int);
619 if ((signed long)ulong < 0)
621 flags.plus_space_flag = PSF_MINUS;
622 ulong = (unsigned long)(-((signed long)ulong));
625 flags.div_factor = DIV_DEC;
627 /* Now convert to digits */
629 ptr = buf_pointer = &buf[FRMWRI_BUFSIZE - 1];
630 flags.nonzero_value = (ulong != 0);
632 /* No char if zero and zero precision */
633 if (precision != 0 || flags.nonzero_value)
635 switch (flags.div_factor)
639 *--buf_pointer = hex[ulong % 10];
645 *--buf_pointer = hex[ulong % 16];
648 #if CONFIG_PRINTF_OCTAL_FORMATTER
651 *--buf_pointer = hex[ulong % 8];
658 /* "precision" takes precedence */
661 precision = field_width - (flags.plus_space_flag != PSF_NONE);
662 while (precision > (int)(ptr - buf_pointer))
663 *--buf_pointer = '0';
665 if (flags.alternate_flag && flags.nonzero_value)
667 if (format_flag == 'x' || format_flag == 'X')
669 *--buf_pointer = format_flag;
670 *--buf_pointer = '0';
672 #if CONFIG_PRINTF_OCTAL_FORMATTER
673 else if ((format_flag == 'o') && (*buf_pointer != '0'))
675 *--buf_pointer = '0';
679 ASSERT(buf_pointer >= buf);
682 #if CONFIG_PRINTF > PRINTF_NOFLOAT
691 goto FLOATING_CONVERSION;
703 if (sizeof(double) != sizeof(max_float_t))
705 fvalue = flags.l_L_modifier ?
706 va_arg(ap,max_float_t) : va_arg(ap,double);
709 fvalue = va_arg(ap,max_float_t);
713 flags.plus_space_flag = PSF_MINUS;
716 ptr = float_conversion (fvalue,
718 buf_pointer += field_width,
721 flags.alternate_flag);
724 precision = field_width - (flags.plus_space_flag != PSF_NONE);
725 while (precision > ptr - buf_pointer)
726 *--buf_pointer = '0';
730 #endif /* CONFIG_PRINTF <= PRINTF_NOFLOAT */
732 case '\0': /* Really bad place to find NUL in */
736 /* Undefined conversion! */
737 ptr = buf_pointer = bad_conversion;
738 ptr += sizeof(bad_conversion) - 1;
744 * This part emittes the formatted string to "put_one_char".
747 /* If field_width == 0 then nothing should be written. */
748 precision = ptr - buf_pointer;
750 if ( precision > field_width)
756 n = field_width - precision - (flags.plus_space_flag != PSF_NONE);
759 /* emit any leading pad characters */
760 if (!flags.left_adjust)
763 put_one_char(' ', secret_pointer);
764 #if CONFIG_PRINTF_COUNT_CHARS
769 /* emit flag characters (if any) */
770 if (flags.plus_space_flag)
772 put_one_char(flags.plus_space_flag == PSF_PLUS ? '+' : '-', secret_pointer);
773 #if CONFIG_PRINTF_COUNT_CHARS
781 while (--precision >= 0)
783 put_one_char(pgm_read_char(buf_pointer++), secret_pointer);
784 #if CONFIG_PRINTF_COUNT_CHARS
790 #endif /* CPU_HARVARD */
792 /* emit the string itself */
793 while (--precision >= 0)
795 put_one_char(*buf_pointer++, secret_pointer);
796 #if CONFIG_PRINTF_COUNT_CHARS
802 /* emit trailing space characters */
803 if (flags.left_adjust)
806 put_one_char(' ', secret_pointer);
807 #if CONFIG_PRINTF_COUNT_CHARS
813 #else /* PRINTF_REDUCED starts here */
815 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
816 bool l_modifier, h_modifier;
817 unsigned long u_val, div_val;
819 unsigned int u_val, div_val;
820 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
823 unsigned int nr_of_chars, base;
828 for (;;) /* Until full format string read */
830 while ((format_flag = PGM_READ_CHAR(format++)) != '%') /* Until '%' or '\0' */
833 return (nr_of_chars);
834 put_one_char(format_flag, secret_pointer);
838 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
840 * Optional 'l', 'z' or 'h' modifiers?
842 l_modifier = h_modifier = false;
843 switch (PGM_READ_CHAR(format))
847 /* for the 'z' modifier, we make this assumption */
848 STATIC_ASSERT(sizeof(size_t) == sizeof(long));
858 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
860 switch (format_flag = PGM_READ_CHAR(format++))
863 format_flag = va_arg(ap, int);
865 put_one_char(format_flag, secret_pointer);
870 ptr = va_arg(ap, char *);
871 while ((format_flag = *ptr++))
873 put_one_char(format_flag, secret_pointer);
883 div_val = 0x40000000;
884 goto CONVERSION_LOOP;
891 div_val = 1000000000;
892 goto CONVERSION_LOOP;
900 div_val = 0x10000000;
903 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
906 if (format_flag == 'd')
907 u_val = (short)va_arg(ap, int);
909 u_val = (unsigned short)va_arg(ap, int);
912 u_val = va_arg(ap, long);
915 if (format_flag == 'd')
916 u_val = va_arg(ap, int);
918 u_val = va_arg(ap, unsigned int);
921 #else /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
922 u_val = va_arg(ap,int);
923 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
924 if (format_flag == 'd')
926 if (((int)u_val) < 0)
929 put_one_char('-', secret_pointer);
933 while (div_val > 1 && div_val > u_val)
939 outChar = (u_val / div_val) + '0';
942 if (format_flag == 'x')
943 outChar += 'a'-'9'-1;
945 outChar += 'A'-'9'-1;
947 put_one_char(outChar, secret_pointer);
954 } /* end switch(format_flag...) */
956 #endif /* CONFIG_PRINTF > PRINTF_REDUCED */
959 #endif /* CONFIG_PRINTF */