summaryrefslogtreecommitdiff
path: root/src/stdio/vsnprintf.c
blob: 5d3f0c5f1977cd23cb95abd21f529d73beb08258 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "stdio_impl.h"

static size_t sn_write(FILE *f, const unsigned char *s, size_t l)
{
	/* pretend to succeed, but discard data */
	return l;
}

int vsnprintf(char *s, size_t n, const char *fmt, va_list ap)
{
	int r;
	FILE f;
	unsigned char buf[1];

	memset(&f, 0, sizeof(FILE));
	f.lbf = EOF;
	f.write = sn_write;
	f.buf_size = 1;
	f.buf = buf;
	f.lock = -1;
	if (n > INT_MAX) {
		errno = EOVERFLOW;
		return -1;
	} else if (n > 0) {
		if (n > (char *)0+SIZE_MAX-s) n = (char *)0+SIZE_MAX-s;
		f.wpos = s;
		f.wbase = f.wend = s+n-1;
		f.wstop = f.wend - 1;
	}
	r = vfprintf(&f, fmt, ap);
	/* wpos points just after last byte written, or to s+n-1 (wbase) */
	*f.wpos = 0;
	return r;
}