simplify/refactor fflush and make fflush_unlocked an alias for fflush
[musl.git] / src / multibyte / wcsnrtombs.c
blob640cbbeb5416dae49143ba713d689c781979a842
1 #include <wchar.h>
3 size_t wcsnrtombs(char *restrict dst, const wchar_t **restrict wcs, size_t wn, size_t n, mbstate_t *restrict st)
5 size_t l, cnt=0, n2;
6 char *s, buf[256];
7 const wchar_t *ws = *wcs;
9 if (!dst) s = buf, n = sizeof buf;
10 else s = dst;
12 while ( ws && n && ( (n2=wn)>=n || n2>32 ) ) {
13 if (n2>=n) n2=n;
14 wn -= n2;
15 l = wcsrtombs(s, &ws, n2, 0);
16 if (!(l+1)) {
17 cnt = l;
18 n = 0;
19 break;
21 if (s != buf) {
22 s += l;
23 n -= l;
25 cnt += l;
27 if (ws) while (n && wn) {
28 l = wcrtomb(s, *ws, 0);
29 if ((l+1)<=1) {
30 if (!l) ws = 0;
31 else cnt = l;
32 break;
34 ws++; wn--;
35 /* safe - this loop runs fewer than sizeof(buf) times */
36 s+=l; n-=l;
37 cnt += l;
39 if (dst) *wcs = ws;
40 return cnt;