1#include <wchar.h> 2 3size_t mbsnrtowcs(wchar_t *restrict wcs, const char **restrict src, size_t n, size_t wn, mbstate_t *restrict st) 4{ 5 size_t l, cnt=0, n2; 6 wchar_t *ws, wbuf[256]; 7 const char *s = *src; 8 9 if (!wcs) ws = wbuf, wn = sizeof wbuf / sizeof *wbuf; 10 else ws = wcs; 11 12 /* making sure output buffer size is at most n/4 will ensure 13 * that mbsrtowcs never reads more than n input bytes. thus 14 * we can use mbsrtowcs as long as it's practical.. */ 15 16 while ( s && wn && ( (n2=n/4)>=wn || n2>32 ) ) { 17 if (n2>=wn) n2=wn; 18 n -= n2; 19 l = mbsrtowcs(ws, &s, n2, st); 20 if (!(l+1)) { 21 cnt = l; 22 wn = 0; 23 break; 24 } 25 if (ws != wbuf) { 26 ws += l; 27 wn -= l; 28 } 29 cnt += l; 30 } 31 if (s) while (wn && n) { 32 l = mbrtowc(ws, s, n, st); 33 if (l+2<=2) { 34 if (!(l+1)) { 35 cnt = l; 36 break; 37 } 38 if (!l) { 39 s = 0; 40 break; 41 } 42 /* have to roll back partial character */ 43 *(unsigned *)st = 0; 44 break; 45 } 46 s += l; n -= l; 47 /* safe - this loop runs fewer than sizeof(wbuf)/8 times */ 48 ws++; wn--; 49 cnt++; 50 } 51 if (wcs) *src = s; 52 return cnt; 53} 54