Skip to content

Commit

Permalink
libcatom: add sprintf
Browse files Browse the repository at this point in the history
  • Loading branch information
saursin committed Dec 31, 2023
1 parent e1fb926 commit 03f236d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
8 changes: 8 additions & 0 deletions sw/lib/include/stdio.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 ==========

Expand Down
34 changes: 34 additions & 0 deletions sw/lib/libcatom/stdio.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include <stdarg.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>

#define BACKSPACE 0x7f

Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 03f236d

Please sign in to comment.