include cleanups: remove unused headers and add feature test macros
[musl.git] / src / multibyte / wcsrtombs.c
blob5cf8f3eb704753d60b2a778966dd4ae8c28057a4
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 */
7 #include <wchar.h>
9 size_t wcsrtombs(char *restrict s, const wchar_t **restrict ws, size_t n, mbstate_t *restrict st)
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++;
22 return n;
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--;
34 (*ws)++;
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--;
48 (*ws)++;
50 if (n) *s = 0;
51 *ws = 0;
52 return N-n;