Skip to content

Commit ccdbd6a

Browse files
committed
term.c: add term_snprint function
Add function for printing terms to buffers. Signed-off-by: Davide Bettio <[email protected]>
1 parent 561f330 commit ccdbd6a

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/libAtomVM/term.c

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,13 @@ struct FprintfFun
4444
FILE *stream;
4545
};
4646

47+
struct SnprintfFun
48+
{
49+
PrinterFun base;
50+
int size;
51+
char *buf;
52+
};
53+
4754
const term empty_tuple = 0;
4855

4956
int fprintf_printer(PrinterFun *fun, const char *fmt, ...)
@@ -61,6 +68,23 @@ int fprintf_printer(PrinterFun *fun, const char *fmt, ...)
6168
return ret;
6269
}
6370

71+
int snprintf_printer(PrinterFun *fun, const char *fmt, ...)
72+
{
73+
int ret;
74+
75+
va_list args;
76+
va_start(args, fmt);
77+
78+
struct SnprintfFun *snpf = CONTAINER_OF(fun, struct SnprintfFun, base);
79+
ret = vsnprintf(snpf->buf, snpf->size, fmt, args);
80+
snpf->buf += ret;
81+
snpf->size -= ret;
82+
83+
va_end(args);
84+
85+
return ret;
86+
}
87+
6488
void term_display(FILE *fd, term t, const Context *ctx)
6589
{
6690
term_fprint(fd, t, ctx->global);
@@ -78,6 +102,19 @@ int term_fprint(FILE *stream, term t, const GlobalContext *global)
78102
return term_funprint(&fprintf_fun.base, t, global);
79103
}
80104

105+
int term_snprint(char *buf, size_t size, term t, const GlobalContext *global)
106+
{
107+
struct SnprintfFun snprintf_fun = {
108+
.base = {
109+
.print = snprintf_printer
110+
},
111+
.buf = buf,
112+
.size = size
113+
};
114+
115+
return term_funprint(&snprintf_fun.base, t, global);
116+
}
117+
81118
int term_funprint(PrinterFun *fun, term t, const GlobalContext *global)
82119
{
83120
if (term_is_atom(t)) {

src/libAtomVM/term.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1435,6 +1435,18 @@ int term_funprint(PrinterFun *pf, term t, const GlobalContext *global);
14351435
*/
14361436
int term_fprint(FILE *fd, term t, const GlobalContext *global);
14371437

1438+
/**
1439+
* @brief Write a term to a string as text
1440+
*
1441+
* @details Print any given term to the given buffer.
1442+
* @param buf the buffer where the term will be printed.
1443+
* @param size the buffer size.
1444+
* @param t the term that will be printed.
1445+
* @param global the \c GlobalContext.
1446+
* @returns the number of printed characters.
1447+
*/
1448+
int term_snprint(char *buf, size_t size, term t, const GlobalContext *global);
1449+
14381450
/**
14391451
* @brief Checks if a term is a string (i.e., a list of characters)
14401452
*

0 commit comments

Comments
 (0)