diff --git a/os/various/chprintf.c b/os/various/chprintf.c index 5d3d38e78..1188df8ff 100644 --- a/os/various/chprintf.c +++ b/os/various/chprintf.c @@ -29,6 +29,7 @@ #include "ch.h" #include "chprintf.h" +#include "memstreams.h" #define MAX_FILLER 11 #define FLOAT_PRECISION 100000 @@ -259,4 +260,48 @@ unsigned_common: } } +/** + * @brief System formatted output function. + * @details This function implements a minimal @p vprintf()-like functionality + * with output on a @p BaseSequentialStream. + * The general parameters format is: %[-][width|*][.precision|*][l|L]p. + * The following parameter types (p) are supported: + * - x hexadecimal integer. + * - X hexadecimal long. + * - o octal integer. + * - O octal long. + * - d decimal signed integer. + * - D decimal signed long. + * - u decimal unsigned integer. + * - U decimal unsigned long. + * - c character. + * - s string. + * . + * + * @param[in] str pointer to a buffer + * @param[in] size maximum size of the buffer + * @param[in] fmt formatting string + * @param[in] ap list of parameters + * + * @api + */ +int chsnprintf(char *str, size_t size, const char *fmt, ...) { + va_list ap; + MemoryStream ms; + BaseSequentialStream *chp; + + /* Memory stream object to be used as a string writer.*/ + msObjectInit(&ms, (uint8_t *)str, size, 0); + + /* Performing the print operation using the common code.*/ + chp = (BaseSequentialStream *)&ms; + va_start(ap, fmt); + chvprintf(chp, fmt, ap); + va_end(ap); + + /* Final zero and size return.*/ + chSequentialStreamPut(chp, 0); + return ms.eos - 1; +} + /** @} */ diff --git a/os/various/chprintf.h b/os/various/chprintf.h index 306adc988..591f98130 100644 --- a/os/various/chprintf.h +++ b/os/various/chprintf.h @@ -38,6 +38,7 @@ extern "C" { #endif void chvprintf(BaseSequentialStream *chp, const char *fmt, va_list ap); + int chsnprintf(char *str, size_t size, const char *fmt, ...); #ifdef __cplusplus } #endif diff --git a/os/various/memstreams.h b/os/various/memstreams.h index 3daa8ee92..ff2fc464f 100644 --- a/os/various/memstreams.h +++ b/os/various/memstreams.h @@ -84,7 +84,8 @@ typedef struct { #ifdef __cplusplus extern "C" { #endif - void msObjectInit(MemoryStream *msp, uint8_t *buffer, size_t size, size_t eos); + void msObjectInit(MemoryStream *msp, uint8_t *buffer, + size_t size, size_t eos); #ifdef __cplusplus } #endif diff --git a/readme.txt b/readme.txt index aaad8b84e..fc571b456 100644 --- a/readme.txt +++ b/readme.txt @@ -135,7 +135,7 @@ (backported to 2.6.0). - FIX: Fixed MS2ST() and US2ST() macros error (bug #415)(backported to 2.6.0, 2.4.4, 2.2.10, NilRTOS). -- NEW: Added chvprintf() function to the chprintf module. +- NEW: Added chvprintf() and chsnprintf() functions to the chprintf module. - NEW: Improved time range check in the kernel, new API chTimeElapsedSince() introduced. The API chTimeIsWithin() is now a macro. - NEW: Added a new function shellExit() to the shell. It allows to exit the