mbtowc.c (599B)
1 #include <stdlib.h> 2 3 #undef mbtowc 4 5 int 6 mbtowc(wchar_t *restrict pwc, const char *restrict s, size_t n) 7 { 8 unsigned char *t = (unsigned char *) s; 9 unsigned long wc; 10 unsigned c; 11 size_t len; 12 13 if (s == NULL) 14 return 0; 15 16 wc = c = *t++; 17 for (len = 0; n > 0 && c & 0x80; --n, ++len) 18 c <<= 1; 19 if (n == 0 || len == 1 || len == 8) 20 return -1; 21 if (len == 0) 22 goto return_code; 23 24 for (wc = (c & 0xFF) >> len; len--; wc |= c & 0x3F) { 25 if ((c = *t++) & 0xC0 != 0x80) 26 return -1; 27 wc <<= 6; 28 } 29 30 return_code: 31 if (pwc) 32 *pwc = wc; 33 if (*s == '\0') 34 return 0; 35 return t - (unsigned char *) s; 36 }