Add alloca_sprintf() macro

This commit is contained in:
Andrew Bettison 2015-03-16 22:33:42 +10:30
parent 00037cf803
commit 72345a3b2f
2 changed files with 19 additions and 3 deletions

17
str.c
View File

@ -893,6 +893,19 @@ int str_to_uint64_interval_ms(const char *str, int64_t *result, const char **aft
return 1;
}
/* Compute the length of the string produced by sprintf(fmt, ...).
@author Andrew Bettison <andrew@servalproject.com>
*/
size_t sprintf_len(const char *fmt, ...)
{
strbuf b = strbuf_local(NULL, 0);
va_list ap;
va_start(ap, fmt);
strbuf_vsprintf(b, fmt, ap);
va_end(ap);
return strbuf_count(b);
}
/* Format a buffer of data as a printable representation, eg: "Abc\x0b\n\0", for display
in log messages.
@author Andrew Bettison <andrew@servalproject.com>
@ -904,9 +917,7 @@ char *toprint(char *dstStr, ssize_t dstBufSiz, const char *srcBuf, size_t srcByt
return dstStr;
}
/* Compute the length of the string produced by toprint(). If dstStrLen == -1 then returns the
exact number of characters in the printable representation (excluding the terminating nul),
otherwise returns dstStrLen.
/* Compute the length of the string produced by toprint().
@author Andrew Bettison <andrew@servalproject.com>
*/
size_t toprint_len(const char *srcBuf, size_t srcBytes, const char quotes[2])

5
str.h
View File

@ -283,6 +283,11 @@ __SERVAL_DNA__STR_INLINE int hexvalue(char c) {
return isxdigit(c) ? _serval_ctype_1[(unsigned char) c] & _SERVAL_CTYPE_1_HEX_MASK : -1;
}
/* -------------------- In-line string formatting -------------------- */
size_t sprintf_len(const char *fmt, ...);
#define alloca_sprintf(dstlen, fmt,...) strbuf_str(strbuf_sprintf(strbuf_alloca((dstlen) == -1 ? sprintf_len((fmt), ##__VA_ARGS__) + 1 : (size_t)(dstlen)), (fmt), ##__VA_ARGS__))
/* -------------------- Printable string representation -------------------- */
char *toprint(char *dstStr, ssize_t dstBufSiz, const char *srcBuf, size_t srcBytes, const char quotes[2]);