Skip to content
Myr

xsnprintf.c

This file

Path

xsnprintf.c

54 lines · 1.6 KiB · C

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 6a4c416 point at it.

changelog: add missing refDaniel Eklöfbefore adoption6a4c416

lines 1–54why, one step back
1#include "xsnprintf.h"
23#include <errno.h>4#include <limits.h>5#include <stdio.h>6#include "debug.h"78/*9 * ISO C doesn't require vsnprintf(3) to set errno on failure, but10 * POSIX does:11 *12 * "If an output error was encountered, these functions shall return13 * a negative value and set errno to indicate the error."14 *15 * The mandated errors of interest are:16 *17 * - EILSEQ: A wide-character code does not correspond to a valid character18 * - EOVERFLOW: The value of n is greater than INT_MAX19 * - EOVERFLOW: The value to be returned is greater than INT_MAX20 *21 * ISO C11 states:22 *23 * "The vsnprintf function returns the number of characters that would24 * have been written had n been sufficiently large, not counting the25 * terminating null character, or a negative value if an encoding error26 * occurred. Thus, the null-terminated output has been completely27 * written if and only if the returned value is nonnegative and less28 * than n."29 *30 * See also:31 *32 * - ISO C11 §7.21.6.12p333 * - https://pubs.opengroup.org/onlinepubs/9699919799/functions/vsnprintf.html34 * - https://pubs.opengroup.org/onlinepubs/9699919799/functions/snprintf.html35 */36size_t37xvsnprintf(char *restrict buf, size_t n, const char *restrict format, va_list ap)38{39 int len = vsnprintf(buf, n, format, ap);40 if (unlikely(len < 0 || len >= (int)n)) {41 FATAL_ERROR(__func__, (len < 0) ? errno : ENOBUFS);42 }43 return (size_t)len;44}4546size_t47xsnprintf(char *restrict buf, size_t n, const char *restrict format, ...)48{49 va_list ap;50 va_start(ap, format);51 size_t len = xvsnprintf(buf, n, format, ap);52 va_end(ap);53 return len;54}