ddc37a57b5c4b54dab0887b739c48cde7fe365c5
[musl] / src / multibyte / wcrtomb.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 <wchar.h>
9 #include <errno.h>
10 #include "internal.h"
11
12 size_t wcrtomb(char *restrict s, wchar_t wc, mbstate_t *restrict st)
13 {
14         if (!s) return 1;
15         if ((unsigned)wc < 0x80) {
16                 *s = wc;
17                 return 1;
18         } else if (MB_CUR_MAX == 1) {
19                 if (!IS_CODEUNIT(wc)) {
20                         errno = EILSEQ;
21                         return -1;
22                 }
23                 *s = wc;
24                 return 1;
25         } else if ((unsigned)wc < 0x800) {
26                 *s++ = 0xc0 | (wc>>6);
27                 *s = 0x80 | (wc&0x3f);
28                 return 2;
29         } else if ((unsigned)wc < 0xd800 || (unsigned)wc-0xe000 < 0x2000) {
30                 *s++ = 0xe0 | (wc>>12);
31                 *s++ = 0x80 | ((wc>>6)&0x3f);
32                 *s = 0x80 | (wc&0x3f);
33                 return 3;
34         } else if ((unsigned)wc-0x10000 < 0x100000) {
35                 *s++ = 0xf0 | (wc>>18);
36                 *s++ = 0x80 | ((wc>>12)&0x3f);
37                 *s++ = 0x80 | ((wc>>6)&0x3f);
38                 *s = 0x80 | (wc&0x3f);
39                 return 4;
40         }
41         errno = EILSEQ;
42         return -1;
43 }