set errno when getpw*_r, getgr*_r, and getspnam_r fail
[oweals/musl.git] / src / multibyte / wcsnrtombs.c
1 #include <wchar.h>
2
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
9         if (!dst) s = buf, n = sizeof buf;
10         else s = dst;
11
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;
20                 }
21                 if (s != buf) {
22                         s += l;
23                         n -= l;
24                 }
25                 cnt += l;
26         }
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;
33                 }
34                 ws++; wn--;
35                 /* safe - this loop runs fewer than sizeof(buf) times */
36                 s+=l; n-=l;
37                 cnt += l;
38         }
39         if (dst) *wcs = ws;
40         return cnt;
41 }