include cleanups: remove unused headers and add feature test macros
[musl] / src / multibyte / wcsrtombs.c
1 /* 
2  * This code was written by Rich Felker in 2010; no copyright is claimed.
3  * This code is in the public domain. Attribution is appreciated but
4  * unnecessary.
5  */
6
7 #include <wchar.h>
8
9 size_t wcsrtombs(char *restrict s, const wchar_t **restrict ws, size_t n, mbstate_t *restrict st)
10 {
11         const wchar_t *ws2;
12         char buf[4];
13         size_t N = n, l;
14         if (!s) {
15                 for (n=0, ws2=*ws; *ws2; ws2++) {
16                         if (*ws2 >= 0x80u) {
17                                 l = wcrtomb(buf, *ws2, 0);
18                                 if (!(l+1)) return -1;
19                                 n += l;
20                         } else n++;
21                 }
22                 return n;
23         }
24         while (n>=4 && **ws) {
25                 if (**ws >= 0x80u) {
26                         l = wcrtomb(s, **ws, 0);
27                         if (!(l+1)) return -1;
28                         s += l;
29                         n -= l;
30                 } else {
31                         *s++ = **ws;
32                         n--;
33                 }
34                 (*ws)++;
35         }
36         while (n && **ws) {
37                 if (**ws >= 0x80u) {
38                         l = wcrtomb(buf, **ws, 0);
39                         if (!(l+1)) return -1;
40                         if (l>n) return N-n;
41                         wcrtomb(s, **ws, 0);
42                         s += l;
43                         n -= l;
44                 } else {
45                         *s++ = **ws;
46                         n--;
47                 }
48                 (*ws)++;
49         }
50         if (n) *s = 0;
51         *ws = 0;
52         return N-n;
53 }