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 #if !(ARCH & ARCH_NIGHTTEST)
112 #warning 134 is too much, the code must be fixed to have a lower precision limit
116 * Conservative estimate. Should be (probably) 12 (which is the size necessary
117 * to represent (2^32-1) in octal plus the sign bit.
119 #define FRMWRI_BUFSIZE 16
122 /* Probably useful for fancy microcontrollers such as the PIC, nobody knows. */
123 #ifndef MEM_ATTRIBUTE
124 #define MEM_ATTRIBUTE
127 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
128 #define IS_SHORT (h_modifier || (sizeof(int) == 2 && !l_modifier))
130 #define IS_SHORT (sizeof(int) == 2)
131 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
134 #if CONFIG_PRINTF > PRINTF_NOFLOAT
136 static char *float_conversion(MEM_ATTRIBUTE max_float_t value,
137 MEM_ATTRIBUTE short nr_of_digits,
138 MEM_ATTRIBUTE char *buf,
139 MEM_ATTRIBUTE char format_flag,
140 MEM_ATTRIBUTE char g_flag,
141 MEM_ATTRIBUTE bool alternate_flag)
143 MEM_ATTRIBUTE char *cp;
144 MEM_ATTRIBUTE char *buf_pointer;
145 MEM_ATTRIBUTE short n, i, dec_point_pos, integral_10_log;
152 while (value >= 1e11) /* To speed up things a bit */
155 integral_10_log += 10;
163 else if (value) /* Not just 0.0 */
165 while (value <= 1e-10) /* To speed up things a bit */
168 integral_10_log -= 10;
178 if (integral_10_log < nr_of_digits && integral_10_log >= -4)
181 nr_of_digits -= integral_10_log;
185 /* %#G - No removal of trailing zeros */
188 /* %G - Removal of trailing zeros */
189 alternate_flag = true;
199 /* Less than one... */
200 if (integral_10_log < 0)
202 *buf_pointer++ = '0';
203 if ((n = nr_of_digits) || alternate_flag)
204 *buf_pointer++ = '.';
206 while (--i > integral_10_log && nr_of_digits)
208 *buf_pointer++ = '0';
211 if (integral_10_log < (-n - 1))
212 /* Nothing more to do */
218 dec_point_pos = - integral_10_log;
223 while (i <= nr_of_digits )
225 value -= (max_float_t)(n = (short)value); /* n=Digit value=Remainder */
226 value *= 10; /* Prepare for next shot */
227 *buf_pointer++ = n + '0';
228 if ( ! i++ && (nr_of_digits || alternate_flag))
229 *buf_pointer++ = '.';
232 /* Rounding possible */
236 cp = buf_pointer - 1;
241 if ( (*cp += n) == ('9' + 1) )
249 } while (cp-- > buf);
258 if (*(cp - 1) == '.')
283 /* %G - Remove trailing zeros */
286 while (*(buf_pointer - 1) == '0')
288 if (*(buf_pointer - 1) == '.')
295 *buf_pointer++ = format_flag;
296 if (integral_10_log < 0)
298 *buf_pointer++ = '-';
299 integral_10_log = -integral_10_log;
302 *buf_pointer++ = '+';
308 *buf_pointer++ = (integral_10_log % 10) + '0';
309 integral_10_log /= 10;
310 } while ( integral_10_log || n < 2 );
311 for ( i = n ; n > 0 ; n-- )
312 *(buf_pointer - 11 - i + n) = *(buf_pointer - n);
315 return (buf_pointer);
318 #endif /* CONFIG_PRINTF > PRINTF_NOFLOAT */
321 * This routine forms the core and entry of the formatter.
323 * The conversion performed conforms to the ANSI specification for "printf".
326 PGM_FUNC(_formatted_write)(const char * PGM_ATTR format,
327 void put_one_char(char, void *),
328 void *secret_pointer,
331 #if CONFIG_PRINTF > PRINTF_REDUCED
332 MEM_ATTRIBUTE static char bad_conversion[] = "???";
333 MEM_ATTRIBUTE static char null_pointer[] = "<NULL>";
335 MEM_ATTRIBUTE int precision;
337 #if CONFIG_PRINTF_COUNT_CHARS
338 MEM_ATTRIBUTE int nr_of_chars;
340 MEM_ATTRIBUTE int field_width;
341 MEM_ATTRIBUTE char format_flag;
342 enum PLUS_SPACE_FLAGS {
343 PSF_NONE, PSF_PLUS, PSF_MINUS
347 #if CONFIG_PRINTF_OCTAL_FORMATTER
351 MEM_ATTRIBUTE struct {
352 enum PLUS_SPACE_FLAGS plus_space_flag : 2;
353 #if CONFIG_PRINTF_OCTAL_FORMATTER
354 enum DIV_FACTOR div_factor : 2;
356 enum DIV_FACTOR div_factor : 1;
358 bool left_adjust : 1;
359 bool l_L_modifier : 1;
361 bool alternate_flag : 1;
362 bool nonzero_value : 1;
368 MEM_ATTRIBUTE unsigned long ulong;
370 #if CONFIG_PRINTF > PRINTF_NOFLOAT
371 MEM_ATTRIBUTE max_float_t fvalue;
374 MEM_ATTRIBUTE char *buf_pointer;
375 MEM_ATTRIBUTE char *ptr;
376 MEM_ATTRIBUTE const char *hex;
377 MEM_ATTRIBUTE char buf[FRMWRI_BUFSIZE];
379 #if CONFIG_PRINTF_COUNT_CHARS
382 for (;;) /* Until full format string read */
384 while ((format_flag = PGM_READ_CHAR(format++)) != '%') /* Until '%' or '\0' */
387 #if CONFIG_PRINTF_RETURN_COUNT
388 return (nr_of_chars);
392 put_one_char(format_flag, secret_pointer);
393 #if CONFIG_PRINTF_COUNT_CHARS
397 if (PGM_READ_CHAR(format) == '%') /* %% prints as % */
400 put_one_char('%', secret_pointer);
401 #if CONFIG_PRINTF_COUNT_CHARS
407 flags.left_adjust = false;
408 flags.alternate_flag = false;
409 flags.plus_space_flag = PSF_NONE;
410 flags.zeropad = false;
412 flags.progmem = false;
414 ptr = buf_pointer = &buf[0];
417 /* check for leading '-', '+', ' ','#' or '0' flags */
420 switch (PGM_READ_CHAR(format))
423 if (flags.plus_space_flag)
426 flags.plus_space_flag = PSF_PLUS;
429 flags.left_adjust = true;
432 flags.alternate_flag = true;
435 flags.zeropad = true;
443 /* Optional field width (may be '*') */
444 if (PGM_READ_CHAR(format) == '*')
446 field_width = va_arg(ap, int);
449 field_width = -field_width;
450 flags.left_adjust = true;
457 while (PGM_READ_CHAR(format) >= '0' && PGM_READ_CHAR(format) <= '9')
458 field_width = field_width * 10 + (PGM_READ_CHAR(format++) - '0');
461 if (flags.left_adjust)
462 flags.zeropad = false;
464 /* Optional precision (or '*') */
465 if (PGM_READ_CHAR(format) == '.')
467 if (PGM_READ_CHAR(++format) == '*')
469 precision = va_arg(ap, int);
475 while (PGM_READ_CHAR(format) >= '0' && PGM_READ_CHAR(format) <= '9')
476 precision = precision * 10 + (PGM_READ_CHAR(format++) - '0');
482 /* At this point, "left_adjust" is nonzero if there was
483 * a sign, "zeropad" is 1 if there was a leading zero
484 * and 0 otherwise, "field_width" and "precision"
485 * contain numbers corresponding to the digit strings
486 * before and after the decimal point, respectively,
487 * and "plus_space_flag" is either 0 (no flag) or
488 * contains a plus or space character. If there was no
489 * decimal point, "precision" will be -1.
492 flags.l_L_modifier = false;
493 flags.h_modifier = false;
495 /* Optional 'l','L','z' or 'h' modifier? */
496 switch (PGM_READ_CHAR(format))
501 flags.l_L_modifier = true;
505 flags.h_modifier = true;
511 * At exit from the following switch, we will emit
512 * the characters starting at "buf_pointer" and
515 switch (format_flag = PGM_READ_CHAR(format++))
517 #if CONFIG_PRINTF_N_FORMATTER
519 if (sizeof(short) != sizeof(int))
521 if (sizeof(int) != sizeof(long))
524 *va_arg(ap, short *) = nr_of_chars;
525 else if (flags.l_L_modifier)
526 *va_arg(ap, long *) = nr_of_chars;
528 *va_arg(ap, int *) = nr_of_chars;
533 *va_arg(ap, short *) = nr_of_chars;
535 *va_arg(ap, int *) = nr_of_chars;
540 if (flags.l_L_modifier)
541 *va_arg(ap, long *) = nr_of_chars;
543 *va_arg(ap, int *) = nr_of_chars;
548 buf[0] = va_arg(ap, int);
552 /* Custom formatter for strings in program memory. */
555 flags.progmem = true;
560 if ( !(buf_pointer = va_arg(ap, char *)) )
561 buf_pointer = null_pointer;
566 * Move `ptr' to the last character of the
567 * string that will be actually printed.
573 for (n=0; pgm_read_char(ptr) && n < precision; n++)
578 for (n=0; *ptr && n < precision; n++)
582 #if CONFIG_PRINTF_OCTAL_FORMATTER
584 if (flags.alternate_flag && !precision)
592 if (format_flag == 'p')
593 #if defined(__AVR__) || defined(__I196__) /* 16bit pointers */
594 ulong = (unsigned long)(unsigned short)va_arg(ap, char *);
595 #else /* 32bit pointers */
596 ulong = (unsigned long)va_arg(ap, char *);
597 #endif /* 32bit pointers */
598 else if (flags.l_L_modifier)
599 ulong = va_arg(ap, unsigned long);
600 else if (flags.h_modifier)
601 ulong = (unsigned long)(unsigned short)va_arg(ap, unsigned int);
603 ulong = va_arg(ap, unsigned int);
606 #if CONFIG_PRINTF_OCTAL_FORMATTER
607 (format_flag == 'o') ? DIV_OCT :
609 (format_flag == 'u') ? DIV_DEC : DIV_HEX;
610 flags.plus_space_flag = PSF_NONE;
611 goto INTEGRAL_CONVERSION;
615 if (flags.l_L_modifier)
616 ulong = (unsigned long)(long)va_arg(ap, long);
618 ulong = (unsigned long)(long)va_arg(ap, int);
621 if ((signed long)ulong < 0)
623 flags.plus_space_flag = PSF_MINUS;
624 ulong = (unsigned long)(-((signed long)ulong));
627 flags.div_factor = DIV_DEC;
629 /* Now convert to digits */
631 ptr = buf_pointer = &buf[FRMWRI_BUFSIZE - 1];
632 flags.nonzero_value = (ulong != 0);
634 /* No char if zero and zero precision */
635 if (precision != 0 || flags.nonzero_value)
637 switch (flags.div_factor)
641 *--buf_pointer = hex[ulong % 10];
647 *--buf_pointer = hex[ulong % 16];
650 #if CONFIG_PRINTF_OCTAL_FORMATTER
653 *--buf_pointer = hex[ulong % 8];
660 /* "precision" takes precedence */
663 precision = field_width - (flags.plus_space_flag != PSF_NONE);
664 while (precision > (int)(ptr - buf_pointer))
665 *--buf_pointer = '0';
667 if (flags.alternate_flag && flags.nonzero_value)
669 if (format_flag == 'x' || format_flag == 'X')
671 *--buf_pointer = format_flag;
672 *--buf_pointer = '0';
674 #if CONFIG_PRINTF_OCTAL_FORMATTER
675 else if ((format_flag == 'o') && (*buf_pointer != '0'))
677 *--buf_pointer = '0';
681 ASSERT(buf_pointer >= buf);
684 #if CONFIG_PRINTF > PRINTF_NOFLOAT
693 goto FLOATING_CONVERSION;
705 if (sizeof(double) != sizeof(max_float_t))
707 fvalue = flags.l_L_modifier ?
708 va_arg(ap,max_float_t) : va_arg(ap,double);
711 fvalue = va_arg(ap,max_float_t);
715 flags.plus_space_flag = PSF_MINUS;
718 ptr = float_conversion (fvalue,
720 buf_pointer += field_width,
723 flags.alternate_flag);
726 precision = field_width - (flags.plus_space_flag != PSF_NONE);
727 while (precision > ptr - buf_pointer)
728 *--buf_pointer = '0';
732 #endif /* CONFIG_PRINTF <= PRINTF_NOFLOAT */
734 case '\0': /* Really bad place to find NUL in */
738 /* Undefined conversion! */
739 ptr = buf_pointer = bad_conversion;
740 ptr += sizeof(bad_conversion) - 1;
746 * This part emittes the formatted string to "put_one_char".
749 /* If field_width == 0 then nothing should be written. */
750 precision = ptr - buf_pointer;
752 if ( precision > field_width)
758 n = field_width - precision - (flags.plus_space_flag != PSF_NONE);
761 /* emit any leading pad characters */
762 if (!flags.left_adjust)
765 put_one_char(' ', secret_pointer);
766 #if CONFIG_PRINTF_COUNT_CHARS
771 /* emit flag characters (if any) */
772 if (flags.plus_space_flag)
774 put_one_char(flags.plus_space_flag == PSF_PLUS ? '+' : '-', secret_pointer);
775 #if CONFIG_PRINTF_COUNT_CHARS
783 while (--precision >= 0)
785 put_one_char(pgm_read_char(buf_pointer++), secret_pointer);
786 #if CONFIG_PRINTF_COUNT_CHARS
792 #endif /* CPU_HARVARD */
794 /* emit the string itself */
795 while (--precision >= 0)
797 put_one_char(*buf_pointer++, secret_pointer);
798 #if CONFIG_PRINTF_COUNT_CHARS
804 /* emit trailing space characters */
805 if (flags.left_adjust)
808 put_one_char(' ', secret_pointer);
809 #if CONFIG_PRINTF_COUNT_CHARS
815 #else /* PRINTF_REDUCED starts here */
817 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
818 bool l_modifier, h_modifier;
819 unsigned long u_val, div_val;
821 unsigned int u_val, div_val;
822 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
825 unsigned int nr_of_chars, base;
830 for (;;) /* Until full format string read */
832 while ((format_flag = PGM_READ_CHAR(format++)) != '%') /* Until '%' or '\0' */
835 return (nr_of_chars);
836 put_one_char(format_flag, secret_pointer);
840 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
842 * Optional 'l', 'z' or 'h' modifiers?
844 l_modifier = h_modifier = false;
845 switch (PGM_READ_CHAR(format))
849 /* for the 'z' modifier, we make this assumption */
850 STATIC_ASSERT(sizeof(size_t) == sizeof(long));
860 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
862 switch (format_flag = PGM_READ_CHAR(format++))
865 format_flag = va_arg(ap, int);
867 put_one_char(format_flag, secret_pointer);
872 ptr = va_arg(ap, char *);
873 while ((format_flag = *ptr++))
875 put_one_char(format_flag, secret_pointer);
885 div_val = 0x40000000;
886 goto CONVERSION_LOOP;
893 div_val = 1000000000;
894 goto CONVERSION_LOOP;
902 div_val = 0x10000000;
905 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
908 if (format_flag == 'd')
909 u_val = (short)va_arg(ap, int);
911 u_val = (unsigned short)va_arg(ap, int);
914 u_val = va_arg(ap, long);
917 if (format_flag == 'd')
918 u_val = va_arg(ap, int);
920 u_val = va_arg(ap, unsigned int);
923 #else /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
924 u_val = va_arg(ap,int);
925 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
926 if (format_flag == 'd')
928 if (((int)u_val) < 0)
931 put_one_char('-', secret_pointer);
935 while (div_val > 1 && div_val > u_val)
941 outChar = (u_val / div_val) + '0';
944 if (format_flag == 'x')
945 outChar += 'a'-'9'-1;
947 outChar += 'A'-'9'-1;
949 put_one_char(outChar, secret_pointer);
956 } /* end switch(format_flag...) */
958 #endif /* CONFIG_PRINTF > PRINTF_REDUCED */
961 #endif /* CONFIG_PRINTF */