implement uchar.h (C11 UTF-16/32 conversion) interfaces
[musl] / src / multibyte / mbrtoc16.c
1 #include <uchar.h>
2 #include <wchar.h>
3
4 size_t mbrtoc16(char16_t *restrict pc16, const char *restrict s, size_t n, mbstate_t *restrict ps)
5 {
6         unsigned *pending = (unsigned *)ps;
7
8         if (!s) return mbrtoc16(0, "", 1, ps);
9
10         /* mbrtowc states for partial UTF-8 characters have the high bit set;
11          * we use nonzero states without high bit for pending surrogates. */
12         if ((int)*pending > 0) {
13                 if (pc16) *pc16 = *pending;
14                 *pending = 0;
15                 return -3;
16         }
17
18         wchar_t wc;
19         size_t ret = mbrtowc(&wc, s, n, ps);
20         if (ret <= 4) {
21                 if (wc >= 0x10000) {
22                         *pending = (wc & 0x3ff) + 0xdc00;
23                         wc = 0xd7c0 + (wc >> 10);
24                 }
25                 if (pc16) *pc16 = wc;
26         }
27         return ret;
28 }