• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <errno.h>
9 
wcrtomb(char * restrict s,wchar_t wc,mbstate_t * restrict st)10 size_t wcrtomb(char *restrict s, wchar_t wc, mbstate_t *restrict st)
11 {
12 	if (!s) return 1;
13 	if ((unsigned)wc < 0x80) {
14 		*s = wc;
15 		return 1;
16 	} else if ((unsigned)wc < 0x800) {
17 		*s++ = 0xc0 | (wc>>6);
18 		*s = 0x80 | (wc&0x3f);
19 		return 2;
20 	} else if ((unsigned)wc < 0xd800 || (unsigned)wc-0xe000 < 0x2000) {
21 		*s++ = 0xe0 | (wc>>12);
22 		*s++ = 0x80 | ((wc>>6)&0x3f);
23 		*s = 0x80 | (wc&0x3f);
24 		return 3;
25 	} else if ((unsigned)wc-0x10000 < 0x100000) {
26 		*s++ = 0xf0 | (wc>>18);
27 		*s++ = 0x80 | ((wc>>12)&0x3f);
28 		*s++ = 0x80 | ((wc>>6)&0x3f);
29 		*s = 0x80 | (wc&0x3f);
30 		return 4;
31 	}
32 	errno = EILSEQ;
33 	return -1;
34 }
35