1 #include <wchar.h>
2 
wcsnrtombs(char * restrict dst,const wchar_t ** restrict wcs,size_t wn,size_t n,mbstate_t * restrict st)3 size_t wcsnrtombs(char *restrict dst, const wchar_t **restrict wcs, size_t wn, size_t n, mbstate_t *restrict st)
4 {
5 	size_t l, cnt=0, n2;
6 	char *s, buf[256];
7 	const wchar_t *ws = *wcs;
8 	const wchar_t *tmp_ws;
9 
10 	if (!dst) s = buf, n = sizeof buf;
11 	else s = dst;
12 
13 	while ( ws && n && ( (n2=wn)>=n || n2>32 ) ) {
14 		if (n2>=n) n2=n;
15 		tmp_ws = ws;
16 		l = wcsrtombs(s, &ws, n2, 0);
17 		if (!(l+1)) {
18 			cnt = l;
19 			n = 0;
20 			break;
21 		}
22 		if (s != buf) {
23 			s += l;
24 			n -= l;
25 		}
26 		wn = ws ? wn - (ws - tmp_ws) : 0;
27 		cnt += l;
28 	}
29 	if (ws) while (n && wn) {
30 		l = wcrtomb(s, *ws, 0);
31 		if ((l+1)<=1) {
32 			if (!l) ws = 0;
33 			else cnt = l;
34 			break;
35 		}
36 		ws++; wn--;
37 		/* safe - this loop runs fewer than sizeof(buf) times */
38 		s+=l; n-=l;
39 		cnt += l;
40 	}
41 	if (dst) *wcs = ws;
42 	return cnt;
43 }
44