diff --git a/sw/lib/include/stdio.h b/sw/lib/include/stdio.h index 3054f08d..afca3607 100644 --- a/sw/lib/include/stdio.h +++ b/sw/lib/include/stdio.h @@ -112,6 +112,14 @@ int fprintf (FILE * file, const char * fmt, ...) int printf (const char * fmt, ...) __attribute__((__format__ (__printf__, 1, 2))); +/** + * @brief Writes formatted string to a char buffer + * @param str char buffer + * @param fmt format string + * @return int number of chars written + */ +int sprintf(char *str, const char *fmt, ...) + __attribute__((__format__ (__printf__, 2, 3))); // ========== Non Standard Functions ========== diff --git a/sw/lib/libcatom/stdio.c b/sw/lib/libcatom/stdio.c index 8d185c9a..0b8ecaca 100644 --- a/sw/lib/libcatom/stdio.c +++ b/sw/lib/libcatom/stdio.c @@ -2,6 +2,7 @@ #include #include #include +#include #define BACKSPACE 0x7f @@ -355,6 +356,39 @@ int printf(const char *fmt, ...) } +static char * __sstream_strbuf = NULL; +static int __sstream_strbuf_writepos = -1; +int __sstream_write(char * bf, uint32_t sz){ + assert(__sstream_strbuf != NULL); + __sstream_strbuf[__sstream_strbuf_writepos++] = bf[0]; + return 0; +} + +int vsprintf(char *str, const char *fmt, va_list args) { + // setup a fake string stream that writes to a string buffer + FILE fake_sstream = {.read=NULL, .write=__sstream_write}; + __sstream_strbuf = str; + __sstream_strbuf_writepos = 0; + + int rv = vfprintf(&fake_sstream, fmt, args); + + // terminate with nullchar + fake_sstream.write("\0", 1); + + // cleanup after we're done + __sstream_strbuf = NULL; + __sstream_strbuf_writepos = -1; + return rv; +} + +int sprintf(char *str, const char *fmt, ...) { + va_list args; + va_start(args, fmt); + int rv = vsprintf(str, fmt, args); + va_end(args); + return rv; +} + void dumphexbuf(char *buf, unsigned len, unsigned base_addr) { const int bpw = 4; // bytes per word