master
 1#include <wchar.h>
 2#include <limits.h>
 3#include <string.h>
 4
 5size_t wcsnrtombs(char *restrict dst, const wchar_t **restrict wcs, size_t wn, size_t n, mbstate_t *restrict st)
 6{
 7	const wchar_t *ws = *wcs;
 8	size_t cnt = 0;
 9	if (!dst) n=0;
10	while (ws && wn) {
11		char tmp[MB_LEN_MAX];
12		size_t l = wcrtomb(n<MB_LEN_MAX ? tmp : dst, *ws, 0);
13		if (l==-1) {
14			cnt = -1;
15			break;
16		}
17		if (dst) {
18			if (n<MB_LEN_MAX) {
19				if (l>n) break;
20				memcpy(dst, tmp, l);
21			}
22			dst += l;
23			n -= l;
24		}
25		if (!*ws) {
26			ws = 0;
27			break;
28		}
29		ws++;
30		wn--;
31		cnt += l;
32	}
33	if (dst) *wcs = ws;
34	return cnt;
35}