implement mbtowc directly, not as a wrapper for mbrtowc
[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 <inttypes.h>
9 #include <wchar.h>
10 #include <errno.h>
11
12 #include "internal.h"
13
14 size_t wcrtomb(char *restrict s, wchar_t wc, mbstate_t *restrict st)
15 {
16         if (!s) return 1;
17         if ((unsigned)wc < 0x80) {
18                 *s = wc;
19                 return 1;
20         } else if ((unsigned)wc < 0x800) {
21                 *s++ = 0xc0 | (wc>>6);
22                 *s = 0x80 | (wc&0x3f);
23                 return 2;
24         } else if ((unsigned)wc < 0xd800 || (unsigned)wc-0xe000 < 0x2000) {
25                 *s++ = 0xe0 | (wc>>12);
26                 *s++ = 0x80 | ((wc>>6)&0x3f);
27                 *s = 0x80 | (wc&0x3f);
28                 return 3;
29         } else if ((unsigned)wc-0x10000 < 0x100000) {
30                 *s++ = 0xf0 | (wc>>18);
31                 *s++ = 0x80 | ((wc>>12)&0x3f);
32                 *s++ = 0x80 | ((wc>>6)&0x3f);
33                 *s = 0x80 | (wc&0x3f);
34                 return 4;
35         }
36         errno = EILSEQ;
37         return -1;
38 }