]> git.proxmox.com Git - wasi-libc.git/blob - libc-top-half/musl/src/stdio/vswprintf.c
Disable unused fields in FILE and __libc.
[wasi-libc.git] / libc-top-half / musl / src / stdio / vswprintf.c
1 #include "stdio_impl.h"
2 #include <limits.h>
3 #include <errno.h>
4 #include <stdint.h>
5 #include <stdlib.h>
6 #include <wchar.h>
7
8 struct cookie {
9 wchar_t *ws;
10 size_t l;
11 };
12
13 static size_t sw_write(FILE *f, const unsigned char *s, size_t l)
14 {
15 size_t l0 = l;
16 int i = 0;
17 struct cookie *c = f->cookie;
18 if (s!=f->wbase && sw_write(f, f->wbase, f->wpos-f->wbase)==-1)
19 return -1;
20 while (c->l && l && (i=mbtowc(c->ws, (void *)s, l))>=0) {
21 s+=i;
22 l-=i;
23 c->l--;
24 c->ws++;
25 }
26 *c->ws = 0;
27 if (i < 0) {
28 f->wpos = f->wbase = f->wend = 0;
29 f->flags |= F_ERR;
30 return i;
31 }
32 f->wend = f->buf + f->buf_size;
33 f->wpos = f->wbase = f->buf;
34 return l0;
35 }
36
37 int vswprintf(wchar_t *restrict s, size_t n, const wchar_t *restrict fmt, va_list ap)
38 {
39 int r;
40 unsigned char buf[256];
41 struct cookie c = { s, n-1 };
42 FILE f = {
43 .lbf = EOF,
44 .write = sw_write,
45 #if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)
46 .lock = -1,
47 #endif
48 .buf = buf,
49 .buf_size = sizeof buf,
50 .cookie = &c,
51 };
52
53 if (!n) {
54 return -1;
55 } else if (n > INT_MAX) {
56 errno = EOVERFLOW;
57 return -1;
58 }
59 r = vfwprintf(&f, fmt, ap);
60 sw_write(&f, 0, 0);
61 return r>=n ? -1 : r;
62 }