diff options
| author | Craig Barnes <craigbarnes@protonmail.com> | 2021-01-14 21:30:06 +0000 |
|---|---|---|
| committer | Craig Barnes <craigbarnes@protonmail.com> | 2021-01-14 21:30:06 +0000 |
| commit | 3f4cfa338b5035b3789ea414eab9f139a18d140b (patch) | |
| tree | b4694f0f3410edcaff64481e62d54dbdfc1993d8 /xsnprintf.c | |
| parent | Merge branch 'selection-extend-force-character-wise' (diff) | |
Add xsnprintf() and remove some unnecessary strlen(3) calls
Diffstat (limited to 'xsnprintf.c')
| -rw-r--r-- | xsnprintf.c | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/xsnprintf.c b/xsnprintf.c new file mode 100644 index 00000000..e8e8d25d --- /dev/null +++ b/xsnprintf.c @@ -0,0 +1,36 @@ +#include "xsnprintf.h" + +#include <assert.h> +#include <limits.h> +#include <stdio.h> + +size_t +xvsnprintf(char *buf, size_t n, const char *format, va_list ap) +{ + assert(n <= INT_MAX); + int len = vsnprintf(buf, n, format, ap); + + /* + * ISO C11 ยง7.21.6.5 states: + * "The snprintf function returns the number of characters that + * would have been written had n been sufficiently large, not + * counting the terminating null character, or a negative value + * if an encoding error occurred. Thus, the null-terminated output + * has been completely written if and only if the returned value + * is nonnegative and less than n." + */ + assert(len >= 0); + assert(len < (int)n); + + return (size_t)len; +} + +size_t +xsnprintf(char *buf, size_t n, const char *format, ...) +{ + va_list ap; + va_start(ap, format); + size_t len = xvsnprintf(buf, n, format, ap); + va_end(ap); + return len; +} |
