initial check-in, version 0.5.0
[musl] / src / multibyte / wcsnrtombs.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 <stdlib.h>
8 #include <inttypes.h>
9 #include <wchar.h>
10 #include <errno.h>
11
12 #include "internal.h"
13
14 size_t wcsnrtombs(char *dst, const wchar_t **wcs, size_t wn, size_t n, mbstate_t *st)
15 {
16         size_t l, cnt=0, n2;
17         char *s, buf[256];
18         const wchar_t *ws = *wcs;
19
20         if (!dst) s = buf, n = sizeof buf;
21         else s = dst;
22
23         while ( n && ( (n2=wn)>=n || n2>32 ) ) {
24                 if (n2>=n) n2=n;
25                 wn -= n2;
26                 l = wcsrtombs(s, &ws, n2, 0);
27                 if (!(l+1)) {
28                         cnt = l;
29                         n = 0;
30                         break;
31                 }
32                 if (s != buf) {
33                         s += l;
34                         n -= l;
35                 }
36                 cnt += l;
37         }
38         while (n && wn) {
39                 l = wcrtomb(s, *ws, 0);
40                 if (!(l+1)) {
41                         cnt = l;
42                         break;
43                 }
44                 ws++; wn--;
45                 /* safe - this loop runs fewer than sizeof(buf) times */
46                 s+=l; n-=l;
47                 cnt++;
48         }
49         if (dst) *wcs = ws;
50         return cnt;
51 }