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 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
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' 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 * PRINTF_FULL 2912byte (0xB60)
55 * PRINTF_NOFLOAT 1684byte (0x694)
56 * PRINTF_REDUCED 924byte (0x39C)
57 * PRINTF_NOMODIFIERS 416byte (0x1A0)
59 * Code/data size in words on DSP56K with CodeWarrior 6.0:
61 * PRINTF_NOFLOAT 795/45
62 * PRINTF_REDUCED 482/0
63 * 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.
81 #include <mware/pgm.h>
82 #include <mware/hex.h>
83 #include <cfg/debug.h> /* ASSERT */
84 #include <appconfig.h> /* CONFIG_ macros */
86 #ifndef CONFIG_PRINTF_N_FORMATTER
87 /** Disable the arcane %n formatter. */
88 #define CONFIG_PRINTF_N_FORMATTER 0
91 #ifndef CONFIG_PRINTF_OCTAL_FORMATTER
92 /** Disable the %o formatter. */
93 #define CONFIG_PRINTF_OCTAL_FORMATTER 0
96 /* True if we must keep a count of the number of characters we print. */
97 #define CONFIG_PRINTF_COUNT_CHARS (CONFIG_PRINTF_RETURN_COUNT || CONFIG_PRINTF_N_FORMATTER)
101 #if CONFIG_PRINTF > PRINTF_NOFLOAT
104 /* Maximum precision for floating point values */
105 typedef long double max_float_t;
107 /*bernie: save some memory, who cares about floats with lots of decimals? */
108 #define FRMWRI_BUFSIZE 134
109 #warning 134 is too much, the code must be fixed to have a lower precision limit
112 * Conservative estimate. Should be (probably) 12 (which is the size necessary
113 * to represent (2^32-1) in octal plus the sign bit.
115 #define FRMWRI_BUFSIZE 16
118 /* Probably useful for fancy microcontrollers such as the PIC, nobody knows. */
119 #ifndef MEM_ATTRIBUTE
120 #define MEM_ATTRIBUTE
123 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
124 #define IS_SHORT (h_modifier || (sizeof(int) == 2 && !l_modifier))
126 #define IS_SHORT (sizeof(int) == 2)
127 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
130 #if CONFIG_PRINTF > PRINTF_NOFLOAT
132 static char *float_conversion(MEM_ATTRIBUTE max_float_t value,
133 MEM_ATTRIBUTE short nr_of_digits,
134 MEM_ATTRIBUTE char *buf,
135 MEM_ATTRIBUTE char format_flag,
136 MEM_ATTRIBUTE char g_flag,
137 MEM_ATTRIBUTE bool alternate_flag)
139 MEM_ATTRIBUTE char *cp;
140 MEM_ATTRIBUTE char *buf_pointer;
141 MEM_ATTRIBUTE short n, i, dec_point_pos, integral_10_log;
148 while (value >= 1e11) /* To speed up things a bit */
151 integral_10_log += 10;
159 else if (value) /* Not just 0.0 */
161 while (value <= 1e-10) /* To speed up things a bit */
164 integral_10_log -= 10;
174 if (integral_10_log < nr_of_digits && integral_10_log >= -4)
177 nr_of_digits -= integral_10_log;
181 /* %#G - No removal of trailing zeros */
184 /* %G - Removal of trailing zeros */
185 alternate_flag = true;
195 /* Less than one... */
196 if (integral_10_log < 0)
198 *buf_pointer++ = '0';
199 if ((n = nr_of_digits) || alternate_flag)
200 *buf_pointer++ = '.';
202 while (--i > integral_10_log && nr_of_digits)
204 *buf_pointer++ = '0';
207 if (integral_10_log < (-n - 1))
208 /* Nothing more to do */
214 dec_point_pos = - integral_10_log;
219 while (i <= nr_of_digits )
221 value -= (max_float_t)(n = (short)value); /* n=Digit value=Remainder */
222 value *= 10; /* Prepare for next shot */
223 *buf_pointer++ = n + '0';
224 if ( ! i++ && (nr_of_digits || alternate_flag))
225 *buf_pointer++ = '.';
228 /* Rounding possible */
232 cp = buf_pointer - 1;
237 if ( (*cp += n) == ('9' + 1) )
245 } while (cp-- > buf);
254 if (*(cp - 1) == '.')
279 /* %G - Remove trailing zeros */
282 while (*(buf_pointer - 1) == '0')
284 if (*(buf_pointer - 1) == '.')
291 *buf_pointer++ = format_flag;
292 if (integral_10_log < 0)
294 *buf_pointer++ = '-';
295 integral_10_log = -integral_10_log;
298 *buf_pointer++ = '+';
304 *buf_pointer++ = (integral_10_log % 10) + '0';
305 integral_10_log /= 10;
306 } while ( integral_10_log || n < 2 );
307 for ( i = n ; n > 0 ; n-- )
308 *(buf_pointer - 11 - i + n) = *(buf_pointer - n);
311 return (buf_pointer);
314 #endif /* CONFIG_PRINTF > PRINTF_NOFLOAT */
317 * This routine forms the core and entry of the formatter.
319 * The conversion performed conforms to the ANSI specification for "printf".
322 PGM_FUNC(_formatted_write)(const char * PGM_ATTR format,
323 void put_one_char(char, void *),
324 void *secret_pointer,
327 #if CONFIG_PRINTF > PRINTF_REDUCED
328 MEM_ATTRIBUTE static char bad_conversion[] = "???";
329 MEM_ATTRIBUTE static char null_pointer[] = "<NULL>";
331 MEM_ATTRIBUTE int precision;
333 #if CONFIG_PRINTF_COUNT_CHARS
334 MEM_ATTRIBUTE int nr_of_chars;
336 MEM_ATTRIBUTE int field_width;
337 MEM_ATTRIBUTE char format_flag;
338 enum PLUS_SPACE_FLAGS {
339 PSF_NONE, PSF_PLUS, PSF_MINUS
343 #if CONFIG_PRINTF_OCTAL_FORMATTER
347 MEM_ATTRIBUTE struct {
348 enum PLUS_SPACE_FLAGS plus_space_flag : 2;
349 #if CONFIG_PRINTF_OCTAL_FORMATTER
350 enum DIV_FACTOR div_factor : 2;
352 enum DIV_FACTOR div_factor : 1;
354 bool left_adjust : 1;
355 bool l_L_modifier : 1;
357 bool alternate_flag : 1;
358 bool nonzero_value : 1;
364 MEM_ATTRIBUTE unsigned long ulong;
366 #if CONFIG_PRINTF > PRINTF_NOFLOAT
367 MEM_ATTRIBUTE max_float_t fvalue;
370 MEM_ATTRIBUTE char *buf_pointer;
371 MEM_ATTRIBUTE char *ptr;
372 MEM_ATTRIBUTE const char *hex;
373 MEM_ATTRIBUTE char buf[FRMWRI_BUFSIZE];
375 #if CONFIG_PRINTF_COUNT_CHARS
378 for (;;) /* Until full format string read */
380 while ((format_flag = PGM_READ_CHAR(format++)) != '%') /* Until '%' or '\0' */
383 #if CONFIG_PRINTF_RETURN_COUNT
384 return (nr_of_chars);
388 put_one_char(format_flag, secret_pointer);
389 #if CONFIG_PRINTF_COUNT_CHARS
393 if (PGM_READ_CHAR(format) == '%') /* %% prints as % */
396 put_one_char('%', secret_pointer);
397 #if CONFIG_PRINTF_COUNT_CHARS
403 flags.left_adjust = false;
404 flags.alternate_flag = false;
405 flags.plus_space_flag = PSF_NONE;
406 flags.zeropad = false;
408 flags.progmem = false;
410 ptr = buf_pointer = &buf[0];
413 /* check for leading '-', '+', ' ','#' or '0' flags */
416 switch (PGM_READ_CHAR(format))
419 if (flags.plus_space_flag)
422 flags.plus_space_flag = PSF_PLUS;
425 flags.left_adjust = true;
428 flags.alternate_flag = true;
431 flags.zeropad = true;
439 /* Optional field width (may be '*') */
440 if (PGM_READ_CHAR(format) == '*')
442 field_width = va_arg(ap, int);
445 field_width = -field_width;
446 flags.left_adjust = true;
453 while (PGM_READ_CHAR(format) >= '0' && PGM_READ_CHAR(format) <= '9')
454 field_width = field_width * 10 + (PGM_READ_CHAR(format++) - '0');
457 if (flags.left_adjust)
458 flags.zeropad = false;
460 /* Optional precision (or '*') */
461 if (PGM_READ_CHAR(format) == '.')
463 if (PGM_READ_CHAR(++format) == '*')
465 precision = va_arg(ap, int);
471 while (PGM_READ_CHAR(format) >= '0' && PGM_READ_CHAR(format) <= '9')
472 precision = precision * 10 + (PGM_READ_CHAR(format++) - '0');
478 /* At this point, "left_adjust" is nonzero if there was
479 * a sign, "zeropad" is 1 if there was a leading zero
480 * and 0 otherwise, "field_width" and "precision"
481 * contain numbers corresponding to the digit strings
482 * before and after the decimal point, respectively,
483 * and "plus_space_flag" is either 0 (no flag) or
484 * contains a plus or space character. If there was no
485 * decimal point, "precision" will be -1.
488 flags.l_L_modifier = false;
489 flags.h_modifier = false;
491 /* Optional 'l','L','z' or 'h' modifier? */
492 switch (PGM_READ_CHAR(format))
497 flags.l_L_modifier = true;
501 flags.h_modifier = true;
507 * At exit from the following switch, we will emit
508 * the characters starting at "buf_pointer" and
511 switch (format_flag = PGM_READ_CHAR(format++))
513 #if CONFIG_PRINTF_N_FORMATTER
515 if (sizeof(short) != sizeof(int))
517 if (sizeof(int) != sizeof(long))
520 *va_arg(ap, short *) = nr_of_chars;
521 else if (flags.l_L_modifier)
522 *va_arg(ap, long *) = nr_of_chars;
524 *va_arg(ap, int *) = nr_of_chars;
529 *va_arg(ap, short *) = nr_of_chars;
531 *va_arg(ap, int *) = nr_of_chars;
536 if (flags.l_L_modifier)
537 *va_arg(ap, long *) = nr_of_chars;
539 *va_arg(ap, int *) = nr_of_chars;
544 buf[0] = va_arg(ap, int);
548 /* Custom formatter for strings in program memory. */
551 flags.progmem = true;
556 if ( !(buf_pointer = va_arg(ap, char *)) )
557 buf_pointer = null_pointer;
562 * Move `ptr' to the last character of the
563 * string that will be actually printed.
569 for (n=0; pgm_read_char(ptr) && n < precision; n++)
574 for (n=0; *ptr && n < precision; n++)
578 #if CONFIG_PRINTF_OCTAL_FORMATTER
580 if (flags.alternate_flag && !precision)
588 if (format_flag == 'p')
589 #if defined(__AVR__) || defined(__I196__) /* 16bit pointers */
590 ulong = (unsigned long)(unsigned short)va_arg(ap, char *);
591 #else /* 32bit pointers */
592 ulong = (unsigned long)va_arg(ap, char *);
593 #endif /* 32bit pointers */
594 else if (flags.l_L_modifier)
595 ulong = va_arg(ap, unsigned long);
596 else if (flags.h_modifier)
597 ulong = (unsigned long)(unsigned short)va_arg(ap, unsigned int);
599 ulong = va_arg(ap, unsigned int);
602 #if CONFIG_PRINTF_OCTAL_FORMATTER
603 (format_flag == 'o') ? DIV_OCT :
605 (format_flag == 'u') ? DIV_DEC : DIV_HEX;
606 flags.plus_space_flag = PSF_NONE;
607 goto INTEGRAL_CONVERSION;
611 if (flags.l_L_modifier)
612 ulong = (unsigned long)(long)va_arg(ap, long);
614 ulong = (unsigned long)(long)va_arg(ap, int);
617 if ((signed long)ulong < 0)
619 flags.plus_space_flag = PSF_MINUS;
620 ulong = (unsigned long)(-((signed long)ulong));
623 flags.div_factor = DIV_DEC;
625 /* Now convert to digits */
627 ptr = buf_pointer = &buf[FRMWRI_BUFSIZE - 1];
628 flags.nonzero_value = (ulong != 0);
630 /* No char if zero and zero precision */
631 if (precision != 0 || flags.nonzero_value)
633 switch (flags.div_factor)
637 *--buf_pointer = hex[ulong % 10];
643 *--buf_pointer = hex[ulong % 16];
646 #if CONFIG_PRINTF_OCTAL_FORMATTER
649 *--buf_pointer = hex[ulong % 8];
656 /* "precision" takes precedence */
659 precision = field_width - (flags.plus_space_flag != PSF_NONE);
660 while (precision > (int)(ptr - buf_pointer))
661 *--buf_pointer = '0';
663 if (flags.alternate_flag && flags.nonzero_value)
665 if (format_flag == 'x' || format_flag == 'X')
667 *--buf_pointer = format_flag;
668 *--buf_pointer = '0';
670 #if CONFIG_PRINTF_OCTAL_FORMATTER
671 else if ((format_flag == 'o') && (*buf_pointer != '0'))
673 *--buf_pointer = '0';
677 ASSERT(buf_pointer >= buf);
680 #if CONFIG_PRINTF > PRINTF_NOFLOAT
689 goto FLOATING_CONVERSION;
701 if (sizeof(double) != sizeof(max_float_t))
703 fvalue = flags.l_L_modifier ?
704 va_arg(ap,max_float_t) : va_arg(ap,double);
707 fvalue = va_arg(ap,max_float_t);
711 flags.plus_space_flag = PSF_MINUS;
714 ptr = float_conversion (fvalue,
716 buf_pointer += field_width,
719 flags.alternate_flag);
722 precision = field_width - (flags.plus_space_flag != PSF_NONE);
723 while (precision > ptr - buf_pointer)
724 *--buf_pointer = '0';
728 #endif /* CONFIG_PRINTF <= PRINTF_NOFLOAT */
730 case '\0': /* Really bad place to find NUL in */
734 /* Undefined conversion! */
735 ptr = buf_pointer = bad_conversion;
736 ptr += sizeof(bad_conversion) - 1;
742 * This part emittes the formatted string to "put_one_char".
745 /* If field_width == 0 then nothing should be written. */
746 precision = ptr - buf_pointer;
748 if ( precision > field_width)
754 n = field_width - precision - (flags.plus_space_flag != PSF_NONE);
757 /* emit any leading pad characters */
758 if (!flags.left_adjust)
761 put_one_char(' ', secret_pointer);
762 #if CONFIG_PRINTF_COUNT_CHARS
767 /* emit flag characters (if any) */
768 if (flags.plus_space_flag)
770 put_one_char(flags.plus_space_flag == PSF_PLUS ? '+' : '-', secret_pointer);
771 #if CONFIG_PRINTF_COUNT_CHARS
779 while (--precision >= 0)
781 put_one_char(pgm_read_char(buf_pointer++), secret_pointer);
782 #if CONFIG_PRINTF_COUNT_CHARS
788 #endif /* CPU_HARVARD */
790 /* emit the string itself */
791 while (--precision >= 0)
793 put_one_char(*buf_pointer++, secret_pointer);
794 #if CONFIG_PRINTF_COUNT_CHARS
800 /* emit trailing space characters */
801 if (flags.left_adjust)
804 put_one_char(' ', secret_pointer);
805 #if CONFIG_PRINTF_COUNT_CHARS
811 #else /* PRINTF_REDUCED starts here */
813 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
814 bool l_modifier, h_modifier;
815 unsigned long u_val, div_val;
817 unsigned int u_val, div_val;
818 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
821 unsigned int nr_of_chars, base;
826 for (;;) /* Until full format string read */
828 while ((format_flag = PGM_READ_CHAR(format++)) != '%') /* Until '%' or '\0' */
831 return (nr_of_chars);
832 put_one_char(format_flag, secret_pointer);
836 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
837 /*=================================*/
838 /* Optional 'l' or 'h' modifiers ? */
839 /*=================================*/
840 l_modifier = h_modifier = false;
841 switch (PGM_READ_CHAR(format))
853 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
855 switch (format_flag = PGM_READ_CHAR(format++))
858 format_flag = va_arg(ap, int);
860 put_one_char(format_flag, secret_pointer);
865 ptr = va_arg(ap, char *);
866 while ((format_flag = *ptr++))
868 put_one_char(format_flag, secret_pointer);
878 div_val = 0x40000000;
879 goto CONVERSION_LOOP;
886 div_val = 1000000000;
887 goto CONVERSION_LOOP;
895 div_val = 0x10000000;
898 #if CONFIG_PRINTF > PRINTF_NOMODIFIERS
900 u_val = (format_flag == 'd') ?
901 (short)va_arg(ap, int) : (unsigned short)va_arg(ap, int);
903 u_val = va_arg(ap, long);
905 u_val = (format_flag == 'd') ?
906 va_arg(ap,int) : va_arg(ap,unsigned int);
907 #else /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
908 u_val = va_arg(ap,int);
909 #endif /* CONFIG_PRINTF > PRINTF_NOMODIFIERS */
910 if (format_flag == 'd')
912 if (((int)u_val) < 0)
915 put_one_char('-', secret_pointer);
919 while (div_val > 1 && div_val > u_val)
925 outChar = (u_val / div_val) + '0';
928 if (format_flag == 'x')
929 outChar += 'a'-'9'-1;
931 outChar += 'A'-'9'-1;
933 put_one_char(outChar, secret_pointer);
940 } /* end switch(format_flag...) */
942 #endif /* CONFIG_PRINTF > PRINTF_REDUCED */
945 #endif /* CONFIG_PRINTF */